zcodeProtocol.test.ts 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922
  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. // 65 participants exceed the 64-participant bound.
  1889. expect(() =>
  1890. parseWith({
  1891. ...graph,
  1892. participants: Array.from({ length: 65 }, (_, index) => ({
  1893. ...participant,
  1894. id: `unphased:actor#1[${index}]`,
  1895. member: { index, of: 65 },
  1896. })),
  1897. }),
  1898. ).toThrow();
  1899. // 一张卡至少一个 step;member = {index ≥ 0, of ≥ 1} strict;many 只接受字面量 true。
  1900. expect(() =>
  1901. parseWith({
  1902. ...graph,
  1903. participants: [{ ...participant, id: "unphased:actor#1[1]", member: { index: 1, of: 2 } }],
  1904. }),
  1905. ).not.toThrow();
  1906. expect(() =>
  1907. parseWith({ ...graph, participants: [{ ...participant, member: { of: 2 } }] }),
  1908. ).toThrow();
  1909. // 交接边只有 {from, to, back?, types?}:分析器的 kind / certainty 不进展示载荷。
  1910. const handoff = { from: "unphased:actor#1", to: "unphased:actor#1" };
  1911. // 257 handoffs exceed the 256-handoff bound.
  1912. expect(() =>
  1913. parseWith({ ...graph, handoffs: Array.from({ length: 257 }, () => handoff) }),
  1914. ).toThrow();
  1915. // `types` 在场就是 1..8 个名字,每个 ≤ 128 字符。
  1916. expect(() =>
  1917. parseWith({ ...graph, handoffs: [{ ...handoff, types: ["Flaky"] }] }),
  1918. ).not.toThrow();
  1919. expect(() => parseWith({ ...graph, handoffs: [{ ...handoff, types: [""] }] })).toThrow();
  1920. });
  1921. it("accepts may-set lane-expansion copies with `source` on both protocol boundaries", () => {
  1922. // may-set 车道展开:一个 ask 站点变成每候选车道一份拷贝,`source` 记下展开自的站点 id
  1923. // (直播叠加的关联键)。字段是 additive 的,所以不带 source 的旧载荷照常验证。
  1924. const copy = {
  1925. id: "ask#2~actor#1",
  1926. kind: "ask",
  1927. label: "ask",
  1928. line: 7,
  1929. column: 58,
  1930. lane: "actor#1",
  1931. lanes: ["actor#1", "actor#2"],
  1932. source: "ask#2",
  1933. repeat: "serial",
  1934. };
  1935. const causalityGraph = {
  1936. steps: [copy, { ...copy, id: "ask#2~actor#2", lane: "actor#2" }],
  1937. lanes: [
  1938. { id: "actor#1", name: "black" },
  1939. { id: "actor#2", name: "white" },
  1940. ],
  1941. // 每条候选车道一张参与者卡,卡的 steps 指向该车道的拷贝 id。
  1942. participants: [
  1943. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#2~actor#1"] },
  1944. { id: "unphased:actor#2", phase: "unphased", lane: "actor#2", steps: ["ask#2~actor#2"] },
  1945. ],
  1946. handoffs: [
  1947. { from: "unphased:actor#1", to: "unphased:actor#2", back: true },
  1948. { from: "unphased:actor#2", to: "unphased:actor#1", back: true },
  1949. ],
  1950. sink: ["ask#2~actor#1", "ask#2~actor#2"],
  1951. };
  1952. const display = {
  1953. kind: "create_workflow",
  1954. ok: true,
  1955. errorCount: 0,
  1956. diagnostics: [],
  1957. causalityGraph,
  1958. };
  1959. // Legacy protocol: result.display superRefine.
  1960. const event = zcodeSessionEventSchema.parse({
  1961. eventId: "evt_tool_workflow_may_set",
  1962. seq: 18,
  1963. sessionId: "sess_1",
  1964. timestamp: 19,
  1965. type: "tool.updated",
  1966. payload: {
  1967. kind: "result",
  1968. toolCallId: "tool_workflow_may_set",
  1969. toolName: "CreateWorkflow",
  1970. duration: 7,
  1971. result: { success: true, content: "The workflow script compiled cleanly.", display },
  1972. },
  1973. });
  1974. expect(event.payload).toMatchObject({
  1975. kind: "result",
  1976. result: { display: { causalityGraph } },
  1977. });
  1978. // V4 rows: toolCallRow.display.
  1979. const base = {
  1980. rowId: 9,
  1981. turnId: "turn-1",
  1982. createdAt: 15,
  1983. createdAtSeq: 9,
  1984. kind: "toolCall",
  1985. toolCallId: "tool-create-workflow-may-set",
  1986. toolName: "CreateWorkflow",
  1987. status: "success",
  1988. inputText: "",
  1989. };
  1990. expect(conversationRowSchema.parse({ ...base, display })).toMatchObject({
  1991. display: { causalityGraph },
  1992. });
  1993. // 65 字符的 source 越界,整份载荷因此不被携带(不设门 = 丢卡,不是拒帧;§4.4.5)。
  1994. const overlongSourceRow = conversationRowSchema.parse({
  1995. ...base,
  1996. display: {
  1997. ...display,
  1998. causalityGraph: {
  1999. steps: [{ ...copy, source: "s".repeat(65) }],
  2000. lanes: causalityGraph.lanes,
  2001. participants: [],
  2002. handoffs: [],
  2003. },
  2004. },
  2005. });
  2006. expect(
  2007. overlongSourceRow.kind === "toolCall" ? overlongSourceRow.display : "unreachable",
  2008. ).toBeUndefined();
  2009. });
  2010. it("accepts the phase vocabulary on both protocol boundaries", () => {
  2011. // docs/dynamic-workflow/presentation.md:phases / phaseEdges / exits / step.phase 是一套
  2012. // 全有或全无的词汇表。四层 schema(contracts、tool-result-metadata、v4 rows、这份 v3
  2013. // 镜像)必须逐字段对齐——任一层漏改,.strict() 之下带阶段的工作流会整图验证失败、图
  2014. // 整块消失,正是 labelPattern/namePattern 在 0a8b059f40 上出过的事故。
  2015. const causalityGraph = {
  2016. steps: [
  2017. {
  2018. id: "world-read#1",
  2019. kind: "world-read",
  2020. label: "glob *.ts",
  2021. lane: "workspace",
  2022. // 首个标记之前的 step 落进保留的合成阶段。
  2023. phase: "unphased",
  2024. },
  2025. {
  2026. id: "ask#1",
  2027. kind: "ask",
  2028. label: "planner",
  2029. lane: "actor#1",
  2030. phase: "phase#1",
  2031. },
  2032. {
  2033. // 跨阶段拷贝:共享 helper 的站点被两个阶段各认领一份,`source` 是运行时站点 id。
  2034. id: "ask#2~phase#1",
  2035. kind: "ask",
  2036. label: "bench",
  2037. lane: "actor#2",
  2038. source: "ask#2",
  2039. phase: "phase#1",
  2040. },
  2041. {
  2042. id: "ask#2~phase#2",
  2043. kind: "ask",
  2044. label: "bench",
  2045. lane: "actor#2",
  2046. source: "ask#2",
  2047. phase: "phase#2",
  2048. },
  2049. ],
  2050. lanes: [
  2051. { id: "workspace" },
  2052. { id: "actor#1", name: "planner" },
  2053. { id: "actor#2", name: "bench" },
  2054. ],
  2055. // 参与者按阶段分卡:同一子代理在两个阶段各是一张卡(id 以阶段为前缀)。
  2056. participants: [
  2057. { id: "unphased:workspace", phase: "unphased", lane: "workspace", steps: ["world-read#1"] },
  2058. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  2059. { id: "phase#1:actor#2", phase: "phase#1", lane: "actor#2", steps: ["ask#2~phase#1"] },
  2060. { id: "phase#2:actor#2", phase: "phase#2", lane: "actor#2", steps: ["ask#2~phase#2"] },
  2061. ],
  2062. handoffs: [
  2063. { from: "unphased:workspace", to: "phase#1:actor#1" },
  2064. { from: "phase#1:actor#1", to: "phase#1:actor#2", types: ["Plan"] },
  2065. ],
  2066. phases: [
  2067. // `unphased` 无 name(UI 本地化显示);作者的阶段带原词与首个标记位置。
  2068. { id: "unphased" },
  2069. { id: "phase#1", name: "preflight", line: 1, column: 1 },
  2070. { id: "phase#2", name: "gate", line: 9, column: 3 },
  2071. ],
  2072. // 阶段边与 step 边同形:{from, to, back?}。回边 phase#2 → phase#1 = 循环跨两个阶段。
  2073. phaseEdges: [
  2074. { from: "unphased", to: "phase#1" },
  2075. { from: "phase#1", to: "phase#2" },
  2076. { from: "phase#2", to: "phase#1", back: true },
  2077. ],
  2078. // 阶段流(docs/dynamic-workflow/presentation.md「Streams」):channel 串起来的两个 future
  2079. // 阶段,只有 {from, to}——不是 runs after,没有 back。
  2080. phaseStreams: [{ from: "phase#1", to: "phase#2" }],
  2081. // 控制流可在其后正常完成的阶段(阶段视图的「阶段 → 返回物」箭头)。
  2082. exits: ["phase#2"],
  2083. sink: ["ask#1"],
  2084. };
  2085. const display = {
  2086. kind: "create_workflow",
  2087. ok: true,
  2088. errorCount: 0,
  2089. diagnostics: [],
  2090. causalityGraph,
  2091. };
  2092. // Legacy protocol: result.display superRefine.
  2093. const event = zcodeSessionEventSchema.parse({
  2094. eventId: "evt_tool_workflow_phases",
  2095. seq: 20,
  2096. sessionId: "sess_1",
  2097. timestamp: 21,
  2098. type: "tool.updated",
  2099. payload: {
  2100. kind: "result",
  2101. toolCallId: "tool_workflow_phases",
  2102. toolName: "CreateWorkflow",
  2103. duration: 7,
  2104. result: { success: true, content: "The workflow script compiled cleanly.", display },
  2105. },
  2106. });
  2107. expect(event.payload).toMatchObject({
  2108. kind: "result",
  2109. result: { display: { causalityGraph } },
  2110. });
  2111. // V4 rows: toolCallRow.display.
  2112. const base = {
  2113. rowId: 10,
  2114. turnId: "turn-1",
  2115. createdAt: 16,
  2116. createdAtSeq: 10,
  2117. kind: "toolCall",
  2118. toolCallId: "tool-create-workflow-phases",
  2119. toolName: "CreateWorkflow",
  2120. status: "success",
  2121. inputText: "",
  2122. };
  2123. expect(conversationRowSchema.parse({ ...base, display })).toMatchObject({
  2124. display: { causalityGraph },
  2125. });
  2126. // v4 行上的 display 不设门(docs/v4-refactor/10-protocol-spec.md §4.4.5):认不出来的载荷被
  2127. // 丢掉、row 本身仍然有效,而不是把整帧拒掉。所以本 helper 断言的是「这份图被携带了」——被丢
  2128. // 时主动抛错,好让下面每条 toThrow / not.toThrow 继续表达原来的意思。有界性没有放松:越界
  2129. // 载荷同样到不了 UI,变的只是代价(拒整帧、连带打掉订阅 → 卡片退化成纯文本)。
  2130. const parseWith = (graph: unknown) => {
  2131. const row = conversationRowSchema.parse({
  2132. ...base,
  2133. display: { ...display, causalityGraph: graph },
  2134. });
  2135. if (row.kind !== "toolCall" || row.display === undefined) {
  2136. throw new Error("v4 row dropped the create_workflow display");
  2137. }
  2138. return row.display;
  2139. };
  2140. // 有标记却零 step 的脚本产出**在场但空**的三个数组,handler 原样直通(不谎报
  2141. // truncated)。UI 的视图切换是「在场且非空」,所以空词汇表必须在两条边界上都可表示——
  2142. // 数组只有 .max() 上界,任何一层手滑加上 .min(1) 都会让那条直通路径整图验证失败。
  2143. const emptyVocabulary = {
  2144. steps: [],
  2145. lanes: [],
  2146. participants: [],
  2147. handoffs: [],
  2148. phases: [],
  2149. phaseEdges: [],
  2150. exits: [],
  2151. };
  2152. expect(() => parseWith(emptyVocabulary)).not.toThrow();
  2153. expect(
  2154. zcodeSessionEventSchema.parse({
  2155. eventId: "evt_tool_workflow_phases_empty",
  2156. seq: 21,
  2157. sessionId: "sess_1",
  2158. timestamp: 22,
  2159. type: "tool.updated",
  2160. payload: {
  2161. kind: "result",
  2162. toolCallId: "tool_workflow_phases_empty",
  2163. toolName: "CreateWorkflow",
  2164. duration: 7,
  2165. result: {
  2166. success: true,
  2167. content: "ok",
  2168. display: { ...display, causalityGraph: emptyVocabulary },
  2169. },
  2170. },
  2171. }).payload,
  2172. ).toMatchObject({ result: { display: { causalityGraph: emptyVocabulary } } });
  2173. // 33 phases exceed the 32-phase bound; the handler degrades the whole vocabulary
  2174. // before this boundary, so a payload this shape must be rejected outright.
  2175. expect(() =>
  2176. parseWith({
  2177. ...causalityGraph,
  2178. phases: Array.from({ length: 33 }, (_, index) => ({ id: `phase#${index + 1}` })),
  2179. }),
  2180. ).toThrow();
  2181. // 129 phase edges exceed the 128-edge bound.
  2182. expect(() =>
  2183. parseWith({
  2184. ...causalityGraph,
  2185. phaseEdges: Array.from({ length: 129 }, () => ({ from: "phase#1", to: "phase#2" })),
  2186. }),
  2187. ).toThrow();
  2188. // 129 phase streams exceed the same 128 bound; a stream carries no `back` and no kind.
  2189. expect(() =>
  2190. parseWith({
  2191. ...causalityGraph,
  2192. phaseStreams: Array.from({ length: 129 }, () => ({ from: "phase#1", to: "phase#2" })),
  2193. }),
  2194. ).toThrow();
  2195. for (const stream of [
  2196. { from: "phase#1", to: "phase#2", back: true },
  2197. { from: "phase#1", to: "phase#2", kind: "data" },
  2198. ]) {
  2199. expect(() => parseWith({ ...causalityGraph, phaseStreams: [stream] })).toThrow();
  2200. }
  2201. // 33 exits exceed the 32-phase bound (exits 与阶段表同一上界).
  2202. expect(() =>
  2203. parseWith({
  2204. ...causalityGraph,
  2205. exits: Array.from({ length: 33 }, (_, index) => `phase#${index + 1}`),
  2206. }),
  2207. ).toThrow();
  2208. // 阶段边与 step 边同形:分析器的 kind / certainty / exact 一个都不进载荷。
  2209. expect(() =>
  2210. parseWith({
  2211. ...causalityGraph,
  2212. phaseEdges: [
  2213. { from: "phase#1", to: "phase#2", kind: "seq", certainty: "maybe", exact: true },
  2214. ],
  2215. }),
  2216. ).toThrow();
  2217. });
  2218. it("gives the same verdict on the single-arrow shape on both protocol boundaries", () => {
  2219. // docs/dynamic-workflow/presentation.md:硬断——旧形状(边带 kind /
  2220. // certainty / exact,step 带 region / certainty,车道带 families,顶层带 regions)在
  2221. // v3 / v4 两份镜像上**同时**被拒;新形状({from, to, back?}、参与者 + 交接、exits)同时
  2222. // 通过。docs/dynamic-workflow/presentation.md 又砍掉 step 级 `edges` 与 `Lane.nesting`,
  2223. // 两者也在这里钉成同判。任一层漏改都会让同一份载荷在一条边界上通过、在另一条上整图消失。第三份
  2224. // (contracts)不在本包依赖里,由 contracts 自己的 create-workflow.test.ts 用同一组
  2225. // 样本钉住。
  2226. const eventOf = (causalityGraph: unknown) => ({
  2227. eventId: "evt_tool_workflow_single_arrow",
  2228. seq: 22,
  2229. sessionId: "sess_1",
  2230. timestamp: 23,
  2231. type: "tool.updated",
  2232. payload: {
  2233. kind: "result",
  2234. toolCallId: "tool_workflow_single_arrow",
  2235. toolName: "CreateWorkflow",
  2236. duration: 7,
  2237. result: {
  2238. success: true,
  2239. content: "ok",
  2240. display: {
  2241. kind: "create_workflow",
  2242. ok: true,
  2243. errorCount: 0,
  2244. diagnostics: [],
  2245. causalityGraph,
  2246. },
  2247. },
  2248. },
  2249. });
  2250. const rowOf = (causalityGraph: unknown) => ({
  2251. rowId: 11,
  2252. turnId: "turn-1",
  2253. createdAt: 17,
  2254. createdAtSeq: 11,
  2255. kind: "toolCall",
  2256. toolCallId: "tool-create-workflow-single-arrow",
  2257. toolName: "CreateWorkflow",
  2258. status: "success",
  2259. inputText: "",
  2260. display: {
  2261. kind: "create_workflow",
  2262. ok: true,
  2263. errorCount: 0,
  2264. diagnostics: [],
  2265. causalityGraph,
  2266. },
  2267. });
  2268. // 第二个判定问的是「v4 行**携带了**这份图吗」,不是「row 解析成功吗」:display 不设门后,
  2269. // 读不懂的载荷被丢而 row 仍然有效,按 success 问每个负例都会变成 true(§4.4.5)。
  2270. const verdicts = (causalityGraph: unknown) => {
  2271. const row = conversationRowSchema.safeParse(rowOf(causalityGraph));
  2272. return [
  2273. zcodeSessionEventSchema.safeParse(eventOf(causalityGraph)).success,
  2274. row.success && row.data.kind === "toolCall" && row.data.display !== undefined,
  2275. ];
  2276. };
  2277. const fresh = {
  2278. steps: [
  2279. { id: "ask#1", kind: "ask", label: "planner", lane: "actor#1", phase: "phase#1" },
  2280. { id: "ask#2", kind: "ask", label: "reviewer", lane: "actor#2", phase: "phase#2" },
  2281. ],
  2282. lanes: [
  2283. { id: "actor#1", name: "planner" },
  2284. { id: "actor#2", name: "reviewer" },
  2285. ],
  2286. participants: [
  2287. { id: "phase#1:actor#1", phase: "phase#1", lane: "actor#1", steps: ["ask#1"] },
  2288. {
  2289. id: "phase#2:actor#2[0]",
  2290. phase: "phase#2",
  2291. lane: "actor#2",
  2292. steps: ["ask#2"],
  2293. member: { index: 0, of: 2 },
  2294. },
  2295. {
  2296. id: "phase#2:actor#2[1]",
  2297. phase: "phase#2",
  2298. lane: "actor#2",
  2299. steps: ["ask#2"],
  2300. member: { index: 1, of: 2 },
  2301. },
  2302. ],
  2303. handoffs: [
  2304. { from: "phase#1:actor#1", to: "phase#2:actor#2[0]", types: ["Plan"] },
  2305. { from: "phase#1:actor#1", to: "phase#2:actor#2[1]", types: ["Plan"] },
  2306. { from: "phase#2:actor#2[0]", to: "phase#1:actor#1", back: true },
  2307. ],
  2308. phases: [
  2309. { id: "phase#1", name: "plan" },
  2310. { id: "phase#2", name: "review" },
  2311. ],
  2312. phaseEdges: [
  2313. { from: "phase#1", to: "phase#2" },
  2314. { from: "phase#2", to: "phase#1", back: true },
  2315. ],
  2316. exits: ["phase#2"],
  2317. sink: ["ask#2"],
  2318. };
  2319. expect(verdicts(fresh)).toEqual([true, true]);
  2320. const legacy = {
  2321. steps: [
  2322. {
  2323. id: "ask#1",
  2324. kind: "ask",
  2325. label: "planner",
  2326. lane: "actor#1",
  2327. region: "seq#1",
  2328. certainty: "always",
  2329. },
  2330. {
  2331. id: "ask#2",
  2332. kind: "ask",
  2333. label: "reviewer",
  2334. lane: "actor#2",
  2335. region: "loop#1",
  2336. certainty: "maybe",
  2337. },
  2338. ],
  2339. lanes: [
  2340. { id: "actor#1", name: "planner" },
  2341. { id: "actor#2", name: "reviewer", families: ["loop#1"] },
  2342. ],
  2343. regions: [
  2344. { id: "seq#1", kind: "seq" },
  2345. { id: "loop#1", kind: "loop", parent: "seq#1" },
  2346. ],
  2347. edges: [
  2348. { from: "ask#1", to: "ask#2", kind: "data", certainty: "always", exact: true },
  2349. { from: "ask#2", to: "ask#1", kind: "carry", certainty: "maybe" },
  2350. ],
  2351. sink: ["ask#2"],
  2352. };
  2353. expect(verdicts(legacy)).toEqual([false, false]);
  2354. // 逐个旧字段也各自被拒——不是只有整包旧载荷才拒。
  2355. const [freshStep] = fresh.steps;
  2356. const [freshLane] = fresh.lanes;
  2357. const [freshParticipant] = fresh.participants;
  2358. const [freshHandoff] = fresh.handoffs;
  2359. const { participants: _p, ...noParticipants } = fresh;
  2360. const { handoffs: _h, ...noHandoffs } = fresh;
  2361. for (const graph of [
  2362. { ...fresh, steps: [{ ...freshStep, region: "seq#1" }, fresh.steps[1]] },
  2363. { ...fresh, steps: [{ ...freshStep, certainty: "always" }, fresh.steps[1]] },
  2364. { ...fresh, lanes: [{ ...freshLane, families: ["loop#1"] }, fresh.lanes[1]] },
  2365. { ...fresh, lanes: [freshLane, { ...fresh.lanes[1], nesting: 2 }] },
  2366. { ...fresh, regions: [] },
  2367. // step 级 edges 整个字段都不在了。
  2368. { ...fresh, edges: [] },
  2369. { ...fresh, edges: [{ from: "ask#1", to: "ask#2" }] },
  2370. // 参与者 / 交接必填、strict、有界。
  2371. noParticipants,
  2372. noHandoffs,
  2373. {
  2374. ...fresh,
  2375. participants: [{ ...freshParticipant, steps: [] }, ...fresh.participants.slice(1)],
  2376. },
  2377. { ...fresh, participants: [{ ...freshParticipant, member: { index: -1, of: 2 } }] },
  2378. { ...fresh, participants: [{ ...freshParticipant, member: { index: 0, of: 0 } }] },
  2379. { ...fresh, participants: [{ ...freshParticipant, member: { index: 0 } }] },
  2380. { ...fresh, participants: [{ ...freshParticipant, many: false }] },
  2381. { ...fresh, participants: [{ ...freshParticipant, name: "planner" }] },
  2382. { ...fresh, handoffs: [{ ...freshHandoff, kind: "data" }] },
  2383. { ...fresh, handoffs: [{ ...freshHandoff, certainty: "always" }] },
  2384. { ...fresh, handoffs: [{ ...freshHandoff, exact: true }] },
  2385. { ...fresh, handoffs: [{ ...freshHandoff, back: false }] },
  2386. { ...fresh, handoffs: [{ ...freshHandoff, types: [] }] },
  2387. {
  2388. ...fresh,
  2389. handoffs: [{ ...freshHandoff, types: Array.from({ length: 9 }, (_, i) => `T${i}`) }],
  2390. },
  2391. { ...fresh, handoffs: [{ ...freshHandoff, types: ["t".repeat(129)] }] },
  2392. { ...fresh, phaseEdges: [{ from: "phase#1", to: "phase#2", kind: "seq" }] },
  2393. { ...fresh, phaseEdges: [{ from: "phase#1", to: "phase#2", back: "yes" }] },
  2394. { ...fresh, phaseEdges: [{ from: "phase#1", to: "phase#2", types: ["Plan"] }] },
  2395. ]) {
  2396. expect(verdicts(graph)).toEqual([false, false]);
  2397. }
  2398. // 新字段的合法变体在两条边界上同时通过。
  2399. for (const graph of [
  2400. {
  2401. ...fresh,
  2402. participants: [{ ...freshParticipant, many: true }, ...fresh.participants.slice(1)],
  2403. },
  2404. {
  2405. ...fresh,
  2406. handoffs: [{ ...freshHandoff, types: Array.from({ length: 8 }, (_, i) => `T${i}`) }],
  2407. },
  2408. { ...fresh, participants: [], handoffs: [] },
  2409. ]) {
  2410. expect(verdicts(graph)).toEqual([true, true]);
  2411. }
  2412. });
  2413. it("parses replayable session event batches", () => {
  2414. const batch = zcodeSessionEventsResultSchema.parse({
  2415. events: [
  2416. {
  2417. eventId: "evt_turn_1",
  2418. seq: 1,
  2419. sessionId: "sess_1",
  2420. timestamp: 2,
  2421. deliveryKind: "web-remote-replayable",
  2422. type: "turn.started",
  2423. payload: {
  2424. inputId: "t-sess_1-run",
  2425. input: "hello",
  2426. turnNumber: 1,
  2427. },
  2428. },
  2429. ],
  2430. });
  2431. expect(batch.events[0]?.deliveryKind).toBe("web-remote-replayable");
  2432. expect(batch.events[0]?.payload).toMatchObject({ inputId: "t-sess_1-run" });
  2433. });
  2434. it.each([undefined, "desktop-continuous", "web-remote-replayable"])(
  2435. "accepts the complete runtime turn.started payload (%s)",
  2436. (deliveryKind) => {
  2437. const event = zcodeSessionEventSchema.parse({
  2438. eventId: "evt_turn_runtime",
  2439. seq: 2,
  2440. sessionId: "sess_1",
  2441. turnId: "turn_1",
  2442. timestamp: 3,
  2443. deliveryKind,
  2444. type: "turn.started",
  2445. payload: {
  2446. turnNumber: 2,
  2447. executionStartedAt: 1789614547807.125,
  2448. input: "hello",
  2449. messageId: "msg_1",
  2450. foregroundExecutionId: "foreground_1",
  2451. backgroundSource: "subagent",
  2452. intent: {
  2453. sourceCommandId: "command_1",
  2454. queueItemId: "queue_1",
  2455. clientId: "bot",
  2456. kind: "sendText",
  2457. },
  2458. originMeta: { source: "bot" },
  2459. attachments: [{ name: "fixture.txt", mediaType: "text/plain" }],
  2460. },
  2461. });
  2462. expect(event.payload).toMatchObject({
  2463. executionStartedAt: 1789614547807.125,
  2464. messageId: "msg_1",
  2465. foregroundExecutionId: "foreground_1",
  2466. backgroundSource: "subagent",
  2467. intent: expect.objectContaining({ sourceCommandId: "command_1" }),
  2468. });
  2469. },
  2470. );
  2471. it("parses subagent message model-only inputs for replayable delivery", () => {
  2472. const event = zcodeSessionEventSchema.parse({
  2473. eventId: "evt_subagent_response",
  2474. seq: 2,
  2475. sessionId: "sess_1",
  2476. timestamp: 3,
  2477. deliveryKind: "web-remote-replayable",
  2478. type: "turn.started",
  2479. payload: {
  2480. inputId: "turn_subagent_response",
  2481. input: "<subagent-message>progress</subagent-message>",
  2482. inputSource: "subagent_message",
  2483. inputVisibility: "model-only",
  2484. turnNumber: 2,
  2485. },
  2486. });
  2487. expect(event.payload).toMatchObject({
  2488. inputSource: "subagent_message",
  2489. inputVisibility: "model-only",
  2490. });
  2491. });
  2492. it("parses persisted model-only subagent messages across the app/agent boundary", () => {
  2493. const message = zcodeUserMessageInfoSchema.parse({
  2494. messageId: "msg_subagent_response",
  2495. sessionId: "sess_1",
  2496. role: "user",
  2497. time: { created: 3 },
  2498. agent: "zcode-agent",
  2499. model,
  2500. source: "subagent_message",
  2501. visibility: "model-only",
  2502. });
  2503. expect(message.source).toBe("subagent_message");
  2504. });
  2505. it("parses strict workspace interaction preference updates", () => {
  2506. expect(
  2507. zcodeWorkspaceUpdateInteractionPreferencesParamsSchema.parse({
  2508. workspace,
  2509. preferences: {
  2510. askUserQuestionAutoResolutionEnabled: false,
  2511. },
  2512. }),
  2513. ).toEqual({
  2514. workspace,
  2515. preferences: {
  2516. askUserQuestionAutoResolutionEnabled: false,
  2517. },
  2518. });
  2519. expect(
  2520. zcodeWorkspaceUpdateInteractionPreferencesResultSchema.parse({
  2521. workspace,
  2522. askUserQuestionAutoResolutionEnabled: false,
  2523. snoozedInteractionCount: 2,
  2524. }),
  2525. ).toMatchObject({
  2526. askUserQuestionAutoResolutionEnabled: false,
  2527. snoozedInteractionCount: 2,
  2528. });
  2529. expect(() =>
  2530. zcodeWorkspaceUpdateInteractionPreferencesParamsSchema.parse({
  2531. workspace,
  2532. preferences: {
  2533. askUserQuestionAutoResolutionEnabled: false,
  2534. ignored: true,
  2535. },
  2536. }),
  2537. ).toThrow();
  2538. });
  2539. it("parses strict workspace ModelIO retention preference updates", () => {
  2540. expect(
  2541. zcodeWorkspaceUpdateModelIoPreferencesParamsSchema.parse({
  2542. workspace,
  2543. preferences: { fullRetentionEnabled: true },
  2544. }),
  2545. ).toEqual({
  2546. workspace,
  2547. preferences: { fullRetentionEnabled: true },
  2548. });
  2549. expect(
  2550. zcodeWorkspaceUpdateModelIoPreferencesResultSchema.parse({
  2551. workspace,
  2552. fullRetentionEnabled: true,
  2553. updatedSessionCount: 2,
  2554. }),
  2555. ).toMatchObject({
  2556. fullRetentionEnabled: true,
  2557. updatedSessionCount: 2,
  2558. });
  2559. expect(() =>
  2560. zcodeWorkspaceUpdateModelIoPreferencesParamsSchema.parse({
  2561. workspace,
  2562. preferences: { fullRetentionEnabled: true, ignored: true },
  2563. }),
  2564. ).toThrow();
  2565. });
  2566. it("validates ToolSearch startup preferences and defaults old Host responses off", () => {
  2567. expect(
  2568. zcodeSessionRuntimePreferencesResultSchema.parse({ nativeSearchEnhancementsEnabled: true })
  2569. .toolSearchMode,
  2570. ).toBe("off");
  2571. for (const mode of ["auto", "local", "off"]) {
  2572. expect(
  2573. zcodeSessionRuntimePreferencesResultSchema.parse({
  2574. nativeSearchEnhancementsEnabled: true,
  2575. toolSearchMode: mode,
  2576. }).toolSearchMode,
  2577. ).toBe(mode);
  2578. }
  2579. expect(
  2580. zcodeSessionRuntimePreferencesResultSchema.safeParse({
  2581. nativeSearchEnhancementsEnabled: true,
  2582. toolSearchMode: "native",
  2583. }).success,
  2584. ).toBe(false);
  2585. });
  2586. it("keeps runtime preference compatibility by defaulting missing fields", () => {
  2587. expect(DEFAULT_ZCODE_MODEL_CONTEXT_BUDGET_STRATEGY).toBe("preflight-v1");
  2588. expect(
  2589. zcodeSessionRuntimePreferencesResultSchema.parse({
  2590. nativeSearchEnhancementsEnabled: true,
  2591. }),
  2592. ).toMatchObject({
  2593. askUserQuestionAutoResolutionEnabled: true,
  2594. memoryEnabled: false,
  2595. modelContextBudgetStrategy: DEFAULT_ZCODE_MODEL_CONTEXT_BUDGET_STRATEGY,
  2596. });
  2597. expect(
  2598. zcodeSessionRuntimePreferencesResultSchema.parse({
  2599. nativeSearchEnhancementsEnabled: true,
  2600. askUserQuestionAutoResolutionEnabled: false,
  2601. modelContextBudgetStrategy: "preflight-v1",
  2602. }).askUserQuestionAutoResolutionEnabled,
  2603. ).toBe(false);
  2604. expect(() =>
  2605. zcodeSessionRuntimePreferencesResultSchema.parse({
  2606. nativeSearchEnhancementsEnabled: true,
  2607. modelContextBudgetStrategy: "unknown",
  2608. }),
  2609. ).toThrow();
  2610. });
  2611. it("accepts turn.completed cache stats and history round count from runtime events", () => {
  2612. const event = zcodeSessionEventSchema.parse({
  2613. type: "turn.completed",
  2614. eventId: "evt_1",
  2615. sessionId: "sess_1",
  2616. turnId: "turn_1",
  2617. seq: 2,
  2618. traceId: "trace_1",
  2619. timestamp: Date.now(),
  2620. deliveryKind: "desktop-continuous",
  2621. payload: {
  2622. response: "ok",
  2623. tokenCount: 2,
  2624. toolCallCount: 0,
  2625. historyRoundCount: 3,
  2626. duration: 123,
  2627. resultType: "success",
  2628. inputId: "run_1",
  2629. cacheStats: {
  2630. totalMessages: 4,
  2631. cachedMessages: 2,
  2632. lastCacheHit: true,
  2633. cacheReadTokens: 128,
  2634. },
  2635. },
  2636. });
  2637. expect(event.payload.cacheStats).toMatchObject({
  2638. cachedMessages: 2,
  2639. lastCacheHit: true,
  2640. });
  2641. expect(event.payload.historyRoundCount).toBe(3);
  2642. });
  2643. it("parses state.updated notifications as the core state sync primitive", () => {
  2644. const event = zcodeStateUpdatedNotificationSchema.parse({
  2645. type: "state.updated",
  2646. scope: "session",
  2647. workspace,
  2648. sessionId: "sess_1",
  2649. revision: 4,
  2650. reason: "model_changed",
  2651. patch: {
  2652. settings: {
  2653. model: {
  2654. current: model,
  2655. },
  2656. },
  2657. },
  2658. });
  2659. expect(event.revision).toBe(4);
  2660. });
  2661. it("workspace presentation rejects model facts", () => {
  2662. expect(() =>
  2663. zcodeWorkspacePresentationSchema.parse({
  2664. workspace,
  2665. mode: "build",
  2666. slashCommands: [],
  2667. model,
  2668. }),
  2669. ).toThrow();
  2670. });
  2671. });
  2672. describe("v4 workflowLaunch rows (direct-launch)", () => {
  2673. const meta = {
  2674. runId: "run-123",
  2675. toolCallId: "launch-abc",
  2676. name: "deep-research",
  2677. scope: "global" as const,
  2678. path: "/home/u/.zcode/workflows/deep-research.ts",
  2679. args: { topic: "adaptive concurrency", depth: 2 },
  2680. description: "Deep-dive a topic across the web and write a brief.",
  2681. };
  2682. it("parses a turnHeader row with origin workflowLaunch + meta", () => {
  2683. const row = conversationRowSchema.parse({
  2684. rowId: 1,
  2685. turnId: "turn-1",
  2686. createdAt: 10,
  2687. createdAtSeq: 1,
  2688. kind: "turnHeader",
  2689. origin: "workflowLaunch",
  2690. executionKind: "controlOnly",
  2691. state: "running",
  2692. startedAt: 10,
  2693. workflowLaunch: meta,
  2694. });
  2695. expect(row).toMatchObject({
  2696. kind: "turnHeader",
  2697. origin: "workflowLaunch",
  2698. workflowLaunch: meta,
  2699. });
  2700. });
  2701. it("parses a userInput row with origin workflowLaunch + meta (text still carried)", () => {
  2702. const row = conversationRowSchema.parse({
  2703. rowId: 2,
  2704. turnId: "turn-1",
  2705. createdAt: 10,
  2706. createdAtSeq: 2,
  2707. kind: "userInput",
  2708. text: 'Started the saved workflow "deep-research" (global) from the workflows hub as run run-123.',
  2709. origin: "workflowLaunch",
  2710. workflowLaunch: meta,
  2711. });
  2712. expect(row).toMatchObject({
  2713. kind: "userInput",
  2714. origin: "workflowLaunch",
  2715. workflowLaunch: meta,
  2716. });
  2717. });
  2718. it("rejects a description over the 500-char bound", () => {
  2719. expect(
  2720. workflowLaunchMetaSchema.safeParse({ ...meta, description: "x".repeat(501) }).success,
  2721. ).toBe(false);
  2722. expect(
  2723. workflowLaunchMetaSchema.safeParse({ ...meta, description: "x".repeat(500) }).success,
  2724. ).toBe(true);
  2725. });
  2726. it("rejects an args payload over the 4KB serialized bound", () => {
  2727. const bigArgs = { blob: "x".repeat(5000) };
  2728. expect(workflowLaunchMetaSchema.safeParse({ ...meta, args: bigArgs }).success).toBe(false);
  2729. });
  2730. it("rejects meta with missing runId or bad scope", () => {
  2731. expect(workflowLaunchMetaSchema.safeParse({ ...meta, runId: "" }).success).toBe(false);
  2732. expect(workflowLaunchMetaSchema.safeParse({ ...meta, scope: "team" }).success).toBe(false);
  2733. });
  2734. // 设置轮(docs/dynamic-workflow/launch.md「The settings turn」):同一份元数据,没有保存文件可指,
  2735. // 多一块 `amend` 说改了什么。
  2736. it("parses a settings-turn meta: no scope or path, an amend block with from/to ends", () => {
  2737. const settings = {
  2738. runId: "run-b",
  2739. toolCallId: "settings-abc",
  2740. name: "deep-research",
  2741. amend: {
  2742. predecessorRunId: "run-a",
  2743. subagentModel: { to: "zhipu/glm-5.3-flash" },
  2744. maxConcurrency: { from: 13, to: 4 },
  2745. ceiling: 13,
  2746. },
  2747. };
  2748. expect(workflowLaunchMetaSchema.parse(settings)).toEqual(settings);
  2749. // 无名 run 的设置轮不带名字(UI 换用兜底词,不拿 run id 当标题)。
  2750. const { name: _name, ...unnamed } = settings;
  2751. void _name;
  2752. expect(workflowLaunchMetaSchema.parse(unnamed)).toEqual(unnamed);
  2753. expect(
  2754. workflowLaunchMetaSchema.safeParse({
  2755. ...settings,
  2756. amend: { ...settings.amend, maxConcurrency: { to: 0 } },
  2757. }).success,
  2758. ).toBe(false);
  2759. expect(
  2760. workflowLaunchMetaSchema.safeParse({ ...settings, amend: { predecessorRunId: "" } }).success,
  2761. ).toBe(false);
  2762. });
  2763. // 就地生效的设置轮(docs/dynamic-workflow/concurrency.md):只改并发上限、run 又在飞时没有前驱,
  2764. // `predecessorRunId` 因此缺席——缺席本身就是「改的就是 runId 这一条」的信号(渲染端据它只出行)。
  2765. it("parses an in-place retune's settings-turn meta: no predecessorRunId at all", () => {
  2766. const retune = {
  2767. runId: "run-a",
  2768. toolCallId: "settings-xyz",
  2769. name: "deep-research",
  2770. amend: { maxConcurrency: { from: 13, to: 4 }, ceiling: 13 },
  2771. };
  2772. expect(workflowLaunchMetaSchema.parse(retune)).toEqual(retune);
  2773. // 在场时仍要是一个真 run id:可选不等于可空、也不等于可空串。
  2774. expect(
  2775. workflowLaunchMetaSchema.safeParse({
  2776. ...retune,
  2777. amend: { ...retune.amend, predecessorRunId: null },
  2778. }).success,
  2779. ).toBe(false);
  2780. });
  2781. });