zcodeProtocol.test.ts 92 KB

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