zcodeProtocol.test.ts 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. DEFAULT_ZCODE_MODEL_CONTEXT_BUDGET_STRATEGY,
  4. ZCODE_PROTOCOL_NAME,
  5. ZCODE_PROTOCOL_VERSION,
  6. zcodeComputerUseOperationEventSchema,
  7. zcodeProviderRuntimeHeadersRequestParamsSchema,
  8. zcodeProviderRuntimeHeadersResponseSchema,
  9. zcodeProtocolMethods,
  10. zcodeProtocolMessageSchema,
  11. zcodeProcessResourceSampleSchema,
  12. zcodeProtocolNotifications,
  13. zcodeMcpListParamsSchema,
  14. zcodeModelFormatPropertiesSchema,
  15. zcodeMcpTelemetryEventSchema,
  16. zcodeSessionCreateParamsSchema,
  17. zcodeSessionCompactParamsSchema,
  18. zcodeSessionEventSchema,
  19. zcodeSessionEventsResultSchema,
  20. zcodeSessionResumeParamsSchema,
  21. zcodeSessionSubagentsParamsSchema,
  22. zcodeSessionSubagentsResultSchema,
  23. zcodeSessionSendParamsSchema,
  24. zcodeSessionSetModelParamsSchema,
  25. zcodeSessionSetThoughtLevelParamsSchema,
  26. zcodeSessionRuntimePreferencesResultSchema,
  27. zcodeSessionSettingsStateSchema,
  28. zcodeSessionStateSnapshotSchema,
  29. zcodeStateUpdatedNotificationSchema,
  30. zcodeWorkspacePresentationSchema,
  31. zcodeWorkspaceReadPresentationParamsSchema,
  32. zcodeWorkspaceUpdateInteractionPreferencesParamsSchema,
  33. zcodeWorkspaceUpdateInteractionPreferencesResultSchema,
  34. zcodeWorkspaceUpdateModelIoPreferencesParamsSchema,
  35. zcodeWorkspaceUpdateModelIoPreferencesResultSchema,
  36. zcodeAutomationCreateParamsSchema,
  37. zcodeAutomationCheckTaskBindingParamsSchema,
  38. zcodeAutomationCheckTaskBindingResultSchema,
  39. zcodeAutomationUpdateParamsSchema,
  40. zcodeAutomationProtocolSchema,
  41. } from "../src/zcode-protocol/index.js";
  42. import {
  43. APP_RUNTIME_PREFERENCES_CHANGED_BROADCAST_CHANNEL,
  44. appRuntimePreferencesChangedBroadcastPayloadSchema,
  45. } from "../src/app-runtime-preferences.js";
  46. import {
  47. isAuxiliarySessionKind,
  48. isReadonlyAgentSessionKind,
  49. zcodeUserMessageInfoSchema,
  50. } from "../src/zcode-protocol-legacy-types.js";
  51. import { conversationRowSchema, workflowLaunchMetaSchema } from "../src/zcode-protocol-v4/rows.js";
  52. import { errorAttributionSchema } from "../src/zcode-protocol-v4/snapshot.js";
  53. const workspace = {
  54. workspacePath: "/workspace/app",
  55. workspaceIdentity: "remote:ssh:dev:/workspace/app",
  56. workspaceKey: "remote:ssh:dev:/workspace/app",
  57. };
  58. const model = {
  59. providerId: "glm",
  60. modelId: "glm-4.6",
  61. };
  62. const modelProperties = {
  63. inputFormat: {
  64. supportsText: true,
  65. supportsImage: false,
  66. supportsVideo: false,
  67. supportsAudio: false,
  68. supportsPdf: true,
  69. },
  70. outputFormat: { supportsText: true },
  71. };
  72. describe("ZCode Protocol", () => {
  73. it("模型格式能力只接受完整的嵌套 properties 契约", () => {
  74. const properties = {
  75. inputFormat: {
  76. supportsText: true,
  77. supportsImage: false,
  78. supportsVideo: false,
  79. supportsAudio: false,
  80. supportsPdf: true,
  81. },
  82. outputFormat: { supportsText: true },
  83. };
  84. expect(zcodeModelFormatPropertiesSchema.parse(properties)).toEqual(properties);
  85. expect(() =>
  86. zcodeModelFormatPropertiesSchema.parse({
  87. supportsImages: true,
  88. supportsPdf: true,
  89. supportsVideo: false,
  90. }),
  91. ).toThrow();
  92. expect(() =>
  93. zcodeModelFormatPropertiesSchema.parse({
  94. inputFormat: {
  95. supportsText: true,
  96. supportsImage: false,
  97. supportsVideo: false,
  98. supportsPdf: true,
  99. },
  100. outputFormat: { supportsText: true },
  101. }),
  102. ).toThrow();
  103. });
  104. it("普通 Session 命令拒绝 Host runtimeModel 快照", () => {
  105. const runtimeModel = {
  106. revision: "model-runtime:test",
  107. generatedAt: 1,
  108. model,
  109. provider: {
  110. providerId: model.providerId,
  111. kind: "anthropic",
  112. apiFormat: "anthropic-messages",
  113. baseURL: "https://example.com",
  114. models: [{ modelId: model.modelId }],
  115. },
  116. };
  117. const payloads = [
  118. [zcodeSessionCreateParamsSchema, { workspace, model, runtimeModel }],
  119. [zcodeSessionResumeParamsSchema, { sessionId: "session-1", runtimeModel }],
  120. [
  121. zcodeSessionSendParamsSchema,
  122. {
  123. sessionId: "session-1",
  124. content: "hello",
  125. expectedModelRuntimeRevision: runtimeModel.revision,
  126. runtimeModel,
  127. },
  128. ],
  129. [zcodeSessionCompactParamsSchema, { sessionId: "session-1", runtimeModel }],
  130. [zcodeSessionSetModelParamsSchema, { sessionId: "session-1", model, runtimeModel }],
  131. [
  132. zcodeSessionSetThoughtLevelParamsSchema,
  133. { sessionId: "session-1", thoughtLevel: "high", runtimeModel },
  134. ],
  135. ] as const;
  136. for (const [schema, payload] of payloads) {
  137. expect(() => schema.parse(payload)).toThrow();
  138. }
  139. });
  140. it("accepts only bounded process resource samples without workspace or session identity", () => {
  141. const sample = {
  142. arch: "arm64",
  143. cpuCores: 2.5,
  144. cpuPercent: 31.25,
  145. intervalMs: 60_000,
  146. logicalCpuCount: 8,
  147. platform: "darwin",
  148. rssKb: 65_536,
  149. };
  150. expect(zcodeProtocolNotifications.processResourceSample).toBe("process/resourceSample");
  151. // PRT-025:旧 CLI 发来的样本没有新字段,仍必须通过校验(新增字段全部可选,握手版本不递增)。
  152. expect(zcodeProcessResourceSampleSchema.parse(sample)).toEqual(sample);
  153. const sampleWithTelemetryFields = {
  154. ...sample,
  155. heapUsedKb: 20_480,
  156. uptimeMinutes: 12,
  157. totalMemoryGb: 16,
  158. instanceToken: "9f2c4a1b7d0e5638",
  159. };
  160. expect(zcodeProcessResourceSampleSchema.parse(sampleWithTelemetryFields)).toEqual(
  161. sampleWithTelemetryFields,
  162. );
  163. // lane 由 app 侧 services 按所属进程管理器打标,CLI 不知道自己的 lane,也不允许自报。
  164. expect(() => zcodeProcessResourceSampleSchema.parse({ ...sample, lane: "chat" })).toThrow();
  165. // instanceToken 只用于 main 统计进程数,绝不能被拿来夹带 pid、路径或 workspace 标识。
  166. expect(() =>
  167. zcodeProcessResourceSampleSchema.parse({ ...sample, instanceToken: "/private/repo" }),
  168. ).toThrow();
  169. expect(() =>
  170. zcodeProcessResourceSampleSchema.parse({ ...sample, instanceToken: "" }),
  171. ).toThrow();
  172. expect(() => zcodeProcessResourceSampleSchema.parse({ ...sample, heapUsedKb: -1 })).toThrow();
  173. expect(() =>
  174. zcodeProcessResourceSampleSchema.parse({ ...sample, uptimeMinutes: 1.5 }),
  175. ).toThrow();
  176. expect(() =>
  177. zcodeProcessResourceSampleSchema.parse({
  178. ...sample,
  179. workspacePath: "/private/repo",
  180. }),
  181. ).toThrow();
  182. expect(() =>
  183. zcodeProcessResourceSampleSchema.parse({
  184. ...sample,
  185. cpuCores: Number.NaN,
  186. }),
  187. ).toThrow();
  188. expect(() =>
  189. zcodeProcessResourceSampleSchema.parse({
  190. ...sample,
  191. logicalCpuCount: 0,
  192. }),
  193. ).toThrow();
  194. });
  195. it("accepts only the four privacy-bounded MCP telemetry events", () => {
  196. const base = {
  197. arch: "arm64",
  198. occurredAt: 1_000,
  199. platform: "darwin",
  200. } as const;
  201. const events = [
  202. {
  203. ...base,
  204. kind: "process_start",
  205. mcpId: "builtin:node_repl",
  206. mcpInstanceId: "mcp-instance-1",
  207. mcpIsolation: "workspace",
  208. mcpSource: "builtin",
  209. },
  210. {
  211. ...base,
  212. kind: "process_start",
  213. mcpId: "builtin:zcode-cua:computer-use",
  214. mcpInstanceId: "mcp-instance-2",
  215. mcpIsolation: "session",
  216. mcpSource: "builtin",
  217. },
  218. {
  219. ...base,
  220. kind: "process_start",
  221. mcpId: "builtin:document-skills:image%20search%2F%E9%AB%98%E6%B8%85",
  222. mcpInstanceId: "mcp-instance-3",
  223. mcpIsolation: "session",
  224. mcpSource: "builtin",
  225. },
  226. {
  227. ...base,
  228. affectedSessionCount: 2,
  229. exitCode: 1,
  230. kind: "process_crash",
  231. mcpId: "builtin:node_repl",
  232. mcpInstanceId: "mcp-instance-1",
  233. mcpIsolation: "workspace",
  234. mcpSource: "builtin",
  235. signal: null,
  236. uptimeMs: 10_000,
  237. },
  238. {
  239. ...base,
  240. configuredCount: 3,
  241. connectedCount: 2,
  242. failedCount: 1,
  243. kind: "session_startup",
  244. processCount: 1,
  245. sessionId: "session-1",
  246. },
  247. {
  248. ...base,
  249. kind: "memory",
  250. mcpId: "custom:123456789abc",
  251. mcpInstanceId: "mcp-instance-2",
  252. mcpIsolation: "session",
  253. mcpSource: "custom",
  254. memoryKb: 65_536,
  255. memoryScope: "process_tree",
  256. orphanSuspected: true,
  257. ownerSessionCount: 0,
  258. unownedSeconds: 60.001,
  259. },
  260. ];
  261. expect(zcodeProtocolNotifications.mcpTelemetry).toBe("process/mcpTelemetry");
  262. expect(events.map((event) => zcodeMcpTelemetryEventSchema.parse(event))).toEqual(events);
  263. expect(() =>
  264. zcodeMcpTelemetryEventSchema.parse({
  265. ...events[0],
  266. mcpServerName: "private-company-server",
  267. }),
  268. ).toThrow();
  269. });
  270. it("accepts a default thought level in session settings", () => {
  271. expect(
  272. zcodeSessionSettingsStateSchema.parse({
  273. model: {
  274. current: model,
  275. available: [{ ref: model, label: "GLM 4.6", properties: modelProperties }],
  276. },
  277. thoughtLevel: {
  278. enabled: true,
  279. current: undefined,
  280. defaultLevel: "max",
  281. available: [
  282. { value: "high", label: "High" },
  283. { value: "max", label: "Max" },
  284. ],
  285. },
  286. mode: {
  287. current: "build",
  288. },
  289. }),
  290. ).toMatchObject({
  291. thoughtLevel: {
  292. defaultLevel: "max",
  293. },
  294. });
  295. });
  296. it("uses reasoning presence as support and rejects removed model-option projections", () => {
  297. const currentModelOption = {
  298. ref: model,
  299. label: "GLM 4.6",
  300. properties: modelProperties,
  301. reasoning: { levels: [{ value: "high", label: "High" }] },
  302. };
  303. expect(
  304. zcodeSessionSettingsStateSchema.parse({
  305. model: { current: model, available: [currentModelOption] },
  306. thoughtLevel: { enabled: true, available: [], current: undefined },
  307. mode: { current: "build" },
  308. }).model.available[0]?.reasoning?.levels,
  309. ).toHaveLength(1);
  310. for (const removedField of [
  311. "providerSource",
  312. "providerLogoUrl",
  313. "supportsTools",
  314. "supportsStructuredOutput",
  315. "supportsJsonSchemaOutput",
  316. ]) {
  317. expect(() =>
  318. zcodeSessionSettingsStateSchema.parse({
  319. model: {
  320. current: model,
  321. available: [{ ...currentModelOption, [removedField]: true }],
  322. },
  323. thoughtLevel: { enabled: true, available: [], current: undefined },
  324. mode: { current: "build" },
  325. }),
  326. ).toThrow();
  327. }
  328. expect(() =>
  329. zcodeSessionSettingsStateSchema.parse({
  330. model: {
  331. current: model,
  332. available: [{ ...currentModelOption, reasoning: { enabled: true, levels: [] } }],
  333. },
  334. thoughtLevel: { enabled: true, available: [], current: undefined },
  335. mode: { current: "build" },
  336. }),
  337. ).toThrow();
  338. });
  339. it("validates the dedicated app runtime preference broadcast payload", () => {
  340. expect(APP_RUNTIME_PREFERENCES_CHANGED_BROADCAST_CHANNEL).toBe(
  341. "settings:app-runtime-preferences",
  342. );
  343. expect(
  344. appRuntimePreferencesChangedBroadcastPayloadSchema.parse({
  345. askUserQuestionAutoResolutionEnabled: false,
  346. }),
  347. ).toEqual({
  348. askUserQuestionAutoResolutionEnabled: false,
  349. modelIoFullRetentionEnabled: false,
  350. });
  351. expect(() =>
  352. appRuntimePreferencesChangedBroadcastPayloadSchema.parse({
  353. askUserQuestionAutoResolutionEnabled: false,
  354. ignored: true,
  355. }),
  356. ).toThrow();
  357. });
  358. it("accepts bounded browser ambient context on session/send while staying strict", () => {
  359. expect(
  360. zcodeSessionSendParamsSchema.parse({
  361. sessionId: "sess_1",
  362. content: "continue",
  363. browserAmbientContext: {
  364. tabCount: 1,
  365. currentUrl: "https://example.com/current?q=1",
  366. },
  367. }).browserAmbientContext,
  368. ).toEqual({ tabCount: 1, currentUrl: "https://example.com/current?q=1" });
  369. expect(() =>
  370. zcodeSessionSendParamsSchema.parse({
  371. sessionId: "sess_1",
  372. content: "continue",
  373. browserAmbientContext: { tabCount: 0 },
  374. }),
  375. ).toThrow();
  376. expect(() =>
  377. zcodeSessionSendParamsSchema.parse({
  378. sessionId: "sess_1",
  379. content: "continue",
  380. browserAmbientContext: { tabCount: 1, pageText: "secret" },
  381. }),
  382. ).toThrow();
  383. });
  384. it("session/send accepts Off-Peak turn attribution but rejects competing automation identity", () => {
  385. expect(
  386. zcodeSessionSendParamsSchema.parse({
  387. sessionId: "sess_1",
  388. content: "continue",
  389. offPeakTaskId: "offpeak-1",
  390. offPeakRunType: "resume",
  391. }),
  392. ).toMatchObject({ offPeakTaskId: "offpeak-1", offPeakRunType: "resume" });
  393. expect(() =>
  394. zcodeSessionSendParamsSchema.parse({
  395. sessionId: "sess_1",
  396. content: "invalid",
  397. offPeakRunType: "init",
  398. }),
  399. ).toThrow();
  400. expect(() =>
  401. zcodeSessionSendParamsSchema.parse({
  402. sessionId: "sess_1",
  403. content: "continue",
  404. automationId: "automation-1",
  405. offPeakTaskId: "offpeak-1",
  406. }),
  407. ).toThrow();
  408. });
  409. it("session/send and automation/create validate the bot delivery target strictly", () => {
  410. const botDeliveryTarget = {
  411. provider: "weixin" as const,
  412. botId: "bot-weixin",
  413. providerUserId: "chat-1",
  414. chatType: "private" as const,
  415. };
  416. expect(
  417. zcodeSessionSendParamsSchema.parse({
  418. sessionId: "sess_1",
  419. content: "创建定时任务",
  420. botDeliveryTarget,
  421. }).botDeliveryTarget,
  422. ).toEqual(botDeliveryTarget);
  423. expect(
  424. zcodeAutomationCreateParamsSchema.parse({
  425. cronExpr: "0 9 * * *",
  426. prompt: "日报",
  427. botDeliveryTarget,
  428. }).botDeliveryTarget,
  429. ).toEqual(botDeliveryTarget);
  430. expect(() =>
  431. zcodeAutomationCreateParamsSchema.parse({
  432. cronExpr: "0 9 * * *",
  433. prompt: "日报",
  434. botDeliveryTarget: { ...botDeliveryTarget, provider: "discord" },
  435. }),
  436. ).toThrow();
  437. });
  438. it("keeps protocol methods session-first and private", () => {
  439. const methods = Object.values(zcodeProtocolMethods);
  440. expect(methods).not.toContain("capabilities");
  441. expect(methods.every((method) => !method.includes("task"))).toBe(true);
  442. expect(methods).toContain("session/read");
  443. expect(methods).toContain("session/usage");
  444. expect(methods).toContain("session/subagents");
  445. expect(methods).toContain("session/setModel");
  446. expect(methods).toContain("session/cancelBackgroundTask");
  447. expect(methods).toContain("workspace/readPresentation");
  448. expect(methods).not.toContain("workspace/readState");
  449. expect(methods).not.toContain("workspace/setDefaultModel");
  450. expect(methods).not.toContain("workspace/setDefaultThoughtLevel");
  451. expect(methods).toContain("automation/create");
  452. expect(methods).toContain("automation/update");
  453. });
  454. it("validates the strict Computer Use operation lifecycle notification", () => {
  455. expect(zcodeProtocolMethods.computerUseOperationEvent).toBe("computer-use/operation-event");
  456. const base = {
  457. eventId: "evt-1",
  458. sequenceNumber: 1,
  459. sessionId: "sess-1",
  460. timestamp: 1_700_000_000_000,
  461. };
  462. for (const event of [
  463. { ...base, kind: "turn-started", turnId: "turn-1" },
  464. { ...base, kind: "turn-completed", turnId: "turn-1" },
  465. { ...base, kind: "turn-failed", turnId: "turn-1" },
  466. {
  467. ...base,
  468. kind: "tool-scheduled",
  469. turnId: "turn-1",
  470. toolCallId: "call-1",
  471. toolName: "mcp__computer-use__left_click",
  472. },
  473. {
  474. ...base,
  475. kind: "tool-scheduled",
  476. turnId: "turn-1",
  477. toolCallId: "call-node-repl",
  478. toolName: "mcp__node_repl__js",
  479. computerUse: true,
  480. },
  481. {
  482. ...base,
  483. kind: "tool-started",
  484. turnId: "turn-1",
  485. toolCallId: "call-1",
  486. },
  487. { ...base, kind: "session-closed" },
  488. ]) {
  489. expect(zcodeComputerUseOperationEventSchema.safeParse(event).success).toBe(true);
  490. }
  491. for (const event of [
  492. { ...base, eventId: "", kind: "session-closed" },
  493. { ...base, sequenceNumber: -1, kind: "session-closed" },
  494. { ...base, kind: "turn-started" },
  495. { ...base, kind: "tool-scheduled", turnId: "turn-1", toolCallId: "call-1" },
  496. // computerUse 是布尔事实,只有 true 有意义;false 与动作名都不在契约里。
  497. {
  498. ...base,
  499. kind: "tool-scheduled",
  500. turnId: "turn-1",
  501. toolCallId: "call-1",
  502. toolName: "mcp__node_repl__js",
  503. computerUse: false,
  504. },
  505. // tool-started 拿不到模型源码(ToolCallStartedPayload 无 input),不允许携带该事实。
  506. {
  507. ...base,
  508. kind: "tool-started",
  509. turnId: "turn-1",
  510. toolCallId: "call-1",
  511. computerUse: true,
  512. },
  513. { ...base, kind: "tool-started", toolCallId: "" },
  514. { ...base, kind: "session-closed", toolName: "must-not-pass" },
  515. { ...base, kind: "unknown-kind" },
  516. ]) {
  517. expect(zcodeComputerUseOperationEventSchema.safeParse(event).success).toBe(false);
  518. }
  519. });
  520. it("workspace/readPresentation 只接受 workspace identity", () => {
  521. expect(() =>
  522. zcodeWorkspaceReadPresentationParamsSchema.parse({
  523. workspace,
  524. runtimeModel: {},
  525. }),
  526. ).toThrow();
  527. expect(zcodeWorkspaceReadPresentationParamsSchema.parse({ workspace })).toEqual({ workspace });
  528. });
  529. it("preserves automation runtime config in strict protocol schemas", () => {
  530. const create = zcodeAutomationCreateParamsSchema.parse({
  531. title: "daily report",
  532. cronExpr: "0 9 * * *",
  533. prompt: "summarize",
  534. modelSelection: {
  535. providerId: "glm",
  536. modelId: "glm-5.2",
  537. options: { reasoningLevel: "high" },
  538. },
  539. mode: "plan",
  540. });
  541. expect(
  542. zcodeAutomationCreateParamsSchema.parse({
  543. title: "3分钟后提醒",
  544. cronExpr: "* * * * *",
  545. relativeDelayMinutes: 3,
  546. prompt: "提醒我",
  547. recurring: false,
  548. }),
  549. ).toMatchObject({ relativeDelayMinutes: 3, recurring: false });
  550. expect(create).toMatchObject({
  551. modelSelection: {
  552. providerId: "glm",
  553. modelId: "glm-5.2",
  554. options: { reasoningLevel: "high" },
  555. },
  556. mode: "plan",
  557. });
  558. expect(
  559. zcodeAutomationProtocolSchema.parse({
  560. automationId: "automation-1",
  561. ...create,
  562. enabled: true,
  563. lifecycleStatus: "active",
  564. runCount: 0,
  565. recurring: true,
  566. }),
  567. ).toMatchObject({ mode: "plan", modelSelection: { modelId: "glm-5.2" } });
  568. expect(
  569. zcodeAutomationProtocolSchema.parse({
  570. automationId: "automation-default-mode",
  571. title: "daily report",
  572. cronExpr: "0 9 * * *",
  573. prompt: "summarize",
  574. mode: "default",
  575. enabled: true,
  576. lifecycleStatus: "active",
  577. runCount: 0,
  578. recurring: true,
  579. }),
  580. ).toMatchObject({ mode: "default" });
  581. });
  582. it("将会话 Cron interval carrier 严格限制为 1-200 并要求成对提交", () => {
  583. expect(
  584. zcodeAutomationCreateParamsSchema.parse({
  585. cronExpr: "* * * * *",
  586. prompt: "提醒我",
  587. intervalUnit: "minute",
  588. interval: 200,
  589. }),
  590. ).toMatchObject({ intervalUnit: "minute", interval: 200 });
  591. expect(() =>
  592. zcodeAutomationCreateParamsSchema.parse({
  593. cronExpr: "* * * * *",
  594. prompt: "提醒我",
  595. intervalUnit: "minute",
  596. interval: 201,
  597. }),
  598. ).toThrow();
  599. expect(() =>
  600. zcodeAutomationCreateParamsSchema.parse({
  601. cronExpr: "* * * * *",
  602. prompt: "提醒我",
  603. intervalUnit: "minute",
  604. }),
  605. ).toThrow();
  606. expect(
  607. zcodeAutomationUpdateParamsSchema.parse({
  608. automationId: "automation-1",
  609. intervalUnit: "yearly",
  610. interval: 200,
  611. }),
  612. ).toMatchObject({ intervalUnit: "yearly", interval: 200 });
  613. expect(() =>
  614. zcodeAutomationUpdateParamsSchema.parse({
  615. automationId: "automation-1",
  616. intervalUnit: "yearly",
  617. interval: 1.5,
  618. }),
  619. ).toThrow();
  620. // carrier 必须保持无限循环,避免 host 直接收到 recurring=false / 有限次数的矛盾状态。
  621. expect(
  622. zcodeAutomationUpdateParamsSchema.parse({
  623. automationId: "automation-1",
  624. intervalUnit: "yearly",
  625. interval: 200,
  626. recurring: true,
  627. maxRuns: null,
  628. }),
  629. ).toMatchObject({ recurring: true, maxRuns: null });
  630. for (const invalidMode of [{ recurring: false }, { maxRuns: 2 }]) {
  631. expect(() =>
  632. zcodeAutomationUpdateParamsSchema.parse({
  633. automationId: "automation-1",
  634. intervalUnit: "yearly",
  635. interval: 200,
  636. ...invalidMode,
  637. }),
  638. ).toThrow();
  639. }
  640. for (const invalidMode of [{ recurring: false }, { maxRuns: 2 }]) {
  641. expect(() =>
  642. zcodeAutomationCreateParamsSchema.parse({
  643. cronExpr: "* * * * *",
  644. prompt: "提醒我",
  645. intervalUnit: "minute",
  646. interval: 200,
  647. ...invalidMode,
  648. }),
  649. ).toThrow();
  650. }
  651. });
  652. it("validates the dedicated automation task-binding query", () => {
  653. expect(
  654. zcodeAutomationCheckTaskBindingParamsSchema.parse({ targetTaskId: "session-1" }),
  655. ).toEqual({ targetTaskId: "session-1" });
  656. expect(zcodeAutomationCheckTaskBindingResultSchema.parse({ bound: true })).toEqual({
  657. bound: true,
  658. });
  659. expect(() =>
  660. zcodeAutomationCheckTaskBindingParamsSchema.parse({ targetTaskId: " " }),
  661. ).toThrow();
  662. expect(() =>
  663. zcodeAutomationCheckTaskBindingResultSchema.parse({ bound: false, automations: [] }),
  664. ).toThrow();
  665. });
  666. it("validates a strict non-empty automation update patch", () => {
  667. expect(
  668. zcodeAutomationUpdateParamsSchema.parse({
  669. automationId: "automation-1",
  670. cronExpr: "0 10 * * *",
  671. recurring: true,
  672. maxRuns: null,
  673. }),
  674. ).toEqual({
  675. automationId: "automation-1",
  676. cronExpr: "0 10 * * *",
  677. recurring: true,
  678. maxRuns: null,
  679. });
  680. expect(
  681. zcodeAutomationUpdateParamsSchema.parse({
  682. automationId: "automation-1",
  683. recurring: true,
  684. }),
  685. ).toEqual({
  686. automationId: "automation-1",
  687. recurring: true,
  688. });
  689. expect(() =>
  690. zcodeAutomationUpdateParamsSchema.parse({ automationId: "automation-1" }),
  691. ).toThrow();
  692. expect(() =>
  693. zcodeAutomationUpdateParamsSchema.parse({
  694. automationId: "automation-1",
  695. title: "new title",
  696. enabled: false,
  697. }),
  698. ).toThrow();
  699. expect(() =>
  700. zcodeAutomationUpdateParamsSchema.parse({
  701. automationId: "automation-1",
  702. maxRuns: null,
  703. }),
  704. ).toThrow("clearing maxRuns requires recurring=true");
  705. expect(() =>
  706. zcodeAutomationUpdateParamsSchema.parse({
  707. automationId: "automation-1",
  708. recurring: false,
  709. maxRuns: null,
  710. }),
  711. ).toThrow("clearing maxRuns requires recurring=true");
  712. expect(() =>
  713. zcodeAutomationUpdateParamsSchema.parse({
  714. automationId: "automation-1",
  715. recurring: true,
  716. maxRuns: 3,
  717. }),
  718. ).toThrow("recurring=true cannot be combined with a numeric maxRuns");
  719. });
  720. it("accepts an explicit session title-generation switch while staying strict", () => {
  721. expect(
  722. zcodeSessionCreateParamsSchema.parse({
  723. workspace,
  724. titleGenerationEnabled: false,
  725. }).titleGenerationEnabled,
  726. ).toBe(false);
  727. expect(() =>
  728. zcodeSessionCreateParamsSchema.parse({
  729. workspace,
  730. titleGenerationEnabled: "false",
  731. }),
  732. ).toThrow();
  733. });
  734. it("validates the paged session subagent projection", () => {
  735. expect(
  736. zcodeSessionSubagentsParamsSchema.parse({
  737. sessionId: "sess_parent",
  738. endedCursor: "cursor-20",
  739. endedLimit: 20,
  740. }),
  741. ).toEqual({
  742. sessionId: "sess_parent",
  743. endedCursor: "cursor-20",
  744. endedLimit: 20,
  745. });
  746. expect(
  747. zcodeSessionSubagentsResultSchema.parse({
  748. revision: 7,
  749. childSessionIds: ["sess_child_running", "sess_child_failed"],
  750. running: [
  751. {
  752. childSessionId: "sess_child_running",
  753. subagentType: "Explore",
  754. title: "Inspect the renderer",
  755. status: "waiting",
  756. startedAt: 10,
  757. },
  758. ],
  759. ended: {
  760. total: 1,
  761. items: [
  762. {
  763. childSessionId: "sess_child_failed",
  764. subagentType: "Plan",
  765. title: "Plan the migration",
  766. summary: "Provider request failed",
  767. status: "failed",
  768. startedAt: 1,
  769. endedAt: 9,
  770. },
  771. ],
  772. nextCursor: "cursor-40",
  773. },
  774. }),
  775. ).toMatchObject({
  776. revision: 7,
  777. childSessionIds: ["sess_child_running", "sess_child_failed"],
  778. running: [{ status: "waiting" }],
  779. ended: { total: 1, items: [{ status: "failed" }] },
  780. });
  781. expect(() =>
  782. zcodeSessionSubagentsParamsSchema.parse({
  783. sessionId: "sess_parent",
  784. endedLimit: 0,
  785. }),
  786. ).toThrow();
  787. expect(() =>
  788. zcodeSessionSubagentsResultSchema.parse({
  789. revision: 0,
  790. childSessionIds: ["sess_child"],
  791. running: [],
  792. ended: {
  793. total: 1,
  794. items: [
  795. {
  796. childSessionId: "sess_child",
  797. subagentType: "Explore",
  798. title: "Inspect",
  799. status: "running",
  800. },
  801. ],
  802. },
  803. }),
  804. ).toThrow();
  805. });
  806. it("parses JSON-RPC style messages without requiring a jsonrpc field", () => {
  807. const parsed = zcodeProtocolMessageSchema.parse({
  808. id: "request-1",
  809. method: "session/read",
  810. params: {
  811. sessionId: "sess_1",
  812. },
  813. });
  814. expect(parsed).toMatchObject({
  815. id: "request-1",
  816. method: "session/read",
  817. });
  818. });
  819. it("allows MCP list requests to carry explicit MCP servers", () => {
  820. expect(
  821. zcodeMcpListParamsSchema.parse({
  822. workspace,
  823. mcpServers: [
  824. {
  825. name: "agents-fallback",
  826. command: "node",
  827. args: ["server.mjs"],
  828. env: [{ name: "TOKEN", value: "secret" }],
  829. timeoutMs: 3000,
  830. },
  831. ],
  832. }),
  833. ).toMatchObject({
  834. workspace,
  835. mcpServers: [
  836. {
  837. name: "agents-fallback",
  838. command: "node",
  839. args: ["server.mjs"],
  840. env: [{ name: "TOKEN", value: "secret" }],
  841. timeoutMs: 3000,
  842. },
  843. ],
  844. });
  845. });
  846. it("accepts MCP servers on session create and resume params while staying strict", () => {
  847. const mcpServers = [
  848. {
  849. name: "chrome-devtools",
  850. command: "npx",
  851. args: ["-y", "chrome-devtools-mcp@latest"],
  852. env: [],
  853. timeoutMs: 3,
  854. },
  855. {
  856. name: "linear",
  857. type: "http",
  858. url: "https://mcp.example.test",
  859. headers: [{ name: "Authorization", value: "Bearer token" }],
  860. timeoutMs: 5000,
  861. },
  862. {
  863. name: "events",
  864. type: "sse",
  865. url: "https://mcp.example.test/sse",
  866. headers: [],
  867. timeoutMs: 8000,
  868. },
  869. ];
  870. expect(zcodeSessionCreateParamsSchema.parse({ workspace, mcpServers }).mcpServers).toEqual(
  871. mcpServers,
  872. );
  873. expect(
  874. zcodeSessionResumeParamsSchema.parse({
  875. sessionId: "sess_1",
  876. workspace,
  877. mcpServers,
  878. }).mcpServers,
  879. ).toEqual(mcpServers);
  880. expect(() =>
  881. zcodeSessionCreateParamsSchema.parse({
  882. workspace,
  883. mcpServers: [
  884. {
  885. ...mcpServers[0],
  886. tokenShouldNotPass: true,
  887. },
  888. ],
  889. }),
  890. ).toThrow();
  891. });
  892. it("accepts session create tool lists while staying strict", () => {
  893. const parsed = zcodeSessionCreateParamsSchema.parse({
  894. workspace,
  895. toolAllowlist: ["mcp__zcode-cua__request_access", "mcp__zcode-cua__list_apps"],
  896. toolDenylist: ["Bash"],
  897. });
  898. expect(parsed.toolAllowlist).toEqual([
  899. "mcp__zcode-cua__request_access",
  900. "mcp__zcode-cua__list_apps",
  901. ]);
  902. expect(parsed.toolDenylist).toEqual(["Bash"]);
  903. expect(() =>
  904. zcodeSessionCreateParamsSchema.parse({
  905. workspace,
  906. toolAllowlist: ["Read"],
  907. unexpectedToolPolicy: true,
  908. }),
  909. ).toThrow();
  910. });
  911. it("accepts session RESUME tool lists too (cold resume keeps the same isolation)", () => {
  912. // 冷恢复必须和 create 同边界地带工具面约束,否则 CUA 会话 resume 后会重新可见 Bash 等被禁工具。
  913. const parsed = zcodeSessionResumeParamsSchema.parse({
  914. sessionId: "sess_1",
  915. toolAllowlist: ["mcp__zcode-cua__request_access"],
  916. toolDenylist: ["Bash"],
  917. });
  918. expect(parsed.toolAllowlist).toEqual(["mcp__zcode-cua__request_access"]);
  919. expect(parsed.toolDenylist).toEqual(["Bash"]);
  920. // 仍 strict:未知字段拒绝。
  921. expect(() =>
  922. zcodeSessionResumeParamsSchema.parse({
  923. sessionId: "sess_1",
  924. unexpectedToolPolicy: true,
  925. }),
  926. ).toThrow();
  927. });
  928. it("models provider runtime header refresh as a strict interaction request", () => {
  929. const params = zcodeProviderRuntimeHeadersRequestParamsSchema.parse({
  930. requestId: "header-refresh-1",
  931. sessionId: "sess_1",
  932. turnId: "turn_1",
  933. workspace,
  934. modelSelection: model,
  935. providerId: "account:zai-individual-coding-plan",
  936. reason: "model-request",
  937. });
  938. // 当前请求期鉴权材料承接请求级 header;不能恢复旧 Registry revision 或裸 headers 协议。
  939. const runtimeProviderHeaders = {
  940. "X-Request-Scoped-Param": "request-token",
  941. "X-Request-Scoped-Region": "cn",
  942. };
  943. const response = zcodeProviderRuntimeHeadersResponseSchema.parse({
  944. headersApplied: true,
  945. requestAuth: {
  946. apiKey: "request-key",
  947. headers: { "X-Request": "request-header", ...runtimeProviderHeaders },
  948. },
  949. });
  950. expect(response).toMatchObject({ requestAuth: { headers: runtimeProviderHeaders } });
  951. expect(() =>
  952. zcodeProviderRuntimeHeadersResponseSchema.parse({
  953. headersApplied: true,
  954. }),
  955. ).toThrow();
  956. expect(() =>
  957. zcodeProviderRuntimeHeadersResponseSchema.parse({
  958. headersApplied: true,
  959. runtimeProviderHeaders,
  960. providerRevision: "rev-2",
  961. }),
  962. ).toThrow();
  963. expect(zcodeProtocolMethods.interactionRequestProviderRuntimeHeaders).toBe(
  964. "interaction/requestProviderRuntimeHeaders",
  965. );
  966. expect(() =>
  967. zcodeProviderRuntimeHeadersRequestParamsSchema.parse({
  968. ...params,
  969. staleHeader: "must-not-pass-through",
  970. }),
  971. ).toThrow();
  972. });
  973. it.each(["start-plan", "individual-coding-plan", "team-coding-plan", "off-peak"] as const)(
  974. "runtime headers 直接接受 Registry zhipu access mode: %s",
  975. (mode) => {
  976. const parsed = zcodeProviderRuntimeHeadersRequestParamsSchema.parse({
  977. requestId: `request-${mode}`,
  978. sessionId: "sess_1",
  979. workspace,
  980. modelSelection: model,
  981. providerId: `account:${mode}`,
  982. accountAccess: {
  983. type: "zhipu-account",
  984. accountType: "bigmodel",
  985. mode,
  986. entitled: true,
  987. },
  988. reason: "model-request",
  989. });
  990. expect(parsed.accountAccess).toEqual({
  991. type: "zhipu-account",
  992. accountType: "bigmodel",
  993. mode,
  994. entitled: true,
  995. });
  996. },
  997. );
  998. it("runtime headers 拒绝已经退出 Registry 的旧 planKind Access 形状", () => {
  999. expect(() =>
  1000. zcodeProviderRuntimeHeadersRequestParamsSchema.parse({
  1001. requestId: "request-legacy",
  1002. sessionId: "sess_1",
  1003. workspace,
  1004. modelSelection: model,
  1005. providerId: "account:legacy",
  1006. accountAccess: {
  1007. type: "zhipu-account",
  1008. accountType: "bigmodel",
  1009. planKind: "team-coding-plan",
  1010. },
  1011. reason: "model-request",
  1012. }),
  1013. ).toThrow();
  1014. });
  1015. it("parses subagent mirrored tool updates with explicit protocol metadata", () => {
  1016. const scheduled = zcodeSessionEventSchema.parse({
  1017. eventId: "evt_subagent_tool_scheduled",
  1018. seq: 12,
  1019. sessionId: "sess_parent",
  1020. timestamp: 13,
  1021. traceId: "trace_parent",
  1022. turnId: "turn_parent",
  1023. type: "tool.updated",
  1024. payload: {
  1025. kind: "scheduled",
  1026. toolCallId: "tool_subagent_agent_1_call_1",
  1027. toolName: "Read",
  1028. input: { filePath: "/workspace/app.ts" },
  1029. parentToolCallId: "call_parent_agent",
  1030. source: "subagent",
  1031. agentId: "agent_1",
  1032. agentType: "Explore",
  1033. childSessionId: "sess_subagent_agent_1",
  1034. childToolCallId: "call_1",
  1035. description: "Inspect workspace",
  1036. },
  1037. });
  1038. const started = zcodeSessionEventSchema.parse({
  1039. eventId: "evt_subagent_tool_started",
  1040. seq: 13,
  1041. sessionId: "sess_parent",
  1042. timestamp: 14,
  1043. traceId: "trace_parent",
  1044. turnId: "turn_parent",
  1045. type: "tool.updated",
  1046. payload: {
  1047. kind: "started",
  1048. toolCallId: "tool_subagent_agent_1_call_1",
  1049. startedAt: 14,
  1050. parentToolCallId: "call_parent_agent",
  1051. source: "subagent",
  1052. agentId: "agent_1",
  1053. agentType: "Explore",
  1054. childSessionId: "sess_subagent_agent_1",
  1055. childToolCallId: "call_1",
  1056. description: "Inspect workspace",
  1057. },
  1058. });
  1059. expect(scheduled.payload.parentToolCallId).toBe("call_parent_agent");
  1060. expect(started.payload.source).toBe("subagent");
  1061. expect(() =>
  1062. zcodeSessionEventSchema.parse({
  1063. ...scheduled,
  1064. payload: {
  1065. ...scheduled.payload,
  1066. unknownSubagentField: true,
  1067. },
  1068. }),
  1069. ).toThrow();
  1070. });
  1071. it("parses background subagent mirrored tool updates", () => {
  1072. const event = zcodeSessionEventSchema.parse({
  1073. eventId: "evt_background_subagent_tool_started",
  1074. seq: 14,
  1075. sessionId: "sess_parent",
  1076. timestamp: 15,
  1077. traceId: "trace_parent",
  1078. turnId: "turn_parent",
  1079. type: "tool.updated",
  1080. payload: {
  1081. kind: "started",
  1082. toolCallId: "tool_subagent_agent_1_call_1",
  1083. startedAt: 15,
  1084. source: "subagent",
  1085. agentId: "agent_1",
  1086. agentType: "Explore",
  1087. childSessionId: "sess_subagent_agent_1",
  1088. childToolCallId: "call_1",
  1089. background: true,
  1090. },
  1091. });
  1092. expect(event.payload.background).toBe(true);
  1093. });
  1094. it("parses subagent mirrored permission events with routing metadata", () => {
  1095. const requested = zcodeSessionEventSchema.parse({
  1096. eventId: "evt_subagent_permission_requested",
  1097. seq: 14,
  1098. sessionId: "sess_parent",
  1099. timestamp: 15,
  1100. traceId: "trace_parent",
  1101. turnId: "turn_parent",
  1102. type: "permission.requested",
  1103. payload: {
  1104. requestId: "permission_1",
  1105. toolCallId: "tool_subagent_agent_1_call_1",
  1106. toolName: "Bash",
  1107. riskLevel: "high",
  1108. reason: "Run workspace tests",
  1109. input: { command: "pnpm test" },
  1110. childSessionId: "sess_subagent_agent_1",
  1111. background: true,
  1112. options: [
  1113. {
  1114. optionId: "allow_once",
  1115. kind: "allowOnce",
  1116. name: "Allow once",
  1117. response: { decision: "allow" },
  1118. },
  1119. ],
  1120. },
  1121. });
  1122. const resolved = zcodeSessionEventSchema.parse({
  1123. eventId: "evt_subagent_permission_resolved",
  1124. seq: 15,
  1125. sessionId: "sess_parent",
  1126. timestamp: 16,
  1127. traceId: "trace_parent",
  1128. turnId: "turn_parent",
  1129. type: "permission.resolved",
  1130. payload: {
  1131. requestId: "permission_1",
  1132. toolCallId: "tool_subagent_agent_1_call_1",
  1133. toolName: "Bash",
  1134. decision: "allow",
  1135. childSessionId: "sess_subagent_agent_1",
  1136. background: true,
  1137. },
  1138. });
  1139. expect(requested.payload.childSessionId).toBe("sess_subagent_agent_1");
  1140. expect(requested.payload.background).toBe(true);
  1141. expect(resolved.payload.childSessionId).toBe("sess_subagent_agent_1");
  1142. expect(resolved.payload.background).toBe(true);
  1143. });
  1144. it("parses scheduled tool updates that reference model-streamed input", () => {
  1145. const scheduled = zcodeSessionEventSchema.parse({
  1146. eventId: "evt_tool_scheduled_tombstone",
  1147. seq: 15,
  1148. sessionId: "sess_parent",
  1149. timestamp: 16,
  1150. traceId: "trace_parent",
  1151. turnId: "turn_parent",
  1152. type: "tool.updated",
  1153. payload: {
  1154. kind: "scheduled",
  1155. toolCallId: "call_1",
  1156. toolName: "Write",
  1157. inputByteLength: 32768,
  1158. inputOmitted: true,
  1159. inputRef: "model_stream",
  1160. },
  1161. });
  1162. expect(scheduled.payload.inputOmitted).toBe(true);
  1163. expect(scheduled.payload.inputRef).toBe("model_stream");
  1164. expect("input" in scheduled.payload).toBe(false);
  1165. });
  1166. describe.each(["desktop-continuous", "web-remote-replayable"])(
  1167. "scheduled tool message ownership (%s)",
  1168. (deliveryKind) => {
  1169. it.each([
  1170. { input: { command: "sleep 20" } },
  1171. { inputByteLength: 128, inputOmitted: true, inputRef: "model_stream" },
  1172. ])("preserves ownership for input form %j while keeping strict validation", (input) => {
  1173. const event = {
  1174. eventId: "evt_scheduled_ownership",
  1175. seq: 1,
  1176. sessionId: "sess_ownership",
  1177. timestamp: 1,
  1178. deliveryKind,
  1179. type: "tool.updated",
  1180. payload: {
  1181. kind: "scheduled",
  1182. toolCallId: "call_ownership",
  1183. toolName: "Bash",
  1184. ...input,
  1185. },
  1186. };
  1187. // 旧 CLI 没有消息归属字段时仍须兼容;新 CLI 的字段不能导致整条调度事件丢失。
  1188. expect(zcodeSessionEventSchema.parse(event).payload).toEqual(event.payload);
  1189. const payload = { ...event.payload, assistantMessageId: "msg_assistant" };
  1190. expect(zcodeSessionEventSchema.parse({ ...event, payload })).toEqual({ ...event, payload });
  1191. for (const assistantMessageId of ["", null, 42]) {
  1192. expect(
  1193. zcodeSessionEventSchema.safeParse({
  1194. ...event,
  1195. payload: { ...payload, assistantMessageId },
  1196. }).success,
  1197. ).toBe(false);
  1198. }
  1199. expect(
  1200. zcodeSessionEventSchema.safeParse({
  1201. ...event,
  1202. payload: { ...payload, unknownField: true },
  1203. }).success,
  1204. ).toBe(false);
  1205. });
  1206. },
  1207. );
  1208. it("parses a server-authoritative session state snapshot", () => {
  1209. const snapshot = zcodeSessionStateSnapshotSchema.parse({
  1210. protocol: {
  1211. name: ZCODE_PROTOCOL_NAME,
  1212. version: ZCODE_PROTOCOL_VERSION,
  1213. },
  1214. session: {
  1215. sessionId: "sess_1",
  1216. workspace,
  1217. sessionKind: "interactive",
  1218. title: "Build login flow",
  1219. titleSource: "generated",
  1220. mode: "build",
  1221. status: "idle",
  1222. model,
  1223. createdAt: 1,
  1224. updatedAt: 2,
  1225. },
  1226. settings: {
  1227. model: {
  1228. current: model,
  1229. available: [{ ref: model, label: "GLM 4.6", properties: modelProperties }],
  1230. lastUsed: model,
  1231. },
  1232. thoughtLevel: {
  1233. enabled: true,
  1234. current: "medium",
  1235. available: [{ value: "medium", label: "Medium" }],
  1236. },
  1237. mode: {
  1238. current: "build",
  1239. },
  1240. },
  1241. projection: {
  1242. sessionId: "sess_1",
  1243. status: "idle",
  1244. mode: "build",
  1245. turnCount: 1,
  1246. totalTokenCount: 0,
  1247. contextUsed: 0,
  1248. contextWindow: 128000,
  1249. pendingPermissions: [],
  1250. activeToolCalls: [],
  1251. backgroundJobs: [],
  1252. lastError: {
  1253. type: "MODEL_ERROR",
  1254. code: "provider_not_found",
  1255. message: "Model provider is not configured: stale-provider",
  1256. detail: "stale-provider/gpt-5.5",
  1257. attribution: {
  1258. source: "runtime",
  1259. reason: "provider_not_configured",
  1260. providerId: "account:zai-individual-coding-plan",
  1261. retryable: false,
  1262. },
  1263. },
  1264. },
  1265. runtime: {
  1266. eventSeq: 7,
  1267. stateRevision: 3,
  1268. deliveryKind: "desktop-continuous",
  1269. pendingRequestIds: [],
  1270. },
  1271. messages: [
  1272. {
  1273. info: {
  1274. messageId: "msg_1",
  1275. sessionId: "sess_1",
  1276. role: "user",
  1277. time: { created: 1 },
  1278. agent: "zcode-agent",
  1279. model,
  1280. },
  1281. parts: [
  1282. {
  1283. partId: "part_1",
  1284. sessionId: "sess_1",
  1285. messageId: "msg_1",
  1286. type: "text",
  1287. text: "hello",
  1288. },
  1289. ],
  1290. },
  1291. ],
  1292. });
  1293. expect(snapshot.settings.model.current.providerId).toBe("glm");
  1294. expect(snapshot.session.titleSource).toBe("generated");
  1295. expect(snapshot.projection.lastError).toEqual({
  1296. type: "MODEL_ERROR",
  1297. code: "provider_not_found",
  1298. message: "Model provider is not configured: stale-provider",
  1299. detail: "stale-provider/gpt-5.5",
  1300. attribution: {
  1301. source: "runtime",
  1302. reason: "provider_not_configured",
  1303. providerId: "account:zai-individual-coding-plan",
  1304. retryable: false,
  1305. },
  1306. });
  1307. expect(snapshot.runtime.stateRevision).toBe(3);
  1308. });
  1309. it("parses agent-owned session title update events", () => {
  1310. const event = zcodeSessionEventSchema.parse({
  1311. eventId: "evt_title_1",
  1312. seq: 8,
  1313. sessionId: "sess_1",
  1314. timestamp: 9,
  1315. traceId: "trace_title_1",
  1316. type: "session.titleUpdated",
  1317. payload: {
  1318. previousTitle: "please fix the mobile login button",
  1319. source: "generated",
  1320. title: "Fix mobile login",
  1321. },
  1322. });
  1323. expect(event.type).toBe("session.titleUpdated");
  1324. expect(event.payload).toMatchObject({ title: "Fix mobile login" });
  1325. });
  1326. it("preserves attribution on legacy turn.failed events", () => {
  1327. const event = zcodeSessionEventSchema.parse({
  1328. eventId: "evt_failed_1",
  1329. seq: 9,
  1330. sessionId: "sess_1",
  1331. timestamp: 10,
  1332. type: "turn.failed",
  1333. payload: {
  1334. turnPhase: "model",
  1335. error: {
  1336. type: "MODEL_ERROR",
  1337. code: "model_request_failed",
  1338. message: "Model request failed.",
  1339. attribution: {
  1340. source: "provider",
  1341. reason: "unknown",
  1342. errorPhase: "response",
  1343. exceptionKind: "api_call",
  1344. providerId: "account:zai-start-plan",
  1345. providerErrorCode: "3012",
  1346. statusCode: 405,
  1347. },
  1348. },
  1349. },
  1350. });
  1351. expect(event.payload.error.attribution).toEqual({
  1352. source: "provider",
  1353. reason: "unknown",
  1354. errorPhase: "response",
  1355. exceptionKind: "api_call",
  1356. providerId: "account:zai-start-plan",
  1357. providerErrorCode: "3012",
  1358. statusCode: 405,
  1359. });
  1360. });
  1361. it("rejects raw exception names from error attribution", () => {
  1362. expect(() =>
  1363. errorAttributionSchema.parse({
  1364. errorPhase: "stream",
  1365. exceptionKind: "SecretProviderNetworkError",
  1366. }),
  1367. ).toThrow();
  1368. });
  1369. it("accepts complete steer queue and drain facts emitted by the CLI", () => {
  1370. const queued = zcodeSessionEventSchema.parse({
  1371. eventId: "evt_steer_queued_1",
  1372. seq: 9,
  1373. sessionId: "sess_1",
  1374. timestamp: 10,
  1375. type: "turn.steerQueued",
  1376. payload: {
  1377. pendingInputId: "pending_1",
  1378. inputId: "input_1",
  1379. queryId: "query_1",
  1380. input: "继续检查",
  1381. inputPreview: "继续检查",
  1382. inputSize: 4,
  1383. delivery: "guide",
  1384. intent: { delivery: "guide", sourceCommandId: "command_1" },
  1385. toolDisallowlist: ["Write"],
  1386. targetTurnId: "turn_1",
  1387. queueLength: 1,
  1388. },
  1389. });
  1390. const drained = zcodeSessionEventSchema.parse({
  1391. eventId: "evt_steer_drained_1",
  1392. seq: 10,
  1393. sessionId: "sess_1",
  1394. timestamp: 11,
  1395. type: "turn.steerDrained",
  1396. payload: {
  1397. pendingInputIds: ["pending_1"],
  1398. queryIds: ["query_1"],
  1399. targetTurnId: "turn_1",
  1400. injectedMessageIds: ["message_1"],
  1401. drainedInputs: [
  1402. {
  1403. pendingInputId: "pending_1",
  1404. messageId: "message_1",
  1405. text: "继续检查",
  1406. delivery: "guide",
  1407. intent: { delivery: "guide", sourceCommandId: "command_1" },
  1408. toolDisallowlist: ["Write"],
  1409. },
  1410. ],
  1411. },
  1412. });
  1413. expect(queued.payload).toMatchObject({ delivery: "guide" });
  1414. expect(drained.payload).toMatchObject({
  1415. drainedInputs: [{ messageId: "message_1", delivery: "guide" }],
  1416. });
  1417. });
  1418. it("parses typed session events for tool updates", () => {
  1419. const event = zcodeSessionEventSchema.parse({
  1420. eventId: "evt_tool_1",
  1421. seq: 12,
  1422. sessionId: "sess_1",
  1423. timestamp: 13,
  1424. type: "tool.updated",
  1425. payload: {
  1426. kind: "result",
  1427. toolCallId: "tool_1",
  1428. toolName: "Edit",
  1429. duration: 42,
  1430. result: {
  1431. success: true,
  1432. content: "done",
  1433. },
  1434. },
  1435. });
  1436. expect(event.type).toBe("tool.updated");
  1437. expect(event.payload.kind).toBe("result");
  1438. });
  1439. it("strictly validates bounded Node REPL image display payloads", () => {
  1440. const event = {
  1441. eventId: "evt_tool_image_1",
  1442. seq: 13,
  1443. sessionId: "sess_1",
  1444. timestamp: 14,
  1445. type: "tool.updated",
  1446. payload: {
  1447. kind: "result",
  1448. toolCallId: "tool_image_1",
  1449. toolName: "mcp__node_repl__js",
  1450. duration: 42,
  1451. result: {
  1452. success: true,
  1453. content: "(no output)\n\n[Attached image/png: MCP image]",
  1454. display: {
  1455. kind: "node_repl_images",
  1456. images: [{ base64: "AAAA", mimeType: "image/png" }],
  1457. source: "browser_turn_end",
  1458. },
  1459. },
  1460. },
  1461. };
  1462. expect(zcodeSessionEventSchema.parse(event).payload).toMatchObject({
  1463. kind: "result",
  1464. result: {
  1465. display: { kind: "node_repl_images", source: "browser_turn_end" },
  1466. },
  1467. });
  1468. expect(() =>
  1469. zcodeSessionEventSchema.parse({
  1470. ...event,
  1471. payload: {
  1472. ...event.payload,
  1473. result: {
  1474. ...event.payload.result,
  1475. display: {
  1476. ...event.payload.result.display,
  1477. unbounded: true,
  1478. },
  1479. },
  1480. },
  1481. }),
  1482. ).toThrow();
  1483. });
  1484. it("keeps browser turn-end image displays in strict v4 tool rows", () => {
  1485. const row = conversationRowSchema.parse({
  1486. rowId: 4,
  1487. turnId: "turn-1",
  1488. createdAt: 10,
  1489. createdAtSeq: 4,
  1490. kind: "toolCall",
  1491. toolCallId: "tool-browser-turn-end",
  1492. toolName: "mcp__node_repl__js",
  1493. status: "success",
  1494. inputText: "",
  1495. display: {
  1496. kind: "node_repl_images",
  1497. source: "browser_turn_end",
  1498. images: [{ base64: "AAAA", mimeType: "image/png" }],
  1499. },
  1500. });
  1501. expect(row).toMatchObject({
  1502. kind: "toolCall",
  1503. display: { kind: "node_repl_images", source: "browser_turn_end" },
  1504. });
  1505. });
  1506. it("keeps the official MCP unavailable code in strict v4 tool rows", () => {
  1507. // 两个 strict schema(CLI contracts 的 display payload 与这里的 row)必须同步加字段,
  1508. // 少加一处整条 row 会被拒,输入框提示就永远拿不到事实。
  1509. const row = conversationRowSchema.parse({
  1510. rowId: 5,
  1511. turnId: "turn-1",
  1512. createdAt: 10,
  1513. createdAtSeq: 5,
  1514. kind: "toolCall",
  1515. toolCallId: "tool-official-mcp",
  1516. toolName: "mcp__zcode-official__search_image",
  1517. status: "success",
  1518. inputText: "{}",
  1519. display: {
  1520. kind: "mcp_tool",
  1521. serverName: "zcode-official",
  1522. toolName: "search_image",
  1523. unavailable: { code: "quota_exceeded" },
  1524. },
  1525. });
  1526. expect(row).toMatchObject({
  1527. display: { kind: "mcp_tool", unavailable: { code: "quota_exceeded" } },
  1528. });
  1529. // internal_error 不在 code 枚举里:它是服务端兜底掩码,不驱动界面提示。枚举外的值因此
  1530. // **不会被携带**——display 不设门后 row 仍然有效,但这张卡没有载荷(§4.4.5)。
  1531. const maskedRow = conversationRowSchema.parse({
  1532. rowId: 6,
  1533. turnId: "turn-1",
  1534. createdAt: 10,
  1535. createdAtSeq: 6,
  1536. kind: "toolCall",
  1537. toolCallId: "tool-official-mcp",
  1538. toolName: "mcp__zcode-official__search_image",
  1539. status: "success",
  1540. inputText: "{}",
  1541. display: {
  1542. kind: "mcp_tool",
  1543. serverName: "zcode-official",
  1544. toolName: "search_image",
  1545. unavailable: { code: "internal_error" },
  1546. },
  1547. });
  1548. expect(maskedRow.kind === "toolCall" ? maskedRow.display : "unreachable").toBeUndefined();
  1549. });
  1550. it("strictly validates bounded CreateWorkflow display payloads", () => {
  1551. const event = {
  1552. eventId: "evt_tool_workflow_1",
  1553. seq: 15,
  1554. sessionId: "sess_1",
  1555. timestamp: 16,
  1556. type: "tool.updated",
  1557. payload: {
  1558. kind: "result",
  1559. toolCallId: "tool_workflow_1",
  1560. toolName: "CreateWorkflow",
  1561. duration: 7,
  1562. result: {
  1563. success: false,
  1564. content: "The workflow script has type errors:",
  1565. display: {
  1566. kind: "create_workflow",
  1567. ok: false,
  1568. errorCount: 1,
  1569. diagnostics: [{ line: 3, column: 5, code: 2304, message: "Cannot find name 'agent'." }],
  1570. },
  1571. },
  1572. },
  1573. };
  1574. expect(zcodeSessionEventSchema.parse(event).payload).toMatchObject({
  1575. kind: "result",
  1576. result: { display: { kind: "create_workflow", ok: false, errorCount: 1 } },
  1577. });
  1578. expect(() =>
  1579. zcodeSessionEventSchema.parse({
  1580. ...event,
  1581. payload: {
  1582. ...event.payload,
  1583. result: {
  1584. ...event.payload.result,
  1585. display: { ...event.payload.result.display, unbounded: true },
  1586. },
  1587. },
  1588. }),
  1589. ).toThrow();
  1590. });
  1591. it("keeps bounded CreateWorkflow diagnostics displays in strict v4 tool rows", () => {
  1592. const row = conversationRowSchema.parse({
  1593. rowId: 6,
  1594. turnId: "turn-1",
  1595. createdAt: 12,
  1596. createdAtSeq: 6,
  1597. kind: "toolCall",
  1598. toolCallId: "tool-create-workflow",
  1599. toolName: "CreateWorkflow",
  1600. status: "error",
  1601. inputText: "",
  1602. display: {
  1603. kind: "create_workflow",
  1604. ok: false,
  1605. errorCount: 2,
  1606. diagnostics: [
  1607. { line: 3, column: 5, code: 2304, message: "Cannot find name 'agent'." },
  1608. { line: 8, column: 1, code: 1005, message: "';' expected." },
  1609. ],
  1610. truncated: true,
  1611. },
  1612. });
  1613. expect(row).toMatchObject({
  1614. kind: "toolCall",
  1615. display: { kind: "create_workflow", ok: false, errorCount: 2, truncated: true },
  1616. });
  1617. });
  1618. it("accepts the bounded CreateWorkflow causality graph on both protocol boundaries", () => {
  1619. const causalityGraph = {
  1620. steps: [
  1621. {
  1622. id: "world-read#1",
  1623. kind: "world-read",
  1624. label: "glob *.ts",
  1625. line: 1,
  1626. column: 20,
  1627. lane: "workspace",
  1628. },
  1629. {
  1630. id: "ask#1",
  1631. kind: "ask",
  1632. label: "planner",
  1633. line: 2,
  1634. column: 24,
  1635. lane: "actor#1",
  1636. repeat: "serial",
  1637. },
  1638. {
  1639. id: "ask#2",
  1640. kind: "ask",
  1641. label: "reviewer",
  1642. // 插值名的静态形状:v3 镜像曾漏掉这两个 pattern 字段(0a8b059f40 只改了
  1643. // contracts 与 v4),.strict() 之下整图验证失败——固定在这条双边界用例里。
  1644. labelPattern: { head: "研究员", tail: "号" },
  1645. line: 3,
  1646. column: 24,
  1647. lane: "actor#2",
  1648. lanes: ["actor#2", "actor#3"],
  1649. repeat: "stack",
  1650. },
  1651. ],
  1652. lanes: [
  1653. { id: "workspace" },
  1654. { id: "actor#1", name: "planner", line: 2, column: 17 },
  1655. { id: "actor#2", name: "reviewer", line: 3, column: 17 },
  1656. { id: "actor#3", namePattern: { head: "研究员" }, line: 4, column: 17 },
  1657. ],
  1658. // 第二层是子代理导向(docs/dynamic-workflow/presentation.md):每阶段一张参与者卡,
  1659. // 无阶段词汇时 phase 恒为 `unphased`。字面量基数的家族每成员一张 `member` 卡,
  1660. // 基数未知时一张 `many` 卡。同样钉在双边界用例里,防单边漏改。
  1661. participants: [
  1662. { id: "unphased:workspace", phase: "unphased", lane: "workspace", steps: ["world-read#1"] },
  1663. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  1664. {
  1665. id: "unphased:actor#2[0]",
  1666. phase: "unphased",
  1667. lane: "actor#2",
  1668. steps: ["ask#2"],
  1669. member: { index: 0, of: 2 },
  1670. },
  1671. {
  1672. id: "unphased:actor#2[1]",
  1673. phase: "unphased",
  1674. lane: "actor#2",
  1675. steps: ["ask#2"],
  1676. member: { index: 1, of: 2 },
  1677. },
  1678. {
  1679. id: "unphased:actor#3",
  1680. phase: "unphased",
  1681. lane: "actor#3",
  1682. steps: ["ask#2"],
  1683. many: true,
  1684. },
  1685. ],
  1686. // 一种箭头:runs after;`back: true` 只标循环回边(single-arrow-contract spec);
  1687. // `types` 是跨越这条交接的产物类型(检视器素材,不上箭头)。
  1688. handoffs: [
  1689. { from: "unphased:workspace", to: "unphased:actor#1" },
  1690. { from: "unphased:actor#1", to: "unphased:actor#2[0]", types: ["Plan"] },
  1691. { from: "unphased:actor#1", to: "unphased:actor#2[1]", types: ["Plan"] },
  1692. { from: "unphased:actor#2[0]", to: "unphased:actor#1", back: true },
  1693. ],
  1694. sink: ["ask#2"],
  1695. };
  1696. // Legacy protocol: result.display superRefine.
  1697. const event = zcodeSessionEventSchema.parse({
  1698. eventId: "evt_tool_workflow_graph",
  1699. seq: 16,
  1700. sessionId: "sess_1",
  1701. timestamp: 17,
  1702. type: "tool.updated",
  1703. payload: {
  1704. kind: "result",
  1705. toolCallId: "tool_workflow_graph",
  1706. toolName: "CreateWorkflow",
  1707. duration: 7,
  1708. result: {
  1709. success: true,
  1710. content: "The workflow script compiled cleanly.",
  1711. display: {
  1712. kind: "create_workflow",
  1713. ok: true,
  1714. errorCount: 0,
  1715. diagnostics: [],
  1716. causalityGraph,
  1717. },
  1718. },
  1719. },
  1720. });
  1721. expect(event.payload).toMatchObject({
  1722. kind: "result",
  1723. result: { display: { kind: "create_workflow", ok: true, causalityGraph } },
  1724. });
  1725. // V4 rows: toolCallRow.display.
  1726. const row = conversationRowSchema.parse({
  1727. rowId: 7,
  1728. turnId: "turn-1",
  1729. createdAt: 13,
  1730. createdAtSeq: 7,
  1731. kind: "toolCall",
  1732. toolCallId: "tool-create-workflow-graph",
  1733. toolName: "CreateWorkflow",
  1734. status: "success",
  1735. inputText: "",
  1736. display: {
  1737. kind: "create_workflow",
  1738. ok: true,
  1739. errorCount: 0,
  1740. diagnostics: [],
  1741. causalityGraph,
  1742. },
  1743. });
  1744. expect(row).toMatchObject({
  1745. kind: "toolCall",
  1746. display: { kind: "create_workflow", ok: true, causalityGraph },
  1747. });
  1748. });
  1749. // 留白(docs/dynamic-workflow/authoring.md「Holes」):`hole` 站点、step / 阶段上的 `fill`、图的
  1750. // `holes[]` 与 FillWorkflowHole 行的顶层 `fill`。dwf-recursive 只改了 contracts 与 v4,v3 镜像在
  1751. // .strict() 之下拒掉整条 tool.updated,桌面端的 v3 订阅便丢了那张卡——与上面 labelPattern 同一类。
  1752. it("carries typed-hole fields through both the legacy event and v4 rows", () => {
  1753. const causalityGraph = {
  1754. steps: [
  1755. { id: "ask#1", kind: "ask", label: "planner", lane: "actor#1", phase: "phase#1" },
  1756. {
  1757. id: "hole#1a2b3c4d",
  1758. kind: "hole",
  1759. label: "verdict",
  1760. lane: "main",
  1761. phase: "hole#1a2b3c4d",
  1762. },
  1763. {
  1764. id: "ask#2",
  1765. kind: "ask",
  1766. label: "judge",
  1767. lane: "actor#2",
  1768. phase: "phase#2",
  1769. fill: "hole#1a2b3c4d",
  1770. },
  1771. ],
  1772. lanes: [
  1773. { id: "actor#1", name: "planner" },
  1774. { id: "actor#2", name: "judge" },
  1775. ],
  1776. participants: [
  1777. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  1778. { id: "phase#2:actor#2", phase: "phase#2", lane: "actor#2", steps: ["ask#2"] },
  1779. ],
  1780. handoffs: [{ from: "phase#1:actor#1", to: "phase#2:actor#2" }],
  1781. phases: [
  1782. { id: "phase#1", name: "plan" },
  1783. { id: "hole#1a2b3c4d", name: "verdict" },
  1784. { id: "phase#2", name: "judge", fill: "hole#1a2b3c4d" },
  1785. ],
  1786. phaseEdges: [
  1787. { from: "phase#1", to: "hole#1a2b3c4d" },
  1788. { from: "hole#1a2b3c4d", to: "phase#2" },
  1789. ],
  1790. holes: [
  1791. {
  1792. siteId: "hole#1a2b3c4d",
  1793. name: "verdict",
  1794. type: "Verdict",
  1795. phase: "hole#1a2b3c4d",
  1796. tail: true,
  1797. },
  1798. ],
  1799. exits: ["phase#2"],
  1800. };
  1801. const display = {
  1802. kind: "create_workflow",
  1803. ok: true,
  1804. errorCount: 0,
  1805. diagnostics: [],
  1806. causalityGraph,
  1807. fill: { siteId: "hole#1a2b3c4d", name: "verdict", draftPath: "/tmp/fill.ts", line: 3 },
  1808. };
  1809. // Legacy protocol: result.display superRefine.
  1810. const event = zcodeSessionEventSchema.parse({
  1811. eventId: "evt_tool_workflow_holes",
  1812. seq: 22,
  1813. sessionId: "sess_1",
  1814. timestamp: 23,
  1815. type: "tool.updated",
  1816. payload: {
  1817. kind: "result",
  1818. toolCallId: "tool_workflow_holes",
  1819. toolName: "FillWorkflowHole",
  1820. duration: 7,
  1821. result: { success: true, content: "The hole is filled.", display },
  1822. },
  1823. });
  1824. expect(event.payload).toMatchObject({ kind: "result", result: { display } });
  1825. // V4 rows: toolCallRow.display.
  1826. const row = conversationRowSchema.parse({
  1827. rowId: 11,
  1828. turnId: "turn-1",
  1829. createdAt: 17,
  1830. createdAtSeq: 11,
  1831. kind: "toolCall",
  1832. toolCallId: "tool-fill-workflow-hole",
  1833. toolName: "FillWorkflowHole",
  1834. status: "success",
  1835. inputText: "",
  1836. display,
  1837. });
  1838. expect(row).toMatchObject({ kind: "toolCall", display });
  1839. });
  1840. it("rejects an out-of-bounds CreateWorkflow causality graph in strict v4 tool rows", () => {
  1841. const base = {
  1842. rowId: 8,
  1843. turnId: "turn-1",
  1844. createdAt: 14,
  1845. createdAtSeq: 8,
  1846. kind: "toolCall",
  1847. toolCallId: "tool-create-workflow-graph-bounds",
  1848. toolName: "CreateWorkflow",
  1849. status: "success",
  1850. inputText: "",
  1851. };
  1852. const display = { kind: "create_workflow", ok: true, errorCount: 0, diagnostics: [] };
  1853. const step = {
  1854. id: "ask#1",
  1855. kind: "ask",
  1856. label: "a",
  1857. lane: "actor#1",
  1858. };
  1859. const participant = {
  1860. id: "unphased:actor#1",
  1861. phase: "unphased",
  1862. lane: "actor#1",
  1863. steps: ["ask#1"],
  1864. };
  1865. const graph = {
  1866. steps: [step],
  1867. lanes: [{ id: "actor#1" }],
  1868. participants: [participant],
  1869. handoffs: [],
  1870. };
  1871. // v4 行上的 display 不设门(docs/v4-refactor/10-protocol-spec.md §4.4.5):认不出来的载荷被
  1872. // 丢掉、row 本身仍然有效,而不是把整帧拒掉。所以本 helper 断言的是「这份图被携带了」——被丢
  1873. // 时主动抛错,好让下面每条 toThrow / not.toThrow 继续表达原来的意思。有界性没有放松:越界
  1874. // 载荷同样到不了 UI,变的只是代价(拒整帧、连带打掉订阅 → 卡片退化成纯文本)。
  1875. const parseWith = (causalityGraph: unknown) => {
  1876. const row = conversationRowSchema.parse({ ...base, display: { ...display, causalityGraph } });
  1877. if (row.kind !== "toolCall" || row.display === undefined) {
  1878. throw new Error("v4 row dropped the create_workflow display");
  1879. }
  1880. return row.display;
  1881. };
  1882. expect(() => parseWith(graph)).not.toThrow();
  1883. // 65 steps exceed the 64-step bound.
  1884. expect(() =>
  1885. parseWith({
  1886. ...graph,
  1887. steps: Array.from({ length: 65 }, (_, index) => ({ ...step, id: `ask#${index}` })),
  1888. }),
  1889. ).toThrow();
  1890. // A 129-char label exceeds the label bound.
  1891. expect(() => parseWith({ ...graph, steps: [{ ...step, label: "n".repeat(129) }] })).toThrow();
  1892. // 65 participants exceed the 64-participant bound.
  1893. expect(() =>
  1894. parseWith({
  1895. ...graph,
  1896. participants: Array.from({ length: 65 }, (_, index) => ({
  1897. ...participant,
  1898. id: `unphased:actor#1[${index}]`,
  1899. member: { index, of: 65 },
  1900. })),
  1901. }),
  1902. ).toThrow();
  1903. // 一张卡至少一个 step;member = {index ≥ 0, of ≥ 1} strict;many 只接受字面量 true。
  1904. expect(() =>
  1905. parseWith({
  1906. ...graph,
  1907. participants: [{ ...participant, id: "unphased:actor#1[1]", member: { index: 1, of: 2 } }],
  1908. }),
  1909. ).not.toThrow();
  1910. expect(() =>
  1911. parseWith({ ...graph, participants: [{ ...participant, member: { of: 2 } }] }),
  1912. ).toThrow();
  1913. // 交接边只有 {from, to, back?, types?}:分析器的 kind / certainty 不进展示载荷。
  1914. const handoff = { from: "unphased:actor#1", to: "unphased:actor#1" };
  1915. // 257 handoffs exceed the 256-handoff bound.
  1916. expect(() =>
  1917. parseWith({ ...graph, handoffs: Array.from({ length: 257 }, () => handoff) }),
  1918. ).toThrow();
  1919. // `types` 在场就是 1..8 个名字,每个 ≤ 128 字符。
  1920. expect(() =>
  1921. parseWith({ ...graph, handoffs: [{ ...handoff, types: ["Flaky"] }] }),
  1922. ).not.toThrow();
  1923. expect(() => parseWith({ ...graph, handoffs: [{ ...handoff, types: [""] }] })).toThrow();
  1924. });
  1925. it("accepts may-set lane-expansion copies with `source` on both protocol boundaries", () => {
  1926. // may-set 车道展开:一个 ask 站点变成每候选车道一份拷贝,`source` 记下展开自的站点 id
  1927. // (直播叠加的关联键)。字段是 additive 的,所以不带 source 的旧载荷照常验证。
  1928. const copy = {
  1929. id: "ask#2~actor#1",
  1930. kind: "ask",
  1931. label: "ask",
  1932. line: 7,
  1933. column: 58,
  1934. lane: "actor#1",
  1935. lanes: ["actor#1", "actor#2"],
  1936. source: "ask#2",
  1937. repeat: "serial",
  1938. };
  1939. const causalityGraph = {
  1940. steps: [copy, { ...copy, id: "ask#2~actor#2", lane: "actor#2" }],
  1941. lanes: [
  1942. { id: "actor#1", name: "black" },
  1943. { id: "actor#2", name: "white" },
  1944. ],
  1945. // 每条候选车道一张参与者卡,卡的 steps 指向该车道的拷贝 id。
  1946. participants: [
  1947. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#2~actor#1"] },
  1948. { id: "unphased:actor#2", phase: "unphased", lane: "actor#2", steps: ["ask#2~actor#2"] },
  1949. ],
  1950. handoffs: [
  1951. { from: "unphased:actor#1", to: "unphased:actor#2", back: true },
  1952. { from: "unphased:actor#2", to: "unphased:actor#1", back: true },
  1953. ],
  1954. sink: ["ask#2~actor#1", "ask#2~actor#2"],
  1955. };
  1956. const display = {
  1957. kind: "create_workflow",
  1958. ok: true,
  1959. errorCount: 0,
  1960. diagnostics: [],
  1961. causalityGraph,
  1962. };
  1963. // Legacy protocol: result.display superRefine.
  1964. const event = zcodeSessionEventSchema.parse({
  1965. eventId: "evt_tool_workflow_may_set",
  1966. seq: 18,
  1967. sessionId: "sess_1",
  1968. timestamp: 19,
  1969. type: "tool.updated",
  1970. payload: {
  1971. kind: "result",
  1972. toolCallId: "tool_workflow_may_set",
  1973. toolName: "CreateWorkflow",
  1974. duration: 7,
  1975. result: { success: true, content: "The workflow script compiled cleanly.", display },
  1976. },
  1977. });
  1978. expect(event.payload).toMatchObject({
  1979. kind: "result",
  1980. result: { display: { causalityGraph } },
  1981. });
  1982. // V4 rows: toolCallRow.display.
  1983. const base = {
  1984. rowId: 9,
  1985. turnId: "turn-1",
  1986. createdAt: 15,
  1987. createdAtSeq: 9,
  1988. kind: "toolCall",
  1989. toolCallId: "tool-create-workflow-may-set",
  1990. toolName: "CreateWorkflow",
  1991. status: "success",
  1992. inputText: "",
  1993. };
  1994. expect(conversationRowSchema.parse({ ...base, display })).toMatchObject({
  1995. display: { causalityGraph },
  1996. });
  1997. // 65 字符的 source 越界,整份载荷因此不被携带(不设门 = 丢卡,不是拒帧;§4.4.5)。
  1998. const overlongSourceRow = conversationRowSchema.parse({
  1999. ...base,
  2000. display: {
  2001. ...display,
  2002. causalityGraph: {
  2003. steps: [{ ...copy, source: "s".repeat(65) }],
  2004. lanes: causalityGraph.lanes,
  2005. participants: [],
  2006. handoffs: [],
  2007. },
  2008. },
  2009. });
  2010. expect(
  2011. overlongSourceRow.kind === "toolCall" ? overlongSourceRow.display : "unreachable",
  2012. ).toBeUndefined();
  2013. });
  2014. it("accepts the phase vocabulary on both protocol boundaries", () => {
  2015. // docs/dynamic-workflow/presentation.md:phases / phaseEdges / exits / step.phase 是一套
  2016. // 全有或全无的词汇表。四层 schema(contracts、tool-result-metadata、v4 rows、这份 v3
  2017. // 镜像)必须逐字段对齐——任一层漏改,.strict() 之下带阶段的工作流会整图验证失败、图
  2018. // 整块消失,正是 labelPattern/namePattern 在 0a8b059f40 上出过的事故。
  2019. const causalityGraph = {
  2020. steps: [
  2021. {
  2022. id: "world-read#1",
  2023. kind: "world-read",
  2024. label: "glob *.ts",
  2025. lane: "workspace",
  2026. // 首个标记之前的 step 落进保留的合成阶段。
  2027. phase: "unphased",
  2028. },
  2029. {
  2030. id: "ask#1",
  2031. kind: "ask",
  2032. label: "planner",
  2033. lane: "actor#1",
  2034. phase: "phase#1",
  2035. },
  2036. {
  2037. // 跨阶段拷贝:共享 helper 的站点被两个阶段各认领一份,`source` 是运行时站点 id。
  2038. id: "ask#2~phase#1",
  2039. kind: "ask",
  2040. label: "bench",
  2041. lane: "actor#2",
  2042. source: "ask#2",
  2043. phase: "phase#1",
  2044. },
  2045. {
  2046. id: "ask#2~phase#2",
  2047. kind: "ask",
  2048. label: "bench",
  2049. lane: "actor#2",
  2050. source: "ask#2",
  2051. phase: "phase#2",
  2052. },
  2053. ],
  2054. lanes: [
  2055. { id: "workspace" },
  2056. { id: "actor#1", name: "planner" },
  2057. { id: "actor#2", name: "bench" },
  2058. ],
  2059. // 参与者按阶段分卡:同一子代理在两个阶段各是一张卡(id 以阶段为前缀)。
  2060. participants: [
  2061. { id: "unphased:workspace", phase: "unphased", lane: "workspace", steps: ["world-read#1"] },
  2062. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  2063. { id: "phase#1:actor#2", phase: "phase#1", lane: "actor#2", steps: ["ask#2~phase#1"] },
  2064. { id: "phase#2:actor#2", phase: "phase#2", lane: "actor#2", steps: ["ask#2~phase#2"] },
  2065. ],
  2066. handoffs: [
  2067. { from: "unphased:workspace", to: "phase#1:actor#1" },
  2068. { from: "phase#1:actor#1", to: "phase#1:actor#2", types: ["Plan"] },
  2069. ],
  2070. phases: [
  2071. // `unphased` 无 name(UI 本地化显示);作者的阶段带原词与首个标记位置。
  2072. { id: "unphased" },
  2073. { id: "phase#1", name: "preflight", line: 1, column: 1 },
  2074. { id: "phase#2", name: "gate", line: 9, column: 3 },
  2075. ],
  2076. // 阶段边与 step 边同形:{from, to, back?}。回边 phase#2 → phase#1 = 循环跨两个阶段。
  2077. phaseEdges: [
  2078. { from: "unphased", to: "phase#1" },
  2079. { from: "phase#1", to: "phase#2" },
  2080. { from: "phase#2", to: "phase#1", back: true },
  2081. ],
  2082. // 阶段流(docs/dynamic-workflow/presentation.md「Streams」):channel 串起来的两个 future
  2083. // 阶段,只有 {from, to}——不是 runs after,没有 back。
  2084. phaseStreams: [{ from: "phase#1", to: "phase#2" }],
  2085. // 控制流可在其后正常完成的阶段(阶段视图的「阶段 → 返回物」箭头)。
  2086. exits: ["phase#2"],
  2087. sink: ["ask#1"],
  2088. };
  2089. const display = {
  2090. kind: "create_workflow",
  2091. ok: true,
  2092. errorCount: 0,
  2093. diagnostics: [],
  2094. causalityGraph,
  2095. };
  2096. // Legacy protocol: result.display superRefine.
  2097. const event = zcodeSessionEventSchema.parse({
  2098. eventId: "evt_tool_workflow_phases",
  2099. seq: 20,
  2100. sessionId: "sess_1",
  2101. timestamp: 21,
  2102. type: "tool.updated",
  2103. payload: {
  2104. kind: "result",
  2105. toolCallId: "tool_workflow_phases",
  2106. toolName: "CreateWorkflow",
  2107. duration: 7,
  2108. result: { success: true, content: "The workflow script compiled cleanly.", display },
  2109. },
  2110. });
  2111. expect(event.payload).toMatchObject({
  2112. kind: "result",
  2113. result: { display: { causalityGraph } },
  2114. });
  2115. // V4 rows: toolCallRow.display.
  2116. const base = {
  2117. rowId: 10,
  2118. turnId: "turn-1",
  2119. createdAt: 16,
  2120. createdAtSeq: 10,
  2121. kind: "toolCall",
  2122. toolCallId: "tool-create-workflow-phases",
  2123. toolName: "CreateWorkflow",
  2124. status: "success",
  2125. inputText: "",
  2126. };
  2127. expect(conversationRowSchema.parse({ ...base, display })).toMatchObject({
  2128. display: { causalityGraph },
  2129. });
  2130. // v4 行上的 display 不设门(docs/v4-refactor/10-protocol-spec.md §4.4.5):认不出来的载荷被
  2131. // 丢掉、row 本身仍然有效,而不是把整帧拒掉。所以本 helper 断言的是「这份图被携带了」——被丢
  2132. // 时主动抛错,好让下面每条 toThrow / not.toThrow 继续表达原来的意思。有界性没有放松:越界
  2133. // 载荷同样到不了 UI,变的只是代价(拒整帧、连带打掉订阅 → 卡片退化成纯文本)。
  2134. const parseWith = (graph: unknown) => {
  2135. const row = conversationRowSchema.parse({
  2136. ...base,
  2137. display: { ...display, causalityGraph: graph },
  2138. });
  2139. if (row.kind !== "toolCall" || row.display === undefined) {
  2140. throw new Error("v4 row dropped the create_workflow display");
  2141. }
  2142. return row.display;
  2143. };
  2144. // 有标记却零 step 的脚本产出**在场但空**的三个数组,handler 原样直通(不谎报
  2145. // truncated)。UI 的视图切换是「在场且非空」,所以空词汇表必须在两条边界上都可表示——
  2146. // 数组只有 .max() 上界,任何一层手滑加上 .min(1) 都会让那条直通路径整图验证失败。
  2147. const emptyVocabulary = {
  2148. steps: [],
  2149. lanes: [],
  2150. participants: [],
  2151. handoffs: [],
  2152. phases: [],
  2153. phaseEdges: [],
  2154. exits: [],
  2155. };
  2156. expect(() => parseWith(emptyVocabulary)).not.toThrow();
  2157. expect(
  2158. zcodeSessionEventSchema.parse({
  2159. eventId: "evt_tool_workflow_phases_empty",
  2160. seq: 21,
  2161. sessionId: "sess_1",
  2162. timestamp: 22,
  2163. type: "tool.updated",
  2164. payload: {
  2165. kind: "result",
  2166. toolCallId: "tool_workflow_phases_empty",
  2167. toolName: "CreateWorkflow",
  2168. duration: 7,
  2169. result: {
  2170. success: true,
  2171. content: "ok",
  2172. display: { ...display, causalityGraph: emptyVocabulary },
  2173. },
  2174. },
  2175. }).payload,
  2176. ).toMatchObject({ result: { display: { causalityGraph: emptyVocabulary } } });
  2177. // 33 phases exceed the 32-phase bound; the handler degrades the whole vocabulary
  2178. // before this boundary, so a payload this shape must be rejected outright.
  2179. expect(() =>
  2180. parseWith({
  2181. ...causalityGraph,
  2182. phases: Array.from({ length: 33 }, (_, index) => ({ id: `phase#${index + 1}` })),
  2183. }),
  2184. ).toThrow();
  2185. // 129 phase edges exceed the 128-edge bound.
  2186. expect(() =>
  2187. parseWith({
  2188. ...causalityGraph,
  2189. phaseEdges: Array.from({ length: 129 }, () => ({ from: "phase#1", to: "phase#2" })),
  2190. }),
  2191. ).toThrow();
  2192. // 129 phase streams exceed the same 128 bound; a stream carries no `back` and no kind.
  2193. expect(() =>
  2194. parseWith({
  2195. ...causalityGraph,
  2196. phaseStreams: Array.from({ length: 129 }, () => ({ from: "phase#1", to: "phase#2" })),
  2197. }),
  2198. ).toThrow();
  2199. for (const stream of [
  2200. { from: "phase#1", to: "phase#2", back: true },
  2201. { from: "phase#1", to: "phase#2", kind: "data" },
  2202. ]) {
  2203. expect(() => parseWith({ ...causalityGraph, phaseStreams: [stream] })).toThrow();
  2204. }
  2205. // 33 exits exceed the 32-phase bound (exits 与阶段表同一上界).
  2206. expect(() =>
  2207. parseWith({
  2208. ...causalityGraph,
  2209. exits: Array.from({ length: 33 }, (_, index) => `phase#${index + 1}`),
  2210. }),
  2211. ).toThrow();
  2212. // 阶段边与 step 边同形:分析器的 kind / certainty / exact 一个都不进载荷。
  2213. expect(() =>
  2214. parseWith({
  2215. ...causalityGraph,
  2216. phaseEdges: [
  2217. { from: "phase#1", to: "phase#2", kind: "seq", certainty: "maybe", exact: true },
  2218. ],
  2219. }),
  2220. ).toThrow();
  2221. });
  2222. it("gives the same verdict on the single-arrow shape on both protocol boundaries", () => {
  2223. // docs/dynamic-workflow/presentation.md:硬断——旧形状(边带 kind /
  2224. // certainty / exact,step 带 region / certainty,车道带 families,顶层带 regions)在
  2225. // v3 / v4 两份镜像上**同时**被拒;新形状({from, to, back?}、参与者 + 交接、exits)同时
  2226. // 通过。docs/dynamic-workflow/presentation.md 又砍掉 step 级 `edges` 与 `Lane.nesting`,
  2227. // 两者也在这里钉成同判。任一层漏改都会让同一份载荷在一条边界上通过、在另一条上整图消失。第三份
  2228. // (contracts)不在本包依赖里,由 contracts 自己的 create-workflow.test.ts 用同一组
  2229. // 样本钉住。
  2230. const eventOf = (causalityGraph: unknown) => ({
  2231. eventId: "evt_tool_workflow_single_arrow",
  2232. seq: 22,
  2233. sessionId: "sess_1",
  2234. timestamp: 23,
  2235. type: "tool.updated",
  2236. payload: {
  2237. kind: "result",
  2238. toolCallId: "tool_workflow_single_arrow",
  2239. toolName: "CreateWorkflow",
  2240. duration: 7,
  2241. result: {
  2242. success: true,
  2243. content: "ok",
  2244. display: {
  2245. kind: "create_workflow",
  2246. ok: true,
  2247. errorCount: 0,
  2248. diagnostics: [],
  2249. causalityGraph,
  2250. },
  2251. },
  2252. },
  2253. });
  2254. const rowOf = (causalityGraph: unknown) => ({
  2255. rowId: 11,
  2256. turnId: "turn-1",
  2257. createdAt: 17,
  2258. createdAtSeq: 11,
  2259. kind: "toolCall",
  2260. toolCallId: "tool-create-workflow-single-arrow",
  2261. toolName: "CreateWorkflow",
  2262. status: "success",
  2263. inputText: "",
  2264. display: {
  2265. kind: "create_workflow",
  2266. ok: true,
  2267. errorCount: 0,
  2268. diagnostics: [],
  2269. causalityGraph,
  2270. },
  2271. });
  2272. // 第二个判定问的是「v4 行**携带了**这份图吗」,不是「row 解析成功吗」:display 不设门后,
  2273. // 读不懂的载荷被丢而 row 仍然有效,按 success 问每个负例都会变成 true(§4.4.5)。
  2274. const verdicts = (causalityGraph: unknown) => {
  2275. const row = conversationRowSchema.safeParse(rowOf(causalityGraph));
  2276. return [
  2277. zcodeSessionEventSchema.safeParse(eventOf(causalityGraph)).success,
  2278. row.success && row.data.kind === "toolCall" && row.data.display !== undefined,
  2279. ];
  2280. };
  2281. const fresh = {
  2282. steps: [
  2283. { id: "ask#1", kind: "ask", label: "planner", lane: "actor#1", phase: "phase#1" },
  2284. { id: "ask#2", kind: "ask", label: "reviewer", lane: "actor#2", phase: "phase#2" },
  2285. ],
  2286. lanes: [
  2287. { id: "actor#1", name: "planner" },
  2288. { id: "actor#2", name: "reviewer" },
  2289. ],
  2290. participants: [
  2291. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  2292. {
  2293. id: "phase#2:actor#2[0]",
  2294. phase: "phase#2",
  2295. lane: "actor#2",
  2296. steps: ["ask#2"],
  2297. member: { index: 0, of: 2 },
  2298. },
  2299. {
  2300. id: "phase#2:actor#2[1]",
  2301. phase: "phase#2",
  2302. lane: "actor#2",
  2303. steps: ["ask#2"],
  2304. member: { index: 1, of: 2 },
  2305. },
  2306. ],
  2307. handoffs: [
  2308. { from: "phase#1:actor#1", to: "phase#2:actor#2[0]", types: ["Plan"] },
  2309. { from: "phase#1:actor#1", to: "phase#2:actor#2[1]", types: ["Plan"] },
  2310. { from: "phase#2:actor#2[0]", to: "phase#1:actor#1", back: true },
  2311. ],
  2312. phases: [
  2313. { id: "phase#1", name: "plan" },
  2314. { id: "phase#2", name: "review" },
  2315. ],
  2316. phaseEdges: [
  2317. { from: "phase#1", to: "phase#2" },
  2318. { from: "phase#2", to: "phase#1", back: true },
  2319. ],
  2320. exits: ["phase#2"],
  2321. sink: ["ask#2"],
  2322. };
  2323. expect(verdicts(fresh)).toEqual([true, true]);
  2324. const legacy = {
  2325. steps: [
  2326. {
  2327. id: "ask#1",
  2328. kind: "ask",
  2329. label: "planner",
  2330. lane: "actor#1",
  2331. region: "seq#1",
  2332. certainty: "always",
  2333. },
  2334. {
  2335. id: "ask#2",
  2336. kind: "ask",
  2337. label: "reviewer",
  2338. lane: "actor#2",
  2339. region: "loop#1",
  2340. certainty: "maybe",
  2341. },
  2342. ],
  2343. lanes: [
  2344. { id: "actor#1", name: "planner" },
  2345. { id: "actor#2", name: "reviewer", families: ["loop#1"] },
  2346. ],
  2347. regions: [
  2348. { id: "seq#1", kind: "seq" },
  2349. { id: "loop#1", kind: "loop", parent: "seq#1" },
  2350. ],
  2351. edges: [
  2352. { from: "ask#1", to: "ask#2", kind: "data", certainty: "always", exact: true },
  2353. { from: "ask#2", to: "ask#1", kind: "carry", certainty: "maybe" },
  2354. ],
  2355. sink: ["ask#2"],
  2356. };
  2357. expect(verdicts(legacy)).toEqual([false, false]);
  2358. // 逐个旧字段也各自被拒——不是只有整包旧载荷才拒。
  2359. const [freshStep] = fresh.steps;
  2360. const [freshLane] = fresh.lanes;
  2361. const [freshParticipant] = fresh.participants;
  2362. const [freshHandoff] = fresh.handoffs;
  2363. const { participants: _p, ...noParticipants } = fresh;
  2364. const { handoffs: _h, ...noHandoffs } = fresh;
  2365. for (const graph of [
  2366. { ...fresh, steps: [{ ...freshStep, region: "seq#1" }, fresh.steps[1]] },
  2367. { ...fresh, steps: [{ ...freshStep, certainty: "always" }, fresh.steps[1]] },
  2368. { ...fresh, lanes: [{ ...freshLane, families: ["loop#1"] }, fresh.lanes[1]] },
  2369. { ...fresh, lanes: [freshLane, { ...fresh.lanes[1], nesting: 2 }] },
  2370. { ...fresh, regions: [] },
  2371. // step 级 edges 整个字段都不在了。
  2372. { ...fresh, edges: [] },
  2373. { ...fresh, edges: [{ from: "ask#1", to: "ask#2" }] },
  2374. // 参与者 / 交接必填、strict、有界。
  2375. noParticipants,
  2376. noHandoffs,
  2377. {
  2378. ...fresh,
  2379. participants: [{ ...freshParticipant, steps: [] }, ...fresh.participants.slice(1)],
  2380. },
  2381. { ...fresh, participants: [{ ...freshParticipant, member: { index: -1, of: 2 } }] },
  2382. { ...fresh, participants: [{ ...freshParticipant, member: { index: 0, of: 0 } }] },
  2383. { ...fresh, participants: [{ ...freshParticipant, member: { index: 0 } }] },
  2384. { ...fresh, participants: [{ ...freshParticipant, many: false }] },
  2385. { ...fresh, participants: [{ ...freshParticipant, name: "planner" }] },
  2386. { ...fresh, handoffs: [{ ...freshHandoff, kind: "data" }] },
  2387. { ...fresh, handoffs: [{ ...freshHandoff, certainty: "always" }] },
  2388. { ...fresh, handoffs: [{ ...freshHandoff, exact: true }] },
  2389. { ...fresh, handoffs: [{ ...freshHandoff, back: false }] },
  2390. { ...fresh, handoffs: [{ ...freshHandoff, types: [] }] },
  2391. {
  2392. ...fresh,
  2393. handoffs: [{ ...freshHandoff, types: Array.from({ length: 9 }, (_, i) => `T${i}`) }],
  2394. },
  2395. { ...fresh, handoffs: [{ ...freshHandoff, types: ["t".repeat(129)] }] },
  2396. { ...fresh, phaseEdges: [{ from: "phase#1", to: "phase#2", kind: "seq" }] },
  2397. { ...fresh, phaseEdges: [{ from: "phase#1", to: "phase#2", back: "yes" }] },
  2398. { ...fresh, phaseEdges: [{ from: "phase#1", to: "phase#2", types: ["Plan"] }] },
  2399. ]) {
  2400. expect(verdicts(graph)).toEqual([false, false]);
  2401. }
  2402. // 新字段的合法变体在两条边界上同时通过。
  2403. for (const graph of [
  2404. {
  2405. ...fresh,
  2406. participants: [{ ...freshParticipant, many: true }, ...fresh.participants.slice(1)],
  2407. },
  2408. {
  2409. ...fresh,
  2410. handoffs: [{ ...freshHandoff, types: Array.from({ length: 8 }, (_, i) => `T${i}`) }],
  2411. },
  2412. { ...fresh, participants: [], handoffs: [] },
  2413. ]) {
  2414. expect(verdicts(graph)).toEqual([true, true]);
  2415. }
  2416. });
  2417. it("parses replayable session event batches", () => {
  2418. const batch = zcodeSessionEventsResultSchema.parse({
  2419. events: [
  2420. {
  2421. eventId: "evt_turn_1",
  2422. seq: 1,
  2423. sessionId: "sess_1",
  2424. timestamp: 2,
  2425. deliveryKind: "web-remote-replayable",
  2426. type: "turn.started",
  2427. payload: {
  2428. inputId: "t-sess_1-run",
  2429. input: "hello",
  2430. turnNumber: 1,
  2431. },
  2432. },
  2433. ],
  2434. });
  2435. expect(batch.events[0]?.deliveryKind).toBe("web-remote-replayable");
  2436. expect(batch.events[0]?.payload).toMatchObject({ inputId: "t-sess_1-run" });
  2437. });
  2438. it.each([undefined, "desktop-continuous", "web-remote-replayable"])(
  2439. "accepts the complete runtime turn.started payload (%s)",
  2440. (deliveryKind) => {
  2441. const event = zcodeSessionEventSchema.parse({
  2442. eventId: "evt_turn_runtime",
  2443. seq: 2,
  2444. sessionId: "sess_1",
  2445. turnId: "turn_1",
  2446. timestamp: 3,
  2447. deliveryKind,
  2448. type: "turn.started",
  2449. payload: {
  2450. turnNumber: 2,
  2451. executionStartedAt: 1789614547807.125,
  2452. input: "hello",
  2453. messageId: "msg_1",
  2454. foregroundExecutionId: "foreground_1",
  2455. backgroundSource: "subagent",
  2456. intent: {
  2457. sourceCommandId: "command_1",
  2458. queueItemId: "queue_1",
  2459. clientId: "bot",
  2460. kind: "sendText",
  2461. },
  2462. originMeta: { source: "bot" },
  2463. attachments: [{ name: "fixture.txt", mediaType: "text/plain" }],
  2464. },
  2465. });
  2466. expect(event.payload).toMatchObject({
  2467. executionStartedAt: 1789614547807.125,
  2468. messageId: "msg_1",
  2469. foregroundExecutionId: "foreground_1",
  2470. backgroundSource: "subagent",
  2471. intent: expect.objectContaining({ sourceCommandId: "command_1" }),
  2472. });
  2473. },
  2474. );
  2475. it("parses subagent message model-only inputs for replayable delivery", () => {
  2476. const event = zcodeSessionEventSchema.parse({
  2477. eventId: "evt_subagent_response",
  2478. seq: 2,
  2479. sessionId: "sess_1",
  2480. timestamp: 3,
  2481. deliveryKind: "web-remote-replayable",
  2482. type: "turn.started",
  2483. payload: {
  2484. inputId: "turn_subagent_response",
  2485. input: "<subagent-message>progress</subagent-message>",
  2486. inputSource: "subagent_message",
  2487. inputVisibility: "model-only",
  2488. turnNumber: 2,
  2489. },
  2490. });
  2491. expect(event.payload).toMatchObject({
  2492. inputSource: "subagent_message",
  2493. inputVisibility: "model-only",
  2494. });
  2495. });
  2496. it("parses persisted model-only subagent messages across the app/agent boundary", () => {
  2497. const message = zcodeUserMessageInfoSchema.parse({
  2498. messageId: "msg_subagent_response",
  2499. sessionId: "sess_1",
  2500. role: "user",
  2501. time: { created: 3 },
  2502. agent: "zcode-agent",
  2503. model,
  2504. source: "subagent_message",
  2505. visibility: "model-only",
  2506. });
  2507. expect(message.source).toBe("subagent_message");
  2508. });
  2509. it("parses strict workspace interaction preference updates", () => {
  2510. expect(
  2511. zcodeWorkspaceUpdateInteractionPreferencesParamsSchema.parse({
  2512. workspace,
  2513. preferences: {
  2514. askUserQuestionAutoResolutionEnabled: false,
  2515. },
  2516. }),
  2517. ).toEqual({
  2518. workspace,
  2519. preferences: {
  2520. askUserQuestionAutoResolutionEnabled: false,
  2521. },
  2522. });
  2523. expect(
  2524. zcodeWorkspaceUpdateInteractionPreferencesResultSchema.parse({
  2525. workspace,
  2526. askUserQuestionAutoResolutionEnabled: false,
  2527. snoozedInteractionCount: 2,
  2528. }),
  2529. ).toMatchObject({
  2530. askUserQuestionAutoResolutionEnabled: false,
  2531. snoozedInteractionCount: 2,
  2532. });
  2533. expect(() =>
  2534. zcodeWorkspaceUpdateInteractionPreferencesParamsSchema.parse({
  2535. workspace,
  2536. preferences: {
  2537. askUserQuestionAutoResolutionEnabled: false,
  2538. ignored: true,
  2539. },
  2540. }),
  2541. ).toThrow();
  2542. });
  2543. it("parses strict workspace ModelIO retention preference updates", () => {
  2544. expect(
  2545. zcodeWorkspaceUpdateModelIoPreferencesParamsSchema.parse({
  2546. workspace,
  2547. preferences: { fullRetentionEnabled: true },
  2548. }),
  2549. ).toEqual({
  2550. workspace,
  2551. preferences: { fullRetentionEnabled: true },
  2552. });
  2553. expect(
  2554. zcodeWorkspaceUpdateModelIoPreferencesResultSchema.parse({
  2555. workspace,
  2556. fullRetentionEnabled: true,
  2557. updatedSessionCount: 2,
  2558. }),
  2559. ).toMatchObject({
  2560. fullRetentionEnabled: true,
  2561. updatedSessionCount: 2,
  2562. });
  2563. expect(() =>
  2564. zcodeWorkspaceUpdateModelIoPreferencesParamsSchema.parse({
  2565. workspace,
  2566. preferences: { fullRetentionEnabled: true, ignored: true },
  2567. }),
  2568. ).toThrow();
  2569. });
  2570. it("validates ToolSearch startup preferences and defaults old Host responses off", () => {
  2571. expect(
  2572. zcodeSessionRuntimePreferencesResultSchema.parse({ nativeSearchEnhancementsEnabled: true })
  2573. .toolSearchMode,
  2574. ).toBe("off");
  2575. for (const mode of ["auto", "local", "off"]) {
  2576. expect(
  2577. zcodeSessionRuntimePreferencesResultSchema.parse({
  2578. nativeSearchEnhancementsEnabled: true,
  2579. toolSearchMode: mode,
  2580. }).toolSearchMode,
  2581. ).toBe(mode);
  2582. }
  2583. expect(
  2584. zcodeSessionRuntimePreferencesResultSchema.safeParse({
  2585. nativeSearchEnhancementsEnabled: true,
  2586. toolSearchMode: "native",
  2587. }).success,
  2588. ).toBe(false);
  2589. });
  2590. it("keeps runtime preference compatibility by defaulting missing fields", () => {
  2591. expect(DEFAULT_ZCODE_MODEL_CONTEXT_BUDGET_STRATEGY).toBe("preflight-v1");
  2592. expect(
  2593. zcodeSessionRuntimePreferencesResultSchema.parse({
  2594. nativeSearchEnhancementsEnabled: true,
  2595. }),
  2596. ).toMatchObject({
  2597. askUserQuestionAutoResolutionEnabled: true,
  2598. memoryEnabled: false,
  2599. modelContextBudgetStrategy: DEFAULT_ZCODE_MODEL_CONTEXT_BUDGET_STRATEGY,
  2600. });
  2601. expect(
  2602. zcodeSessionRuntimePreferencesResultSchema.parse({
  2603. nativeSearchEnhancementsEnabled: true,
  2604. askUserQuestionAutoResolutionEnabled: false,
  2605. modelContextBudgetStrategy: "preflight-v1",
  2606. }).askUserQuestionAutoResolutionEnabled,
  2607. ).toBe(false);
  2608. expect(() =>
  2609. zcodeSessionRuntimePreferencesResultSchema.parse({
  2610. nativeSearchEnhancementsEnabled: true,
  2611. modelContextBudgetStrategy: "unknown",
  2612. }),
  2613. ).toThrow();
  2614. });
  2615. it("accepts turn.completed cache stats and history round count from runtime events", () => {
  2616. const event = zcodeSessionEventSchema.parse({
  2617. type: "turn.completed",
  2618. eventId: "evt_1",
  2619. sessionId: "sess_1",
  2620. turnId: "turn_1",
  2621. seq: 2,
  2622. traceId: "trace_1",
  2623. timestamp: Date.now(),
  2624. deliveryKind: "desktop-continuous",
  2625. payload: {
  2626. response: "ok",
  2627. tokenCount: 2,
  2628. toolCallCount: 0,
  2629. historyRoundCount: 3,
  2630. duration: 123,
  2631. resultType: "success",
  2632. inputId: "run_1",
  2633. cacheStats: {
  2634. totalMessages: 4,
  2635. cachedMessages: 2,
  2636. lastCacheHit: true,
  2637. cacheReadTokens: 128,
  2638. },
  2639. },
  2640. });
  2641. expect(event.payload.cacheStats).toMatchObject({
  2642. cachedMessages: 2,
  2643. lastCacheHit: true,
  2644. });
  2645. expect(event.payload.historyRoundCount).toBe(3);
  2646. });
  2647. it("parses state.updated notifications as the core state sync primitive", () => {
  2648. const event = zcodeStateUpdatedNotificationSchema.parse({
  2649. type: "state.updated",
  2650. scope: "session",
  2651. workspace,
  2652. sessionId: "sess_1",
  2653. revision: 4,
  2654. reason: "model_changed",
  2655. patch: {
  2656. settings: {
  2657. model: {
  2658. current: model,
  2659. },
  2660. },
  2661. },
  2662. });
  2663. expect(event.revision).toBe(4);
  2664. });
  2665. it("workspace presentation rejects model facts", () => {
  2666. expect(() =>
  2667. zcodeWorkspacePresentationSchema.parse({
  2668. workspace,
  2669. mode: "build",
  2670. slashCommands: [],
  2671. model,
  2672. }),
  2673. ).toThrow();
  2674. });
  2675. });
  2676. describe("v4 workflowLaunch rows (direct-launch)", () => {
  2677. const meta = {
  2678. runId: "run-123",
  2679. toolCallId: "launch-abc",
  2680. name: "deep-research",
  2681. scope: "global" as const,
  2682. path: "/home/u/.zcode/workflows/deep-research.ts",
  2683. args: { topic: "adaptive concurrency", depth: 2 },
  2684. description: "Deep-dive a topic across the web and write a brief.",
  2685. };
  2686. it("parses a turnHeader row with origin workflowLaunch + meta", () => {
  2687. const row = conversationRowSchema.parse({
  2688. rowId: 1,
  2689. turnId: "turn-1",
  2690. createdAt: 10,
  2691. createdAtSeq: 1,
  2692. kind: "turnHeader",
  2693. origin: "workflowLaunch",
  2694. executionKind: "controlOnly",
  2695. state: "running",
  2696. startedAt: 10,
  2697. workflowLaunch: meta,
  2698. });
  2699. expect(row).toMatchObject({
  2700. kind: "turnHeader",
  2701. origin: "workflowLaunch",
  2702. workflowLaunch: meta,
  2703. });
  2704. });
  2705. it("parses a userInput row with origin workflowLaunch + meta (text still carried)", () => {
  2706. const row = conversationRowSchema.parse({
  2707. rowId: 2,
  2708. turnId: "turn-1",
  2709. createdAt: 10,
  2710. createdAtSeq: 2,
  2711. kind: "userInput",
  2712. text: 'Started the saved workflow "deep-research" (global) from the workflows hub as run run-123.',
  2713. origin: "workflowLaunch",
  2714. workflowLaunch: meta,
  2715. });
  2716. expect(row).toMatchObject({
  2717. kind: "userInput",
  2718. origin: "workflowLaunch",
  2719. workflowLaunch: meta,
  2720. });
  2721. });
  2722. it("rejects a description over the 500-char bound", () => {
  2723. expect(
  2724. workflowLaunchMetaSchema.safeParse({ ...meta, description: "x".repeat(501) }).success,
  2725. ).toBe(false);
  2726. expect(
  2727. workflowLaunchMetaSchema.safeParse({ ...meta, description: "x".repeat(500) }).success,
  2728. ).toBe(true);
  2729. });
  2730. it("rejects an args payload over the 4KB serialized bound", () => {
  2731. const bigArgs = { blob: "x".repeat(5000) };
  2732. expect(workflowLaunchMetaSchema.safeParse({ ...meta, args: bigArgs }).success).toBe(false);
  2733. });
  2734. it("rejects meta with missing runId or bad scope", () => {
  2735. expect(workflowLaunchMetaSchema.safeParse({ ...meta, runId: "" }).success).toBe(false);
  2736. expect(workflowLaunchMetaSchema.safeParse({ ...meta, scope: "team" }).success).toBe(false);
  2737. });
  2738. // 设置轮(docs/dynamic-workflow/launch.md「The settings turn」):同一份元数据,没有保存文件可指,
  2739. // 多一块 `amend` 说改了什么。
  2740. it("parses a settings-turn meta: no scope or path, an amend block with from/to ends", () => {
  2741. const settings = {
  2742. runId: "run-b",
  2743. toolCallId: "settings-abc",
  2744. name: "deep-research",
  2745. amend: {
  2746. predecessorRunId: "run-a",
  2747. subagentModel: { to: "zhipu/glm-5.3-flash" },
  2748. maxConcurrency: { from: 13, to: 4 },
  2749. ceiling: 13,
  2750. },
  2751. };
  2752. expect(workflowLaunchMetaSchema.parse(settings)).toEqual(settings);
  2753. // 无名 run 的设置轮不带名字(UI 换用兜底词,不拿 run id 当标题)。
  2754. const { name: _name, ...unnamed } = settings;
  2755. void _name;
  2756. expect(workflowLaunchMetaSchema.parse(unnamed)).toEqual(unnamed);
  2757. expect(
  2758. workflowLaunchMetaSchema.safeParse({
  2759. ...settings,
  2760. amend: { ...settings.amend, maxConcurrency: { to: 0 } },
  2761. }).success,
  2762. ).toBe(false);
  2763. expect(
  2764. workflowLaunchMetaSchema.safeParse({ ...settings, amend: { predecessorRunId: "" } }).success,
  2765. ).toBe(false);
  2766. });
  2767. // 就地生效的设置轮(docs/dynamic-workflow/concurrency.md):只改并发上限、run 又在飞时没有前驱,
  2768. // `predecessorRunId` 因此缺席——缺席本身就是「改的就是 runId 这一条」的信号(渲染端据它只出行)。
  2769. it("parses an in-place retune's settings-turn meta: no predecessorRunId at all", () => {
  2770. const retune = {
  2771. runId: "run-a",
  2772. toolCallId: "settings-xyz",
  2773. name: "deep-research",
  2774. amend: { maxConcurrency: { from: 13, to: 4 }, ceiling: 13 },
  2775. };
  2776. expect(workflowLaunchMetaSchema.parse(retune)).toEqual(retune);
  2777. // 在场时仍要是一个真 run id:可选不等于可空、也不等于可空串。
  2778. expect(
  2779. workflowLaunchMetaSchema.safeParse({
  2780. ...retune,
  2781. amend: { ...retune.amend, predecessorRunId: null },
  2782. }).success,
  2783. ).toBe(false);
  2784. });
  2785. });
  2786. // 类型策略相互独立:辅助对话继承项目且隐藏,但仍能接受用户输入。
  2787. describe("session kind policies", () => {
  2788. it.each([
  2789. ["interactive", false, false],
  2790. ["fork", false, false],
  2791. ["workflow_parent", false, false],
  2792. ["subagent_child", true, true],
  2793. ["workflow_child", true, true],
  2794. ["nested_workflow_child", true, true],
  2795. ["selection_side_chat", true, false],
  2796. [undefined, false, false],
  2797. ["unknown", false, false],
  2798. ] as const)("%s preserves its project/list and input policy", (kind, auxiliary, readonly) => {
  2799. expect(isAuxiliarySessionKind(kind)).toBe(auxiliary);
  2800. expect(isReadonlyAgentSessionKind(kind)).toBe(readonly);
  2801. });
  2802. });