paseo-plugin-zcode-provider 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +29 -0
  3. package/README.md +98 -2
  4. package/client/diagnostics.tsx +397 -0
  5. package/client/setup.tsx +347 -0
  6. package/icon.svg +1 -0
  7. package/index.client.tsx +22 -0
  8. package/index.server.ts +21 -0
  9. package/package.json +75 -4
  10. package/paseo-plugin.json +6 -0
  11. package/server/attachments.ts +150 -0
  12. package/server/build-info.ts +2 -0
  13. package/server/conversation.ts +319 -0
  14. package/server/diagnostics.ts +235 -0
  15. package/server/discovery/discover.ts +225 -0
  16. package/server/discovery/manifest.ts +36 -0
  17. package/server/discovery/types.ts +30 -0
  18. package/server/errors.ts +36 -0
  19. package/server/host/bridge.ts +463 -0
  20. package/server/host/schemas.ts +119 -0
  21. package/server/logger.ts +19 -0
  22. package/server/mapping.ts +270 -0
  23. package/server/models.ts +68 -0
  24. package/server/persistence.ts +146 -0
  25. package/server/presentation.ts +428 -0
  26. package/server/provider.ts +831 -0
  27. package/server/runtime/managed.ts +501 -0
  28. package/server/runtime/pins.ts +72 -0
  29. package/server/runtime-setup.ts +102 -0
  30. package/server/session-types.ts +49 -0
  31. package/server/session.ts +866 -0
  32. package/server/status.ts +89 -0
  33. package/server/timeline.ts +18 -0
  34. package/server/vendor/zcode/LICENSE +202 -0
  35. package/server/vendor/zcode/NOTICE.md +70 -0
  36. package/server/vendor/zcode/THIRD-PARTY-NOTICES.md +37 -0
  37. package/server/vendor/zcode/packages/model-option-map/src/compiler.ts +92 -0
  38. package/server/vendor/zcode/packages/model-option-map/src/evaluator.ts +214 -0
  39. package/server/vendor/zcode/packages/model-option-map/src/index.ts +5 -0
  40. package/server/vendor/zcode/packages/model-option-map/src/merge-patch.ts +97 -0
  41. package/server/vendor/zcode/packages/model-option-map/src/option-maps.ts +42 -0
  42. package/server/vendor/zcode/packages/model-option-map/src/parser.ts +240 -0
  43. package/server/vendor/zcode/packages/model-option-map/src/tokenizer.ts +141 -0
  44. package/server/vendor/zcode/packages/model-option-map/src/types.ts +36 -0
  45. package/server/vendor/zcode/packages/rpc/src/buffer.ts +88 -0
  46. package/server/vendor/zcode/packages/rpc/src/channelClient.ts +275 -0
  47. package/server/vendor/zcode/packages/rpc/src/channelServer.ts +283 -0
  48. package/server/vendor/zcode/packages/rpc/src/channels.shared.ts +66 -0
  49. package/server/vendor/zcode/packages/rpc/src/channels.ts +4 -0
  50. package/server/vendor/zcode/packages/rpc/src/delayedChannel.ts +17 -0
  51. package/server/vendor/zcode/packages/rpc/src/foundation.ts +260 -0
  52. package/server/vendor/zcode/packages/rpc/src/protocol.ts +397 -0
  53. package/server/vendor/zcode/packages/rpc/src/proxy-channel.ts +213 -0
  54. package/server/vendor/zcode/packages/rpc/src/serialization.ts +291 -0
  55. package/server/vendor/zcode/packages/shared/src/account-provider-state.ts +13 -0
  56. package/server/vendor/zcode/packages/shared/src/background-bash-output.ts +24 -0
  57. package/server/vendor/zcode/packages/shared/src/background-task-controls.ts +404 -0
  58. package/server/vendor/zcode/packages/shared/src/bash-output-display.ts +11 -0
  59. package/server/vendor/zcode/packages/shared/src/bots.ts +558 -0
  60. package/server/vendor/zcode/packages/shared/src/browser-use/backend.ts +80 -0
  61. package/server/vendor/zcode/packages/shared/src/browser-use/command-metadata.ts +170 -0
  62. package/server/vendor/zcode/packages/shared/src/browser-use/commands.ts +588 -0
  63. package/server/vendor/zcode/packages/shared/src/browser-use/result.ts +130 -0
  64. package/server/vendor/zcode/packages/shared/src/browser-use/snapshot.ts +77 -0
  65. package/server/vendor/zcode/packages/shared/src/command-types.ts +96 -0
  66. package/server/vendor/zcode/packages/shared/src/config-schema.ts +8 -0
  67. package/server/vendor/zcode/packages/shared/src/cuaAccessibilitySettings.ts +41 -0
  68. package/server/vendor/zcode/packages/shared/src/database-startup.ts +178 -0
  69. package/server/vendor/zcode/packages/shared/src/env.ts +63 -0
  70. package/server/vendor/zcode/packages/shared/src/execution-output-preview.ts +14 -0
  71. package/server/vendor/zcode/packages/shared/src/localTtft.ts +192 -0
  72. package/server/vendor/zcode/packages/shared/src/model-config.ts +123 -0
  73. package/server/vendor/zcode/packages/shared/src/model-execution.ts +23 -0
  74. package/server/vendor/zcode/packages/shared/src/model-provider-family.ts +171 -0
  75. package/server/vendor/zcode/packages/shared/src/model-provider-types.ts +81 -0
  76. package/server/vendor/zcode/packages/shared/src/model-selection.ts +60 -0
  77. package/server/vendor/zcode/packages/shared/src/oauth.ts +203 -0
  78. package/server/vendor/zcode/packages/shared/src/official-mcp-auth.ts +272 -0
  79. package/server/vendor/zcode/packages/shared/src/official-mcp-tool-error.ts +68 -0
  80. package/server/vendor/zcode/packages/shared/src/process-diagnostic.ts +42 -0
  81. package/server/vendor/zcode/packages/shared/src/protocol.ts +369 -0
  82. package/server/vendor/zcode/packages/shared/src/provider-family-connection-selection.ts +32 -0
  83. package/server/vendor/zcode/packages/shared/src/remoteAssetInstallMode.ts +11 -0
  84. package/server/vendor/zcode/packages/shared/src/remoteResourcePackages.ts +91 -0
  85. package/server/vendor/zcode/packages/shared/src/runtimeEnv.ts +315 -0
  86. package/server/vendor/zcode/packages/shared/src/settings-source.ts +10 -0
  87. package/server/vendor/zcode/packages/shared/src/usage-quota.ts +74 -0
  88. package/server/vendor/zcode/packages/shared/src/usage-stats.ts +462 -0
  89. package/server/vendor/zcode/packages/shared/src/validationAppSettings.ts +562 -0
  90. package/server/vendor/zcode/packages/shared/src/workspacePurpose.ts +2 -0
  91. package/server/vendor/zcode/packages/shared/src/wslUserValidation.ts +33 -0
  92. package/server/vendor/zcode/packages/shared/src/zcode-agent-policy.ts +25 -0
  93. package/server/vendor/zcode/packages/shared/src/zcode-media-policy.ts +10 -0
  94. package/server/vendor/zcode/packages/shared/src/zcode-protocol/index.ts +3720 -0
  95. package/server/vendor/zcode/packages/shared/src/zcode-protocol-legacy-types.ts +529 -0
  96. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/apply.ts +218 -0
  97. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/attachment-ref.ts +14 -0
  98. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/command.ts +482 -0
  99. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/core.ts +100 -0
  100. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/create-workflow-display.ts +156 -0
  101. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/cuaPermission.ts +41 -0
  102. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/delta.ts +147 -0
  103. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/input-intent.ts +69 -0
  104. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/rows.ts +432 -0
  105. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/session-config.ts +43 -0
  106. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/sessions-index-workflow-activity.ts +195 -0
  107. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/sessions-index.ts +85 -0
  108. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/shared-context-import.ts +38 -0
  109. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/shared-context-ref.ts +10 -0
  110. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/snapshot.ts +509 -0
  111. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/submission.ts +5 -0
  112. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/toolDisplay.ts +264 -0
  113. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/transport.ts +1152 -0
  114. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/wire-assembler.ts +574 -0
  115. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/wire-binary.ts +65 -0
  116. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/wire-codec.ts +240 -0
  117. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/wire-fault.ts +39 -0
  118. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/wire.ts +159 -0
  119. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workflow-artifacts.ts +291 -0
  120. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workflow-observation-display.ts +281 -0
  121. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workflow-row-meta.ts +163 -0
  122. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workflow-run-settings-command.ts +62 -0
  123. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workflow-runs-delta.ts +517 -0
  124. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workflow-runs.ts +512 -0
  125. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workspace-config.ts +81 -0
  126. package/server/vendor/zcode/packages/shared/src/zcode-protocol-v4/workspace-hook-review.ts +210 -0
  127. package/server/vendor/zcode/packages/shared/src/zcode-task-mode-schema.ts +6 -0
  128. package/server/vendor/zcode/packages/shared/src/zcode-task-types-core.ts +1187 -0
  129. package/server/vendor/zcode/packages/shared/src/zcodeEndpoint.ts +296 -0
  130. package/server/vendor/zcode/provenance.json +405 -0
  131. package/shared/diagnostics.ts +52 -0
  132. package/shared/runtime-setup.ts +75 -0
  133. package/vendor/acp-registry/LICENSE +176 -0
  134. package/vendor/paseo/LICENSE +211 -0
@@ -0,0 +1,3720 @@
1
+ import {
2
+ databaseStartupErrorCodeSchema,
3
+ databaseStartupErrorDetailsSchema,
4
+ databaseMigrationFactsSchema,
5
+ } from "../database-startup.js";
6
+ /* oxlint-disable eslint(max-lines) -- ZCode Protocol schema 需要单文件导出,方便 app 与 agent 共享同一份协议契约。 */
7
+ // ── 旧协议删除边界──────────────────────
8
+ // 剩余 ~257 个导出:旧 ZCode Protocol 方法契约、请求/响应/事件 schema、
9
+ // session/workspace state snapshot 投影等(承重类型已迁 zcode-protocol-legacy-types.ts)。
10
+ // 已连根删除的死词(词表+schema+两侧实现):session/steer、session/rewind、
11
+ // session/rewindCascade、session/previewFileRewind、session/applyFileRewind、
12
+ // prompt/enhance 全簇(含 promptEnhanceResult 通知)、plugins/marketplace/list;
13
+ // session/fork 客户端链已删(op+schema 留存 = v4 forkSessionAtMessage 钩子消费)。
14
+ // 消费者:services 旧栈(zcodeProtocolClient/zcodeAgent/zcodeAgentService/zcodeSession*)、
15
+ // CLI bootstrap 旧协议 server(zcode-protocol/server-operations、plugins、session-mapper 等)、
16
+ // UI 旧投影(zcodeSessionProjection 等读路径)。
17
+ // 上述旧协议 client/server 组删除时,本文件整体删除。
18
+ // 注:外部零消费 schema 多为存活 schema 联合的内部依赖,随宿主文件一起处理,勿单删。
19
+ import { bashOutputDisplaySchema } from "../bash-output-display.js";
20
+ // 后台详情共享精简的只读响应 schema,不携带命令或计时元数据。
21
+ export * from "../background-bash-output.js";
22
+ import { executionOutputPreviewSchema } from "../execution-output-preview.js";
23
+ import { z } from "zod";
24
+ export * from "../process-diagnostic.js";
25
+ import { errorAttributionSchema } from "../zcode-protocol-v4/snapshot.js";
26
+ import { modelSelectionSchema } from "../model-selection.js";
27
+ import { completeModelPropertiesDataSchema } from "../model-config.js";
28
+ import { accountProviderUnavailableReasonSchema } from "../account-provider-state.js";
29
+ import { modelExecutionSchema } from "../model-execution.js";
30
+ import { APP_USAGE_RANGES, appUsageSnapshotSchema } from "../usage-stats.js";
31
+ import { zcodeAutomationBotDeliveryTargetSchema } from "../bots.js";
32
+ // browser-use 命令/结果契约单一来源:agent 构造、协议校验和 main executor 共用同一 schema。
33
+ import { browserClientModeSchema, browserCommandSchema } from "../browser-use/commands.js";
34
+ import {
35
+ browserBackendListResultSchema,
36
+ browserSessionContextKindSchema,
37
+ } from "../browser-use/backend.js";
38
+ import { browserCommandResultSchema } from "../browser-use/result.js";
39
+ import { integratedTerminalShellSelectionSchema } from "../validationAppSettings.js";
40
+ import { zcodeTaskModeSchema } from "../zcode-task-mode-schema.js";
41
+ import { OFFICIAL_MCP_AUTH_PORT_FAILURE_REASONS } from "../official-mcp-auth.js";
42
+ import {
43
+ zcodeDeliveryKindSchema,
44
+ zcodeMessageVisibilitySchema,
45
+ zcodeSyntheticUserMessageSourceSchema as legacyZcodeSyntheticUserMessageSourceSchema,
46
+ zcodeWorkspaceRefSchema,
47
+ zcodePermissionDecisionSchema,
48
+ zcodePermissionResponseSchema,
49
+ zcodePermissionUpdateSchema,
50
+ zcodeSessionModeSchema,
51
+ zcodeSessionStatusSchema,
52
+ zcodeSessionKindSchema,
53
+ zcodeSessionGoalSchema,
54
+ zcodeSessionGoalVerificationSchema,
55
+ zcodeSessionGoalVerificationTimelineSchema,
56
+ zcodeInteractionRequestOriginSchema,
57
+ zcodeToolStateSchema,
58
+ zcodeSessionApiRetryStatusSchema,
59
+ zcodeSessionContextUsageSchema,
60
+ zcodeSessionInfoSchema,
61
+ zcodeSessionRuntimeStateSchema,
62
+ zcodeMessageWithPartsSchema,
63
+ zcodeMessagePartSchema,
64
+ } from "../zcode-protocol-legacy-types.js";
65
+
66
+ export {
67
+ hookExecutionProjectionSchema,
68
+ hookInvocationRowSchema,
69
+ type HookExecutionProjection,
70
+ type HookInvocationRow,
71
+ } from "../zcode-protocol-v4/rows.js";
72
+
73
+ export const ZCODE_PROTOCOL_NAME = "ZCode Protocol" as const;
74
+ export const ZCODE_PROTOCOL_VERSION = 1 as const;
75
+ // V4 wire 与 legacy 主协议并存;禁止为了 V4 physical framing 改写 legacy 版本。
76
+ export const ZCODE_PROTOCOL_V4_WIRE_VERSION = 3 as const;
77
+ export const zcodeRuntimeCapabilitiesSchema = z.object({
78
+ independentPlanState: z.boolean().optional(),
79
+ });
80
+ export const zcodeProtocolErrorCodes = {
81
+ sessionUnavailable: -32004,
82
+ } as const;
83
+
84
+ const nonEmptyString = z.string().trim().min(1);
85
+ const jsonObjectSchema = z.record(z.string(), z.unknown());
86
+ const timestampMsSchema = z.number().int().nonnegative();
87
+ const protocolInstantSchema = z.union([timestampMsSchema, nonEmptyString, z.date()]);
88
+
89
+ // Tool result display 不受模型文本 budget 约束;Node REPL 图片必须在 Agent/App 协议边界
90
+ // 做严格限长,避免截图把 continuous 或 replayable 消息扩成无界载荷。
91
+ export const zcodeNodeReplImageToolResultDisplaySchema = z
92
+ .object({
93
+ kind: z.literal("node_repl_images"),
94
+ images: z
95
+ .array(
96
+ z
97
+ .object({
98
+ base64: z
99
+ .string()
100
+ .min(1)
101
+ .max(200 * 1024),
102
+ mimeType: z.string().regex(/^image\/[a-z0-9.+-]+$/iu),
103
+ })
104
+ .strict(),
105
+ )
106
+ .min(1)
107
+ .max(2),
108
+ truncated: z.boolean().optional(),
109
+ source: z.literal("browser_turn_end").optional(),
110
+ })
111
+ .strict();
112
+
113
+ // 同理:CreateWorkflow 的类型检查诊断也是 display 通道,必须在协议边界限长,
114
+ // 避免大量诊断把 continuous/replayable 消息扩成无界载荷。
115
+ // causalityGraph 在工具输出边界已限长,这里镜像同一组上界(与 v4 rows 保持一致)。
116
+ // 图的词汇表刻意很小:step 卡片 + actor 车道 + 一种箭头(runs after,`back` 只标回边)+
117
+ // 返回物标记。分析器的 kind / certainty / exact / region 不进载荷。
118
+ // 名字只在运行时成形(`` agent(`研究员${i + 1}`) ``)时静态能拿到的形状:第一个洞之前的
119
+ // 字面量(head)与最后一个洞之后的字面量(tail)。至少一个在场,两者都已 trim 且含实义字符。
120
+ // Bug 修复:这两个字段随 0a8b059f40 落进 contracts 与 v4 镜像,v3 这份漏改——.strict()
121
+ // 之下带插值名的工作流会让整个 display 验证失败、图整块消失,所以这里必须与 v4 逐字段对齐。
122
+ const zcodeWorkflowNamePatternSchema = z
123
+ .object({
124
+ head: z.string().min(1).max(128).optional(),
125
+ tail: z.string().min(1).max(128).optional(),
126
+ })
127
+ .strict();
128
+
129
+ // 一条边 = runs after;step 边与阶段边同形,`back` 只标循环回边。
130
+ const zcodeWorkflowEdgeSchema = z
131
+ .object({
132
+ from: z.string().min(1).max(64),
133
+ to: z.string().min(1).max(64),
134
+ back: z.literal(true).optional(),
135
+ })
136
+ .strict();
137
+
138
+ const zcodeCreateWorkflowCausalityGraphDisplaySchema = z
139
+ .object({
140
+ steps: z
141
+ .array(
142
+ z
143
+ .object({
144
+ id: z.string().min(1).max(64),
145
+ kind: z.enum(["ask", "world-read"]),
146
+ label: z.string().min(1).max(128),
147
+ // 内联 `agent()` receiver 让 label 落到兜底串时,那个名字的静态形状。
148
+ labelPattern: zcodeWorkflowNamePatternSchema.optional(),
149
+ line: z.number().int().positive().optional(),
150
+ column: z.number().int().positive().optional(),
151
+ lane: z.string().min(1).max(64),
152
+ lanes: z.array(z.string().min(1).max(64)).max(32).optional(),
153
+ // 展开自的站点 id,只出现在 may-set 车道展开的拷贝上(实时叠加的关联键);
154
+ // 加字段是 additive 的,不带它的旧载荷照常通过 .strict()。
155
+ source: z.string().min(1).max(64).optional(),
156
+ // 作者用 `phase("…")` 标记划入的阶段。
157
+ // 与图的 phases / phaseEdges / exits 同进同退:全在场或全缺席。
158
+ phase: z.string().min(1).max(64).optional(),
159
+ repeat: z.enum(["stack", "serial"]).optional(),
160
+ })
161
+ .strict(),
162
+ )
163
+ .max(64),
164
+ lanes: z
165
+ .array(
166
+ z
167
+ .object({
168
+ id: z.string().min(1).max(64),
169
+ name: z.string().min(1).max(128).optional(),
170
+ // `name` 缺席而 agent() 首参是带洞的模板串时的静态形状;与 name 互斥。
171
+ namePattern: zcodeWorkflowNamePatternSchema.optional(),
172
+ line: z.number().int().positive().optional(),
173
+ column: z.number().int().positive().optional(),
174
+ })
175
+ .strict(),
176
+ )
177
+ .max(32),
178
+ // 参与者与交接;镜像 v4。
179
+ participants: z
180
+ .array(
181
+ z
182
+ .object({
183
+ id: z.string().min(1).max(64),
184
+ phase: z.string().min(1).max(64),
185
+ lane: z.string().min(1).max(64),
186
+ steps: z.array(z.string().min(1).max(64)).min(1).max(64),
187
+ member: z
188
+ .object({ index: z.number().int().nonnegative(), of: z.number().int().positive() })
189
+ .strict()
190
+ .optional(),
191
+ many: z.literal(true).optional(),
192
+ })
193
+ .strict(),
194
+ )
195
+ .max(64),
196
+ handoffs: z
197
+ .array(
198
+ zcodeWorkflowEdgeSchema
199
+ .extend({ types: z.array(z.string().min(1).max(128)).min(1).max(8).optional() })
200
+ .strict(),
201
+ )
202
+ .max(256),
203
+ // 阶段词汇表:作者施加的分组结构,主画面以它为节点。与 phaseEdges / exits / Step.phase
204
+ // 全有或全无——零标记脚本全缺席,UI 据此退回 step/车道视图。零成员阶段也在表里。
205
+ // `unphased` 无 name,显示名由 UI 本地化。
206
+ phases: z
207
+ .array(
208
+ z
209
+ .object({
210
+ id: z.string().min(1).max(64),
211
+ name: z.string().min(1).max(128).optional(),
212
+ line: z.number().int().positive().optional(),
213
+ column: z.number().int().positive().optional(),
214
+ // 进入本阶段时还在跑的其他阶段(它们的 strand 尚未 join),阶段表序,不含自己,
215
+ // 为空时缺席。是节点事实而不是边——控制没有从那里转移过来,所以不进 phaseEdges。
216
+ // 时间轴据此把相邻阶段折成一条分叉的「带」,侧栏迷你轨道画成双线段。
217
+ alongside: z.array(z.string().min(1).max(64)).min(1).max(32).optional(),
218
+ })
219
+ .strict(),
220
+ )
221
+ .max(32)
222
+ .optional(),
223
+ phaseEdges: z.array(zcodeWorkflowEdgeSchema).max(128).optional(),
224
+ // 控制流可在其后正常完成的阶段(阶段视图的「阶段 → 返回物」箭头);组内可为空数组。
225
+ exits: z.array(z.string().min(1).max(64)).max(32).optional(),
226
+ sink: z.array(z.string().min(1).max(64)).max(64).optional(),
227
+ truncated: z.boolean().optional(),
228
+ })
229
+ .strict();
230
+
231
+ export const zcodeCreateWorkflowToolResultDisplaySchema = z
232
+ .object({
233
+ kind: z.literal("create_workflow"),
234
+ ok: z.boolean(),
235
+ errorCount: z.number().int().nonnegative(),
236
+ diagnostics: z
237
+ .array(
238
+ z
239
+ .object({
240
+ line: z.number().int().nonnegative(),
241
+ column: z.number().int().nonnegative(),
242
+ code: z.number().int().nonnegative(),
243
+ message: z.string().min(1).max(2_048),
244
+ })
245
+ .strict(),
246
+ )
247
+ .max(100),
248
+ causalityGraph: zcodeCreateWorkflowCausalityGraphDisplaySchema.optional(),
249
+ truncated: z.boolean().optional(),
250
+ })
251
+ .strict();
252
+
253
+ const zcodeToolResultObjectSchema = jsonObjectSchema.superRefine((result, context) => {
254
+ const display = result.display;
255
+ if (typeof display !== "object" || display === null || Array.isArray(display)) {
256
+ return;
257
+ }
258
+ const kind = (display as Record<string, unknown>).kind;
259
+ const schemaByKind: Record<string, z.ZodTypeAny> = {
260
+ node_repl_images: zcodeNodeReplImageToolResultDisplaySchema,
261
+ create_workflow: zcodeCreateWorkflowToolResultDisplaySchema,
262
+ bash_output: bashOutputDisplaySchema,
263
+ };
264
+ const schema = typeof kind === "string" ? schemaByKind[kind] : undefined;
265
+ if (!schema) return;
266
+ const parsed = schema.safeParse(display);
267
+ if (parsed.success) return;
268
+ for (const issue of parsed.error.issues) {
269
+ context.addIssue({ ...issue, path: ["display", ...issue.path] });
270
+ }
271
+ });
272
+
273
+ export const zcodeProtocolRequestIdSchema = z.union([z.string(), z.number().int()]);
274
+ export type ZCodeProtocolRequestId = z.infer<typeof zcodeProtocolRequestIdSchema>;
275
+
276
+ export const zcodeProtocolTraceSchema = z
277
+ .object({
278
+ traceparent: nonEmptyString.optional(),
279
+ traceId: nonEmptyString.optional(),
280
+ parentId: nonEmptyString.optional(),
281
+ spanId: nonEmptyString.optional(),
282
+ })
283
+ .strict();
284
+ export type ZCodeProtocolTrace = z.infer<typeof zcodeProtocolTraceSchema>;
285
+
286
+ export const zcodeProtocolRequestSchema = z
287
+ .object({
288
+ id: zcodeProtocolRequestIdSchema,
289
+ method: nonEmptyString,
290
+ params: z.unknown().optional(),
291
+ trace: zcodeProtocolTraceSchema.optional(),
292
+ })
293
+ .strict();
294
+ export type ZCodeProtocolRequest = z.infer<typeof zcodeProtocolRequestSchema>;
295
+
296
+ export const zcodeProtocolNotificationSchema = z
297
+ .object({
298
+ method: nonEmptyString,
299
+ params: z.unknown().optional(),
300
+ trace: zcodeProtocolTraceSchema.optional(),
301
+ })
302
+ .strict();
303
+ export type ZCodeProtocolNotification = z.infer<typeof zcodeProtocolNotificationSchema>;
304
+
305
+ export const zcodeProtocolResponseSchema = z
306
+ .object({
307
+ id: zcodeProtocolRequestIdSchema,
308
+ result: z.unknown(),
309
+ })
310
+ .strict();
311
+ export type ZCodeProtocolResponse = z.infer<typeof zcodeProtocolResponseSchema>;
312
+
313
+ export const zcodeProtocolErrorSchema = z
314
+ .object({
315
+ id: zcodeProtocolRequestIdSchema,
316
+ error: z
317
+ .object({
318
+ code: z.number().int(),
319
+ message: nonEmptyString,
320
+ data: z.unknown().optional(),
321
+ })
322
+ .strict(),
323
+ })
324
+ .strict();
325
+ export type ZCodeProtocolError = z.infer<typeof zcodeProtocolErrorSchema>;
326
+
327
+ export const zcodeProtocolMessageSchema = z.union([
328
+ zcodeProtocolRequestSchema,
329
+ zcodeProtocolNotificationSchema,
330
+ zcodeProtocolResponseSchema,
331
+ zcodeProtocolErrorSchema,
332
+ ]);
333
+ export type ZCodeProtocolMessage = z.infer<typeof zcodeProtocolMessageSchema>;
334
+
335
+ export const zcodeProtocolNotifications = {
336
+ storageStartup: "startup/storageState",
337
+ providerRuntimeHeadersCancelled: "interaction/providerRuntimeHeadersCancelled",
338
+ mcpTelemetry: "process/mcpTelemetry",
339
+ mcpResourceSamples: "process/mcpResourceSamples",
340
+ toolExecResource: "process/toolExecResource",
341
+ pluginOperationProgress: "plugins/operationProgress",
342
+ processResourceSample: "process/resourceSample",
343
+ } as const;
344
+
345
+ /** 启动控制面独立于 task stream;数据库身份不可携带路径/凭据。 */
346
+ export const zcodeStorageStartupStateSchema = z
347
+ .object({
348
+ schemaVersion: z.literal(1),
349
+ attemptId: z.string().min(1).max(128),
350
+ sequence: z.number().int().positive(),
351
+ databaseId: z.string().min(1).max(128),
352
+ databaseKind: z.enum(["session", "tasks-index"]),
353
+ phase: z.enum(["checking", "waiting_for_lock", "migrating", "committing", "ready", "failed"]),
354
+ // 包含锁内、版本 SQL 之前的可选 lastAppliedMigrationId;旧通知仍可解析。
355
+ migration: databaseMigrationFactsSchema.optional(),
356
+ elapsedMs: z.number().nonnegative().finite(),
357
+ completed: z.number().int().nonnegative().optional(),
358
+ total: z.number().int().nonnegative().optional(),
359
+ errorCode: databaseStartupErrorCodeSchema.optional(),
360
+ ...databaseStartupErrorDetailsSchema.shape,
361
+ })
362
+ .strict()
363
+ .superRefine((state, context) => {
364
+ if (state.phase === "failed" && !state.errorCode)
365
+ context.addIssue({ code: "custom", message: "failed requires errorCode" });
366
+ });
367
+ export type ZCodeStorageStartupState = z.infer<typeof zcodeStorageStartupStateSchema>;
368
+
369
+ const zcodeMcpTelemetryPlatformSchema = z.enum([
370
+ "aix",
371
+ "android",
372
+ "darwin",
373
+ "freebsd",
374
+ "haiku",
375
+ "linux",
376
+ "netbsd",
377
+ "openbsd",
378
+ "sunos",
379
+ "win32",
380
+ "cygwin",
381
+ ]);
382
+ const zcodeMcpTelemetryArchSchema = z.enum([
383
+ "arm",
384
+ "arm64",
385
+ "ia32",
386
+ "loong64",
387
+ "mips",
388
+ "mipsel",
389
+ "ppc",
390
+ "ppc64",
391
+ "riscv64",
392
+ "s390",
393
+ "s390x",
394
+ "x64",
395
+ ]);
396
+ const zcodeMcpTelemetryBaseSchema = z
397
+ .object({
398
+ arch: zcodeMcpTelemetryArchSchema,
399
+ occurredAt: z.number().int().nonnegative(),
400
+ platform: zcodeMcpTelemetryPlatformSchema,
401
+ })
402
+ .strict();
403
+ const zcodeMcpProcessTelemetryBaseShape = {
404
+ mcpId: z
405
+ .string()
406
+ .regex(
407
+ /^(?:builtin:(?:[A-Za-z0-9._~-]|%[0-9A-F]{2})+(?::(?:[A-Za-z0-9._~-]|%[0-9A-F]{2})+)*|(?:plugin|custom):[a-f0-9]{12})$/,
408
+ ),
409
+ mcpInstanceId: nonEmptyString,
410
+ mcpIsolation: z.enum(["session", "workspace"]),
411
+ mcpSource: z.enum(["builtin", "plugin", "custom"]),
412
+ } as const;
413
+
414
+ export const zcodeMcpTelemetryEventSchema = z.discriminatedUnion("kind", [
415
+ zcodeMcpTelemetryBaseSchema
416
+ .extend({
417
+ kind: z.literal("process_start"),
418
+ ...zcodeMcpProcessTelemetryBaseShape,
419
+ })
420
+ .strict(),
421
+ zcodeMcpTelemetryBaseSchema
422
+ .extend({
423
+ kind: z.literal("process_crash"),
424
+ ...zcodeMcpProcessTelemetryBaseShape,
425
+ affectedSessionCount: z.number().int().nonnegative().max(10_000),
426
+ exitCode: z.number().int().nullable(),
427
+ signal: nonEmptyString.nullable(),
428
+ uptimeMs: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
429
+ })
430
+ .strict(),
431
+ zcodeMcpTelemetryBaseSchema
432
+ .extend({
433
+ kind: z.literal("session_startup"),
434
+ configuredCount: z.number().int().nonnegative().max(10_000),
435
+ connectedCount: z.number().int().nonnegative().max(10_000),
436
+ failedCount: z.number().int().nonnegative().max(10_000),
437
+ processCount: z.number().int().nonnegative().max(10_000),
438
+ sessionId: nonEmptyString,
439
+ })
440
+ .strict(),
441
+ zcodeMcpTelemetryBaseSchema
442
+ .extend({
443
+ kind: z.literal("memory"),
444
+ ...zcodeMcpProcessTelemetryBaseShape,
445
+ memoryKb: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
446
+ memoryScope: z.enum(["process_tree", "direct_process"]),
447
+ orphanSuspected: z.boolean(),
448
+ ownerSessionCount: z.number().int().nonnegative().max(10_000),
449
+ unownedSeconds: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
450
+ })
451
+ .strict(),
452
+ ]);
453
+ export type ZCodeMcpTelemetryEvent = z.infer<typeof zcodeMcpTelemetryEventSchema>;
454
+
455
+ /** MCP 每五分钟只探测一次,周期由生产者与设备总量过期判据共用。 */
456
+ export const ZCODE_MCP_RESOURCE_SAMPLE_INTERVAL_MS = 5 * 60_000;
457
+
458
+ export const zcodeMcpResourceSampleSchema = z
459
+ .object({
460
+ mcpId: zcodeMcpProcessTelemetryBaseShape.mcpId,
461
+ instanceToken: z.string().regex(/^[A-Za-z0-9_-]{8,64}$/),
462
+ sampledAt: z.number().int().nonnegative(),
463
+ intervalMs: z.number().finite().positive(),
464
+ processCount: z.number().int().positive().max(100_000),
465
+ rssKbTotal: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
466
+ rssKbMaxProcess: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
467
+ cpuTimeMsDelta: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
468
+ uptimeMinutes: z.number().int().nonnegative(),
469
+ platform: zcodeMcpTelemetryPlatformSchema,
470
+ arch: zcodeMcpTelemetryArchSchema,
471
+ logicalCpuCount: z.number().int().positive().max(4_096),
472
+ totalMemoryGb: z.number().int().nonnegative().max(1_048_576),
473
+ })
474
+ .strict();
475
+ export type ZCodeMcpResourceSample = z.infer<typeof zcodeMcpResourceSampleSchema>;
476
+ // 通知输入有界;main 另按每个上报窗口的 32 个 MCP 分组执行事件额度。
477
+ export const zcodeMcpResourceSamplesSchema = z.array(zcodeMcpResourceSampleSchema).max(1_024);
478
+
479
+ export const BASH_RESOURCE_SAMPLE_INTERVAL_MS = 15_000;
480
+ export const BASH_RESOURCE_MAX_SAMPLES = 20;
481
+
482
+ /** Bash 子进程的有界完成事实;禁止命令、路径与会话标识进入遥测旁路。 */
483
+ export const zcodeToolExecResourceSchema = z
484
+ .object({
485
+ // 同一完成事实可能经多个 Host 转发;随机标识仅供 main 去重,旧 CLI 缺字段仍兼容。
486
+ completionToken: z.string().uuid().optional(),
487
+ platform: zcodeMcpTelemetryPlatformSchema,
488
+ toolName: z.literal("bash"),
489
+ durationMs: z.number().finite().min(BASH_RESOURCE_SAMPLE_INTERVAL_MS),
490
+ exitKind: z.enum(["completed", "timeout", "killed", "error"]),
491
+ treeRssKbPeak: z.number().finite().nonnegative().optional(),
492
+ treeCpuTimeMs: z.number().finite().nonnegative().optional(),
493
+ sampleCount: z.number().int().nonnegative().max(BASH_RESOURCE_MAX_SAMPLES),
494
+ cliRssKb: z.number().finite().nonnegative(),
495
+ systemFreeMemoryKb: z.number().finite().nonnegative(),
496
+ })
497
+ .strict();
498
+ export type ZCodeToolExecResource = z.infer<typeof zcodeToolExecResourceSchema>;
499
+
500
+ export const zcodeProcessResourceSampleSchema = z
501
+ .object({
502
+ platform: z.enum([
503
+ "aix",
504
+ "android",
505
+ "darwin",
506
+ "freebsd",
507
+ "haiku",
508
+ "linux",
509
+ "netbsd",
510
+ "openbsd",
511
+ "sunos",
512
+ "win32",
513
+ "cygwin",
514
+ ]),
515
+ arch: z.enum([
516
+ "arm",
517
+ "arm64",
518
+ "ia32",
519
+ "loong64",
520
+ "mips",
521
+ "mipsel",
522
+ "ppc",
523
+ "ppc64",
524
+ "riscv64",
525
+ "s390",
526
+ "s390x",
527
+ "x64",
528
+ ]),
529
+ logicalCpuCount: z.number().int().positive().max(4_096),
530
+ intervalMs: z
531
+ .number()
532
+ .int()
533
+ .positive()
534
+ .max(7 * 24 * 60 * 60 * 1_000),
535
+ cpuCores: z.number().finite().nonnegative().max(4_096),
536
+ cpuPercent: z.number().finite().nonnegative().max(100_000),
537
+ rssKb: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
538
+ /**
539
+ * 以下四项为遥测新增字段,全部可选:旧 CLI 发来的样本仍能通过校验,因此
540
+ * **不递增协议握手版本号**(握手版本是兼容性开关,不是字段版本)。
541
+ */
542
+ heapUsedKb: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
543
+ uptimeMinutes: z
544
+ .number()
545
+ .int()
546
+ .nonnegative()
547
+ .max(10 * 365 * 24 * 60)
548
+ .optional(),
549
+ totalMemoryGb: z.number().int().nonnegative().max(1_048_576).optional(),
550
+ /**
551
+ * CLI 进程启动时随机生成的实例标识,仅供 app 侧 main 统计「同时存活几个 CLI 进程」
552
+ * 与「最大单进程 RSS」。不进 ARMS 属性、不含 pid。收紧字符集是隐私红线的机械保障:
553
+ * 路径、workspace 标识这类内容不可能通过校验。
554
+ */
555
+ instanceToken: z
556
+ .string()
557
+ .regex(/^[A-Za-z0-9_-]{8,64}$/)
558
+ .optional(),
559
+ })
560
+ .strict();
561
+ export type ZCodeProcessResourceSample = z.infer<typeof zcodeProcessResourceSampleSchema>;
562
+
563
+ export const zcodeProcessChildProcessesParamsSchema = z.object({}).strict();
564
+ export const zcodeProcessChildProcessSchema = z
565
+ .object({
566
+ pid: z.number().int().positive(),
567
+ serverName: nonEmptyString,
568
+ mcpSource: z.enum(["builtin", "plugin", "custom"]),
569
+ /** 官方/第三方插件的插件名(`plugin:<name>:<key>` 的 name,或官方 host MCP 对应插件);custom 无 */
570
+ pluginName: nonEmptyString.optional(),
571
+ })
572
+ .strict();
573
+ export const zcodeProcessChildProcessesResultSchema = z
574
+ .object({
575
+ processes: z.array(zcodeProcessChildProcessSchema).max(10_000),
576
+ })
577
+ .strict();
578
+ export type ZCodeProcessChildProcess = z.infer<typeof zcodeProcessChildProcessSchema>;
579
+ export type ZCodeProcessChildProcessesResult = z.infer<
580
+ typeof zcodeProcessChildProcessesResultSchema
581
+ >;
582
+
583
+ export type ZCodeDeliveryKind = z.infer<typeof zcodeDeliveryKindSchema>;
584
+ // TurnStarted 与持久 message 必须共用同一来源词表;否则 live event 能通过而 cold
585
+ // message 在 app/agent 边界被拒绝,造成 continuous/replayable 语义分叉。
586
+ const zcodeTurnInputSourceSchema = legacyZcodeSyntheticUserMessageSourceSchema;
587
+ export const zcodeSessionPersistenceSchema = z.enum(["immediate", "deferred"]);
588
+ export type ZCodeSessionPersistence = z.infer<typeof zcodeSessionPersistenceSchema>;
589
+ export type ZCodeWorkspaceRef = z.infer<typeof zcodeWorkspaceRefSchema>;
590
+ export const zcodePermissionOptionSchema = z
591
+ .object({
592
+ optionId: nonEmptyString,
593
+ kind: nonEmptyString,
594
+ name: nonEmptyString,
595
+ description: z.string().optional(),
596
+ response: zcodePermissionResponseSchema,
597
+ })
598
+ .strict();
599
+
600
+ const zcodeProtocolMcpEntrySchema = z
601
+ .object({
602
+ name: nonEmptyString,
603
+ value: z.string(),
604
+ })
605
+ .strict();
606
+
607
+ const zcodeProtocolMcpOAuthSchema = z.union([
608
+ z
609
+ .object({
610
+ type: z.literal("client_credentials"),
611
+ clientId: nonEmptyString,
612
+ clientSecret: nonEmptyString,
613
+ clientName: nonEmptyString.optional(),
614
+ scope: z.string().optional(),
615
+ })
616
+ .strict(),
617
+ z
618
+ .object({
619
+ type: z.literal("authorization_code"),
620
+ clientId: nonEmptyString.optional(),
621
+ clientSecret: nonEmptyString.optional(),
622
+ clientName: nonEmptyString.optional(),
623
+ redirectPath: nonEmptyString.optional(),
624
+ scope: z.string().optional(),
625
+ })
626
+ .strict(),
627
+ ]);
628
+
629
+ export const zcodeProtocolMcpServerSchema = z.union([
630
+ z
631
+ .object({
632
+ name: nonEmptyString,
633
+ command: nonEmptyString,
634
+ args: z.array(z.string()),
635
+ env: z.array(zcodeProtocolMcpEntrySchema),
636
+ isolation: z.enum(["session", "workspace"]).optional(),
637
+ protocolVersion: z.enum(["legacy", "auto", "2026-07-28"]).optional(),
638
+ timeoutMs: z.number().int().positive().optional(),
639
+ })
640
+ .strict(),
641
+ z
642
+ .object({
643
+ name: nonEmptyString,
644
+ type: z.enum(["http", "sse"]),
645
+ url: nonEmptyString,
646
+ headers: z.array(zcodeProtocolMcpEntrySchema),
647
+ oauth: zcodeProtocolMcpOAuthSchema.optional(),
648
+ isolation: z.enum(["session", "workspace"]).optional(),
649
+ protocolVersion: z.enum(["legacy", "auto", "2026-07-28"]).optional(),
650
+ timeoutMs: z.number().int().positive().optional(),
651
+ })
652
+ .strict(),
653
+ ]);
654
+ export type ZCodeProtocolMcpServer = z.infer<typeof zcodeProtocolMcpServerSchema>;
655
+
656
+ export const zcodeMcpServerStatusKindSchema = z.enum([
657
+ "connecting",
658
+ "connected",
659
+ "disabled",
660
+ "disconnected",
661
+ "failed",
662
+ "untrusted",
663
+ ]);
664
+ export const MCP_SERVER_FAILURE_KINDS = [
665
+ "config_invalid",
666
+ "runtime_unavailable",
667
+ "process_start_failed",
668
+ "network_unreachable",
669
+ "connection_timeout",
670
+ "protocol_negotiation_failed",
671
+ "tool_list_failed",
672
+ "unexpected_disconnect",
673
+ "oauth_authorization_failed",
674
+ "official_origin_untrusted",
675
+ "not_authenticated",
676
+ "coding_plan_required",
677
+ "server_not_found",
678
+ "server_unavailable",
679
+ "rate_limited",
680
+ "server_internal_error",
681
+ "protocol_error",
682
+ "status_unavailable",
683
+ "connection_failed",
684
+ ] as const;
685
+ export const mcpServerFailureKindSchema = z.enum(MCP_SERVER_FAILURE_KINDS);
686
+ export type McpServerFailureKind = z.infer<typeof mcpServerFailureKindSchema>;
687
+ export const zcodeMcpServerStatusSnapshotSchema = z
688
+ .object({
689
+ status: zcodeMcpServerStatusKindSchema,
690
+ transport: z.enum(["stdio", "http", "sse"]),
691
+ toolCount: z.number().int().nonnegative(),
692
+ updatedAt: nonEmptyString,
693
+ error: z.string().optional(),
694
+ failureKind: mcpServerFailureKindSchema.optional(),
695
+ serverRequestId: nonEmptyString.optional(),
696
+ protocolEra: z.enum(["legacy", "modern"]).optional(),
697
+ authorization: z
698
+ .object({
699
+ type: z.literal("oauth_authorization_code"),
700
+ authorizationUrl: nonEmptyString,
701
+ startedAt: nonEmptyString,
702
+ })
703
+ .strict()
704
+ .optional(),
705
+ })
706
+ .strict();
707
+ export type ZCodeMcpServerStatusSnapshot = z.infer<typeof zcodeMcpServerStatusSnapshotSchema>;
708
+
709
+ export const zcodeMcpListModeSchema = z.enum(["connect", "status"]);
710
+ export type ZCodeMcpListMode = z.infer<typeof zcodeMcpListModeSchema>;
711
+
712
+ export const zcodeMcpListParamsSchema = z
713
+ .object({
714
+ workspace: zcodeWorkspaceRefSchema,
715
+ mcpServers: z.array(zcodeProtocolMcpServerSchema).optional(),
716
+ mode: zcodeMcpListModeSchema.default("connect"),
717
+ })
718
+ .strict();
719
+ export const zcodeMcpListResultSchema = z
720
+ .object({
721
+ statuses: z.record(z.string(), zcodeMcpServerStatusSnapshotSchema),
722
+ })
723
+ .strict();
724
+ export type ZCodeMcpListResult = z.infer<typeof zcodeMcpListResultSchema>;
725
+
726
+ export const zcodeSessionImportMessageSchema = z
727
+ .object({
728
+ role: z.enum(["user", "assistant"]),
729
+ content: z.string(),
730
+ timestamp: timestampMsSchema.optional(),
731
+ })
732
+ .strict();
733
+ export type ZCodeSessionImportMessage = z.infer<typeof zcodeSessionImportMessageSchema>;
734
+
735
+ export const zcodeSessionImportHistorySchema = z.discriminatedUnion("source", [
736
+ z
737
+ .object({
738
+ source: z.literal("claudeCode"),
739
+ title: z.string().optional(),
740
+ createdAt: timestampMsSchema.optional(),
741
+ updatedAt: timestampMsSchema.optional(),
742
+ messages: z.array(zcodeSessionImportMessageSchema).min(1),
743
+ })
744
+ .strict(),
745
+ z
746
+ .object({
747
+ source: z.literal("sharedContext"),
748
+ title: z.string().trim().min(1),
749
+ createdAt: timestampMsSchema.optional(),
750
+ markdown: z.string().min(1),
751
+ provenance: z
752
+ .object({
753
+ shareId: z.string().trim().min(1),
754
+ contextId: z.string().trim().min(1).optional(),
755
+ shareUrl: z.string().url().optional(),
756
+ status: z.enum(["pending", "reserved", "attached", "discarded"]).optional(),
757
+ projectionSha256: z.string().regex(/^[0-9a-f]{64}$/u),
758
+ artifactSetSha256: z.string().regex(/^[0-9a-f]{64}$/u),
759
+ formatterVersion: z.literal(1),
760
+ markdownSha256: z.string().regex(/^[0-9a-f]{64}$/u),
761
+ installedArtifacts: z.array(
762
+ z
763
+ .object({
764
+ artifactId: z.string().trim().min(1),
765
+ workspaceRelativePath: z.string().trim().min(1),
766
+ })
767
+ .strict(),
768
+ ),
769
+ })
770
+ .strict(),
771
+ })
772
+ .strict(),
773
+ ]);
774
+ export type ZCodeSessionImportHistory = z.infer<typeof zcodeSessionImportHistorySchema>;
775
+
776
+ export const zcodeThoughtLevelOptionSchema = z
777
+ .object({
778
+ value: nonEmptyString,
779
+ label: nonEmptyString,
780
+ description: z.string().optional(),
781
+ })
782
+ .strict();
783
+ export const zcodeModelReasoningOptionsSchema = z
784
+ .object({
785
+ levels: z.array(zcodeThoughtLevelOptionSchema),
786
+ defaultLevel: nonEmptyString.optional(),
787
+ })
788
+ .strict();
789
+ export type ZCodeModelReasoningOptions = z.infer<typeof zcodeModelReasoningOptionsSchema>;
790
+
791
+ export const zcodeModelFormatPropertiesSchema = completeModelPropertiesDataSchema.pick({
792
+ inputFormat: true,
793
+ outputFormat: true,
794
+ });
795
+ export type ZCodeModelFormatProperties = z.infer<typeof zcodeModelFormatPropertiesSchema>;
796
+
797
+ export const zcodeModelOptionSchema = z
798
+ .object({
799
+ ref: modelSelectionSchema,
800
+ label: nonEmptyString,
801
+ providerLabel: nonEmptyString.optional(),
802
+ description: z.string().optional(),
803
+ contextWindow: z.number().int().positive().optional(),
804
+ maxOutputTokens: z.number().int().positive().optional(),
805
+ reasoning: zcodeModelReasoningOptionsSchema.optional(),
806
+ properties: zcodeModelFormatPropertiesSchema,
807
+ disabledReason: z.string().optional(),
808
+ })
809
+ .strict();
810
+ export type ZCodeModelOption = z.infer<typeof zcodeModelOptionSchema>;
811
+
812
+ export const zcodeAccountAccessSchema = z.discriminatedUnion("planKind", [
813
+ z
814
+ .object({
815
+ type: z.literal("zhipu-account"),
816
+ family: z.enum(["zai", "bigmodel"]),
817
+ planKind: z.literal("start-plan"),
818
+ })
819
+ .strict(),
820
+ z
821
+ .object({
822
+ type: z.literal("zhipu-account"),
823
+ family: z.enum(["zai", "bigmodel"]),
824
+ planKind: z.literal("individual-coding-plan"),
825
+ })
826
+ .strict(),
827
+ z
828
+ .object({
829
+ type: z.literal("zhipu-account"),
830
+ family: z.enum(["zai", "bigmodel"]),
831
+ planKind: z.literal("team-coding-plan"),
832
+ productId: nonEmptyString,
833
+ organizationId: nonEmptyString,
834
+ projectId: nonEmptyString,
835
+ })
836
+ .strict(),
837
+ ]);
838
+ export type ZCodeAccountAccess = z.infer<typeof zcodeAccountAccessSchema>;
839
+
840
+ /** Active Model 固定的账号访问类别;当前商品和 Team scope 由账号服务在请求期解析。 */
841
+ export const zcodeProviderAccountAccessSchema = z
842
+ .object({
843
+ type: z.literal("zhipu-account"),
844
+ accountType: z.enum(["zai", "bigmodel"]),
845
+ mode: z.enum(["start-plan", "individual-coding-plan", "team-coding-plan", "off-peak"]),
846
+ entitled: z.boolean(),
847
+ })
848
+ .strict();
849
+ export type ZCodeProviderAccountAccess = z.infer<typeof zcodeProviderAccountAccessSchema>;
850
+
851
+ export type ZCodeSessionMode = z.infer<typeof zcodeSessionModeSchema>;
852
+ export type ZCodeSessionKind = z.infer<typeof zcodeSessionKindSchema>;
853
+ export type ZCodeSessionGoal = z.infer<typeof zcodeSessionGoalSchema>;
854
+
855
+ export const zcodeSessionTodoItemSchema = z
856
+ .object({
857
+ content: nonEmptyString,
858
+ status: z.enum(["pending", "in_progress", "completed"]),
859
+ priority: z.enum(["high", "medium", "low"]),
860
+ })
861
+ .strict();
862
+ export const zcodeSessionGoalStatsSchema = z
863
+ .object({
864
+ timeUsedSeconds: z.number().int().nonnegative(),
865
+ tokensUsed: z.number().int().nonnegative(),
866
+ tokenBudget: z.number().int().positive().nullable(),
867
+ contextUsed: z.number().int().nonnegative(),
868
+ contextWindow: z.number().int().nonnegative(),
869
+ toolCallCount: z.number().int().nonnegative(),
870
+ iterationCount: z.number().int().nonnegative(),
871
+ })
872
+ .strict();
873
+ export type ZCodeSessionGoalStats = z.infer<typeof zcodeSessionGoalStatsSchema>;
874
+ export type ZCodeSessionGoalVerification = z.infer<typeof zcodeSessionGoalVerificationSchema>;
875
+ export type ZCodeSessionGoalVerificationTimeline = z.infer<
876
+ typeof zcodeSessionGoalVerificationTimelineSchema
877
+ >;
878
+
879
+ export const zcodeSessionTodoGroupSchema = z
880
+ .object({
881
+ id: nonEmptyString,
882
+ source: z.enum(["goal_iteration", "session"]),
883
+ goalIteration: z.number().int().positive().optional(),
884
+ targetId: nonEmptyString.optional(),
885
+ startedAt: timestampMsSchema.optional(),
886
+ updatedAt: timestampMsSchema.optional(),
887
+ todos: z.array(zcodeSessionTodoItemSchema),
888
+ })
889
+ .strict();
890
+ export type ZCodeSessionTodoGroup = z.infer<typeof zcodeSessionTodoGroupSchema>;
891
+
892
+ export const zcodeSessionSettingsStateSchema = z
893
+ .object({
894
+ model: z
895
+ .object({
896
+ // 未绑定是合法恢复状态;不能为满足协议而伪造模型或阻断历史读取。
897
+ current: modelSelectionSchema.optional(),
898
+ available: z.array(zcodeModelOptionSchema),
899
+ lastUsed: modelSelectionSchema.optional(),
900
+ })
901
+ .strict(),
902
+ thoughtLevel: z
903
+ .object({
904
+ enabled: z.boolean(),
905
+ current: nonEmptyString.optional(),
906
+ defaultLevel: nonEmptyString.optional(),
907
+ available: z.array(zcodeThoughtLevelOptionSchema),
908
+ })
909
+ .strict(),
910
+ mode: z
911
+ .object({
912
+ current: zcodeSessionModeSchema,
913
+ })
914
+ .strict(),
915
+ permission: z
916
+ .object({
917
+ mode: zcodeSessionModeSchema.optional(),
918
+ rulesRevision: z.number().int().nonnegative().optional(),
919
+ })
920
+ .strict()
921
+ .optional(),
922
+ })
923
+ .strict();
924
+ export type ZCodeSessionSettingsState = z.infer<typeof zcodeSessionSettingsStateSchema>;
925
+ export const zcodePendingPermissionSchema = z
926
+ .object({
927
+ requestId: nonEmptyString,
928
+ toolCallId: nonEmptyString,
929
+ toolName: nonEmptyString,
930
+ reason: z.string(),
931
+ riskLevel: z.enum(["low", "medium", "high", "critical"]),
932
+ input: z.unknown().optional(),
933
+ origin: zcodeInteractionRequestOriginSchema.optional(),
934
+ options: z.array(zcodePermissionOptionSchema).min(1),
935
+ requestedAt: timestampMsSchema,
936
+ })
937
+ .strict();
938
+ export type ZCodePendingPermission = z.infer<typeof zcodePendingPermissionSchema>;
939
+
940
+ export const zcodeActiveToolCallSchema = z
941
+ .object({
942
+ toolCallId: nonEmptyString,
943
+ toolName: nonEmptyString,
944
+ status: z.enum(["pending", "running", "completed", "failed", "denied"]),
945
+ startedAt: timestampMsSchema.optional(),
946
+ })
947
+ .strict();
948
+ export type ZCodeActiveToolCall = z.infer<typeof zcodeActiveToolCallSchema>;
949
+
950
+ export const zcodeSessionProjectionSchema = z
951
+ .object({
952
+ sessionId: nonEmptyString,
953
+ status: zcodeSessionStatusSchema,
954
+ mode: zcodeSessionModeSchema,
955
+ turnCount: z.number().int().nonnegative(),
956
+ totalTokenCount: z.number().int().nonnegative(),
957
+ contextUsed: z.number().int().nonnegative(),
958
+ contextWindow: z.number().int().nonnegative(),
959
+ currentTurnId: nonEmptyString.optional(),
960
+ pendingPermissions: z.array(zcodePendingPermissionSchema),
961
+ activeToolCalls: z.array(zcodeActiveToolCallSchema),
962
+ backgroundJobs: z.array(jsonObjectSchema),
963
+ target: zcodeSessionGoalSchema.nullable().optional(),
964
+ lastError: z
965
+ .object({
966
+ type: nonEmptyString,
967
+ code: nonEmptyString.optional(),
968
+ message: nonEmptyString,
969
+ detail: z.string().optional(),
970
+ attribution: errorAttributionSchema.optional(),
971
+ })
972
+ .strict()
973
+ .optional(),
974
+ })
975
+ .strict();
976
+ export type ZCodeSessionProjection = z.infer<typeof zcodeSessionProjectionSchema>;
977
+ export type ZCodeToolState = z.infer<typeof zcodeToolStateSchema>;
978
+ export const zcodeSlashCommandSchema = z
979
+ .object({
980
+ name: nonEmptyString,
981
+ description: z.string(),
982
+ inputHint: z.string().optional(),
983
+ source: z.enum(["builtin", "custom"]).optional(),
984
+ })
985
+ .strict();
986
+ export type ZCodeSessionApiRetryStatus = z.infer<typeof zcodeSessionApiRetryStatusSchema>;
987
+ export type ZCodeSessionContextUsage = z.infer<typeof zcodeSessionContextUsageSchema>;
988
+ export const zcodeModelStreamingKindSchema = z.enum([
989
+ "start",
990
+ "finish",
991
+ "error",
992
+ "text_start",
993
+ "text_delta",
994
+ "text_end",
995
+ "reasoning_start",
996
+ "reasoning_delta",
997
+ "reasoning_end",
998
+ "tool_input_start",
999
+ "tool_input_delta",
1000
+ "tool_input_end",
1001
+ "tool_call",
1002
+ ]);
1003
+ export const zcodeModelStreamingEventPayloadSchema = z
1004
+ .object({
1005
+ assistantMessageId: z.string().optional(),
1006
+ delta: z.string().optional(),
1007
+ done: z.boolean().optional(),
1008
+ input: z.unknown().optional(),
1009
+ kind: zcodeModelStreamingKindSchema,
1010
+ partId: z.string().optional(),
1011
+ providerExecuted: z.boolean().optional(),
1012
+ toolCallId: z.string().optional(),
1013
+ toolName: z.string().optional(),
1014
+ })
1015
+ .strict();
1016
+ export const zcodeSessionStateSnapshotSchema = z
1017
+ .object({
1018
+ protocol: z
1019
+ .object({
1020
+ name: z.literal(ZCODE_PROTOCOL_NAME),
1021
+ version: z.literal(ZCODE_PROTOCOL_VERSION),
1022
+ })
1023
+ .strict(),
1024
+ session: zcodeSessionInfoSchema,
1025
+ settings: zcodeSessionSettingsStateSchema,
1026
+ projection: zcodeSessionProjectionSchema,
1027
+ runtime: zcodeSessionRuntimeStateSchema,
1028
+ messages: z.array(zcodeMessageWithPartsSchema),
1029
+ goalStats: zcodeSessionGoalStatsSchema.optional(),
1030
+ todos: z.array(zcodeSessionTodoItemSchema).optional(),
1031
+ todoGroups: z.array(zcodeSessionTodoGroupSchema).optional(),
1032
+ slashCommands: z.array(zcodeSlashCommandSchema).optional(),
1033
+ })
1034
+ .strict();
1035
+ export type ZCodeSessionStateSnapshot = z.infer<typeof zcodeSessionStateSnapshotSchema>;
1036
+
1037
+ export const zcodeEventEnvelopeSchema = z
1038
+ .object({
1039
+ eventId: nonEmptyString,
1040
+ sessionId: nonEmptyString,
1041
+ turnId: nonEmptyString.optional(),
1042
+ seq: z.number().int().nonnegative(),
1043
+ traceId: nonEmptyString.optional(),
1044
+ timestamp: timestampMsSchema,
1045
+ deliveryKind: zcodeDeliveryKindSchema.optional(),
1046
+ })
1047
+ .strict();
1048
+
1049
+ const zcodeComputerUseOperationEventBaseSchema = z
1050
+ .object({
1051
+ eventId: nonEmptyString,
1052
+ sequenceNumber: z.number().int().nonnegative(),
1053
+ sessionId: nonEmptyString,
1054
+ timestamp: timestampMsSchema,
1055
+ })
1056
+ .strict();
1057
+
1058
+ const zcodeComputerUseTurnStartedEventSchema = zcodeComputerUseOperationEventBaseSchema.extend({
1059
+ kind: z.literal("turn-started"),
1060
+ turnId: nonEmptyString,
1061
+ });
1062
+ const zcodeComputerUseTurnCompletedEventSchema = zcodeComputerUseOperationEventBaseSchema.extend({
1063
+ kind: z.literal("turn-completed"),
1064
+ turnId: nonEmptyString,
1065
+ });
1066
+ const zcodeComputerUseTurnFailedEventSchema = zcodeComputerUseOperationEventBaseSchema.extend({
1067
+ kind: z.literal("turn-failed"),
1068
+ turnId: nonEmptyString,
1069
+ });
1070
+ const zcodeComputerUseToolScheduledEventSchema = zcodeComputerUseOperationEventBaseSchema.extend({
1071
+ kind: z.literal("tool-scheduled"),
1072
+ turnId: nonEmptyString,
1073
+ toolCallId: nonEmptyString,
1074
+ toolName: nonEmptyString,
1075
+ // 这个 cell 是否在用 Computer Use。只表达布尔事实,不再携带动作名——旧的
1076
+ // operationAction 靠从模型源码里抽取动作名得到,SDK 面一变就整体失配(见
1077
+ // bootstrap/src/zcode-protocol/computer-use-operation-event.ts 的 usesComputerUse)。
1078
+ // 只挂在 scheduled 上:ToolCallStartedPayload 没有 input,start 时已拿不到模型源码。
1079
+ computerUse: z.literal(true).optional(),
1080
+ });
1081
+ const zcodeComputerUseToolStartedEventSchema = zcodeComputerUseOperationEventBaseSchema.extend({
1082
+ kind: z.literal("tool-started"),
1083
+ turnId: nonEmptyString.optional(),
1084
+ toolCallId: nonEmptyString,
1085
+ toolName: nonEmptyString.optional(),
1086
+ });
1087
+ const zcodeComputerUseSessionClosedEventSchema = zcodeComputerUseOperationEventBaseSchema.extend({
1088
+ kind: z.literal("session-closed"),
1089
+ });
1090
+
1091
+ export const zcodeComputerUseOperationEventSchema = z.discriminatedUnion("kind", [
1092
+ zcodeComputerUseTurnStartedEventSchema,
1093
+ zcodeComputerUseTurnCompletedEventSchema,
1094
+ zcodeComputerUseTurnFailedEventSchema,
1095
+ zcodeComputerUseToolScheduledEventSchema,
1096
+ zcodeComputerUseToolStartedEventSchema,
1097
+ zcodeComputerUseSessionClosedEventSchema,
1098
+ ]);
1099
+ export type ZCodeComputerUseOperationEvent = z.infer<typeof zcodeComputerUseOperationEventSchema>;
1100
+
1101
+ export const zcodeSessionEventTypeSchema = z.enum([
1102
+ "session.created",
1103
+ "session.resumed",
1104
+ "session.updated",
1105
+ "session.titleUpdated",
1106
+ "session.closed",
1107
+ "turn.started",
1108
+ "turn.steerQueued",
1109
+ "turn.steerDrained",
1110
+ "turn.completed",
1111
+ "turn.failed",
1112
+ "message.upserted",
1113
+ "message.removed",
1114
+ "part.started",
1115
+ "part.delta",
1116
+ "part.upserted",
1117
+ "part.removed",
1118
+ "model.streaming",
1119
+ "tool.updated",
1120
+ "permission.requested",
1121
+ "permission.resolved",
1122
+ "userInput.requested",
1123
+ "userInput.resolved",
1124
+ "checkpoint.created",
1125
+ "rewind.triggered",
1126
+ "streamRecovery.updated",
1127
+ ]);
1128
+ export type ZCodeSessionEventType = z.infer<typeof zcodeSessionEventTypeSchema>;
1129
+
1130
+ export const zcodeProtocolErrorDetailSchema = z
1131
+ .object({
1132
+ type: nonEmptyString,
1133
+ message: nonEmptyString,
1134
+ stack: z.string().optional(),
1135
+ code: z.string().optional(),
1136
+ detail: z.string().optional(),
1137
+ underlyingErrorMessage: z.string().optional(),
1138
+ underlyingErrorDetail: z.string().optional(),
1139
+ attribution: errorAttributionSchema.optional(),
1140
+ retryable: z.boolean().optional(),
1141
+ data: z.unknown().optional(),
1142
+ })
1143
+ .strict();
1144
+ export const zcodeSessionCreatedEventPayloadSchema = z
1145
+ .object({
1146
+ mode: zcodeSessionModeSchema,
1147
+ contextWindow: z.number().int().nonnegative(),
1148
+ })
1149
+ .strict();
1150
+ export const zcodeSessionResumedEventPayloadSchema = z
1151
+ .object({
1152
+ directory: nonEmptyString,
1153
+ interruptedToolCount: z.number().int().nonnegative(),
1154
+ messageCount: z.number().int().nonnegative(),
1155
+ partCount: z.number().int().nonnegative(),
1156
+ recoveredCompactTimelineCount: z.number().int().nonnegative().optional(),
1157
+ recoveredSteerInputCount: z.number().int().nonnegative().optional(),
1158
+ resumedTodoCount: z.number().int().nonnegative().optional(),
1159
+ })
1160
+ .strict();
1161
+ export const zcodeSessionTitleUpdatedEventPayloadSchema = z
1162
+ .object({
1163
+ messageID: nonEmptyString.optional(),
1164
+ previousTitle: z.string(),
1165
+ source: z.enum(["default", "first_input", "generated", "custom"]),
1166
+ title: z.string(),
1167
+ })
1168
+ .strict();
1169
+ export const zcodeTurnStartedEventPayloadSchema = z
1170
+ .object({
1171
+ turnNumber: z.number().int().nonnegative(),
1172
+ input: z.string(),
1173
+ inputId: nonEmptyString.optional(),
1174
+ queryId: nonEmptyString.optional(),
1175
+ inputSource: zcodeTurnInputSourceSchema.optional(),
1176
+ inputVisibility: zcodeMessageVisibilitySchema.optional(),
1177
+ executionKind: z.enum(["agent", "controlOnly"]).optional(),
1178
+ targetId: nonEmptyString.optional(),
1179
+ messageId: nonEmptyString.optional(),
1180
+ foregroundExecutionId: nonEmptyString.optional(),
1181
+ intent: jsonObjectSchema.optional(),
1182
+ originMeta: jsonObjectSchema.optional(),
1183
+ // runtime 会透传后台唤醒来源,strict schema 必须同步声明以免丢弃整条事件。
1184
+ backgroundSource: z.enum(["bash", "subagent"]).optional(),
1185
+ attachments: z.array(jsonObjectSchema).optional(),
1186
+ })
1187
+ .strict();
1188
+ const zcodeTurnSteerSourceSchema = z.enum(["plan_approval_feedback", "workflow_refine_feedback"]);
1189
+ const zcodeTurnSteerCommandKindSchema = z.enum(["sendText", "sendGoalCommand", "compact"]);
1190
+ const zcodeTurnSteerDeliverySchema = z.enum(["queue", "guide"]);
1191
+
1192
+ export const zcodeTurnSteerQueuedEventPayloadSchema = z
1193
+ .object({
1194
+ pendingInputId: nonEmptyString,
1195
+ inputId: nonEmptyString.optional(),
1196
+ queryId: nonEmptyString.optional(),
1197
+ input: z.string(),
1198
+ inputPreview: z.string(),
1199
+ inputSize: z.number().int().nonnegative(),
1200
+ commandKind: zcodeTurnSteerCommandKindSchema.optional(),
1201
+ source: zcodeTurnSteerSourceSchema.optional(),
1202
+ toolDisallowlist: z.array(nonEmptyString).optional(),
1203
+ delivery: zcodeTurnSteerDeliverySchema.optional(),
1204
+ targetTurnId: nonEmptyString,
1205
+ queueLength: z.number().int().nonnegative(),
1206
+ intent: jsonObjectSchema.optional(),
1207
+ })
1208
+ .strict();
1209
+ export const zcodeTurnSteerDrainedEventPayloadSchema = z
1210
+ .object({
1211
+ pendingInputIds: z.array(nonEmptyString),
1212
+ queryIds: z.array(nonEmptyString).optional(),
1213
+ targetTurnId: nonEmptyString,
1214
+ injectedMessageIds: z.array(nonEmptyString),
1215
+ drainedInputs: z
1216
+ .array(
1217
+ z
1218
+ .object({
1219
+ pendingInputId: nonEmptyString,
1220
+ messageId: nonEmptyString,
1221
+ text: z.string(),
1222
+ delivery: zcodeTurnSteerDeliverySchema.optional(),
1223
+ intent: jsonObjectSchema.optional(),
1224
+ toolDisallowlist: z.array(nonEmptyString).optional(),
1225
+ })
1226
+ .strict(),
1227
+ )
1228
+ .optional(),
1229
+ })
1230
+ .strict();
1231
+ export const zcodeTurnCompletedEventPayloadSchema = z
1232
+ .object({
1233
+ response: z.string(),
1234
+ tokenCount: z.number().int().nonnegative(),
1235
+ usage: z.unknown().optional(),
1236
+ toolCallCount: z.number().int().nonnegative(),
1237
+ historyRoundCount: z.number().int().nonnegative().optional(),
1238
+ duration: z.number().nonnegative(),
1239
+ // runtime turn.completed 会附带 cacheStats,协议 schema 之前漏掉该字段。
1240
+ // strict 校验失败会让桌面端丢掉终态事件,表现为消息已完成但 UI 一直没有回复。
1241
+ cacheStats: z
1242
+ .object({
1243
+ totalMessages: z.number().int().nonnegative(),
1244
+ cachedMessages: z.number().int().nonnegative(),
1245
+ lastCacheHit: z.boolean(),
1246
+ cacheReadTokens: z.number().int().nonnegative().optional(),
1247
+ })
1248
+ .strict()
1249
+ .optional(),
1250
+ inputId: nonEmptyString.optional(),
1251
+ resultType: z.enum([
1252
+ "success",
1253
+ // "cancelled": 用户主动中断属于正常结束,复用 turn.completed 上报,避免被映射成 turn.failed。
1254
+ "cancelled",
1255
+ "error_max_turns",
1256
+ "error_max_budget",
1257
+ "error_during_execution",
1258
+ "error_max_tool_calls",
1259
+ ]),
1260
+ backgroundSubagentResultConsumed: z.boolean().optional(),
1261
+ })
1262
+ .strict();
1263
+ export const zcodeTurnFailedEventPayloadSchema = z
1264
+ .object({
1265
+ error: zcodeProtocolErrorDetailSchema,
1266
+ turnPhase: z.string(),
1267
+ inputId: nonEmptyString.optional(),
1268
+ backgroundSubagentResultConsumed: z.boolean().optional(),
1269
+ })
1270
+ .strict();
1271
+ export const zcodeMessageUpsertedEventPayloadSchema = z
1272
+ .object({
1273
+ content: z.string(),
1274
+ attachments: z.array(z.unknown()).optional(),
1275
+ toolCalls: z.array(z.unknown()).optional(),
1276
+ type: z.string().optional(),
1277
+ compactBoundary: z.unknown().optional(),
1278
+ })
1279
+ .strict();
1280
+ export const zcodeMessageRemovedEventPayloadSchema = z
1281
+ .object({
1282
+ messageId: nonEmptyString,
1283
+ reason: z.string().optional(),
1284
+ })
1285
+ .strict();
1286
+ export const zcodeMessagePartDeltaEventPayloadSchema = z
1287
+ .object({
1288
+ messageId: nonEmptyString,
1289
+ partId: nonEmptyString,
1290
+ field: z.enum(["text", "reasoning", "input", "output"]).optional(),
1291
+ delta: z.string(),
1292
+ })
1293
+ .strict();
1294
+ export const zcodeMessagePartUpsertedEventPayloadSchema = z
1295
+ .object({
1296
+ part: zcodeMessagePartSchema,
1297
+ })
1298
+ .strict();
1299
+ export const zcodeMessagePartRemovedEventPayloadSchema = z
1300
+ .object({
1301
+ messageId: nonEmptyString,
1302
+ partId: nonEmptyString,
1303
+ reason: z.string().optional(),
1304
+ })
1305
+ .strict();
1306
+ const zcodeToolCallBasePayloadSchema = z
1307
+ .object({
1308
+ toolCallId: nonEmptyString,
1309
+ toolName: z.string().optional(),
1310
+ parentToolCallId: nonEmptyString.optional(),
1311
+ source: z.enum(["subagent"]).optional(),
1312
+ agentId: nonEmptyString.optional(),
1313
+ agentType: nonEmptyString.optional(),
1314
+ // subagent mirror 会携带后台归因;strict schema 漏字段会让 session/event 整条被丢弃。
1315
+ background: z.boolean().optional(),
1316
+ childSessionId: nonEmptyString.optional(),
1317
+ childToolCallId: nonEmptyString.optional(),
1318
+ description: z.string().optional(),
1319
+ })
1320
+ .strict();
1321
+
1322
+ export const zcodeToolUpdatedEventPayloadSchema = z.discriminatedUnion("kind", [
1323
+ zcodeToolCallBasePayloadSchema
1324
+ .extend({
1325
+ kind: z.literal("scheduled"),
1326
+ // 修复:CLI 调度事件已携带所属消息 ID;漏声明会让严格校验丢弃整条事件。
1327
+ assistantMessageId: nonEmptyString.optional(),
1328
+ toolName: nonEmptyString,
1329
+ input: z.unknown().optional(),
1330
+ inputByteLength: z.number().int().nonnegative().optional(),
1331
+ inputOmitted: z.boolean().optional(),
1332
+ inputRef: z.literal("model_stream").optional(),
1333
+ dependencies: z.array(nonEmptyString).optional(),
1334
+ parallelGroupIndex: z.number().int().nonnegative().optional(),
1335
+ canRunParallel: z.boolean().optional(),
1336
+ schedule: jsonObjectSchema.optional(),
1337
+ })
1338
+ .strict(),
1339
+ zcodeToolCallBasePayloadSchema
1340
+ .extend({
1341
+ kind: z.literal("started"),
1342
+ startedAt: protocolInstantSchema,
1343
+ })
1344
+ .strict(),
1345
+ zcodeToolCallBasePayloadSchema
1346
+ .extend({
1347
+ kind: z.literal("progress"),
1348
+ elapsedMs: z.number().nonnegative().optional(),
1349
+ pid: z.number().int().optional(),
1350
+ stdoutBytes: z.number().int().nonnegative().optional(),
1351
+ stderrBytes: z.number().int().nonnegative().optional(),
1352
+ outputBytes: z.number().int().nonnegative().optional(),
1353
+ outputPreview: executionOutputPreviewSchema.optional(),
1354
+ stdoutTail: z.string().optional(),
1355
+ stderrTail: z.string().optional(),
1356
+ })
1357
+ .strict(),
1358
+ zcodeToolCallBasePayloadSchema
1359
+ .extend({
1360
+ kind: z.literal("result"),
1361
+ result: zcodeToolResultObjectSchema,
1362
+ duration: z.number().nonnegative(),
1363
+ })
1364
+ .strict(),
1365
+ zcodeToolCallBasePayloadSchema
1366
+ .extend({
1367
+ kind: z.literal("error"),
1368
+ error: zcodeProtocolErrorDetailSchema,
1369
+ })
1370
+ .strict(),
1371
+ z
1372
+ .object({
1373
+ kind: z.literal("batch"),
1374
+ toolCallIds: z.array(nonEmptyString),
1375
+ successCount: z.number().int().nonnegative(),
1376
+ errorCount: z.number().int().nonnegative(),
1377
+ })
1378
+ .strict(),
1379
+ zcodeToolCallBasePayloadSchema
1380
+ .extend({
1381
+ kind: z.literal("raw"),
1382
+ payload: jsonObjectSchema,
1383
+ })
1384
+ .strict(),
1385
+ ]);
1386
+ export const zcodePermissionRequestedEventPayloadSchema = z
1387
+ .object({
1388
+ requestId: nonEmptyString.optional(),
1389
+ toolCallId: nonEmptyString,
1390
+ toolName: nonEmptyString,
1391
+ riskLevel: z.enum(["low", "medium", "high", "critical"]),
1392
+ reason: z.string(),
1393
+ input: z.unknown(),
1394
+ suggestedPermissionUpdates: z.array(zcodePermissionUpdateSchema).optional(),
1395
+ origin: zcodeInteractionRequestOriginSchema.optional(),
1396
+ options: z.array(zcodePermissionOptionSchema).min(1),
1397
+ childSessionId: nonEmptyString.optional(),
1398
+ background: z.boolean().optional(),
1399
+ })
1400
+ .strict();
1401
+ export const zcodePermissionResolvedEventPayloadSchema = z
1402
+ .object({
1403
+ requestId: nonEmptyString.optional(),
1404
+ toolCallId: nonEmptyString,
1405
+ toolName: nonEmptyString.optional(),
1406
+ decision: zcodePermissionDecisionSchema.optional(),
1407
+ reason: z.string().optional(),
1408
+ modifiedInput: z.unknown().optional(),
1409
+ inputSummary: z.unknown().optional(),
1410
+ childSessionId: nonEmptyString.optional(),
1411
+ background: z.boolean().optional(),
1412
+ })
1413
+ .strict();
1414
+ export const zcodeUserInputRequestedEventPayloadSchema = z
1415
+ .object({
1416
+ requestId: nonEmptyString,
1417
+ prompt: z.string(),
1418
+ inputType: z.enum(["text", "choice", "confirm"]).optional(),
1419
+ choices: z.array(z.string()).optional(),
1420
+ })
1421
+ .strict();
1422
+ export const zcodeUserInputResolvedEventPayloadSchema = z
1423
+ .object({
1424
+ requestId: nonEmptyString,
1425
+ value: z.unknown().optional(),
1426
+ cancelled: z.boolean().optional(),
1427
+ })
1428
+ .strict();
1429
+ export const zcodeSessionClosedEventPayloadSchema = z
1430
+ .object({
1431
+ reason: z.string().optional(),
1432
+ })
1433
+ .strict();
1434
+
1435
+ function zcodeSessionEventEnvelopeFor<T extends ZCodeSessionEventType>(
1436
+ type: T,
1437
+ payload: z.ZodTypeAny,
1438
+ ) {
1439
+ return zcodeEventEnvelopeSchema.extend({
1440
+ type: z.literal(type),
1441
+ payload: payload.optional(),
1442
+ });
1443
+ }
1444
+
1445
+ export const zcodeSessionEventSchema = z.discriminatedUnion("type", [
1446
+ zcodeSessionEventEnvelopeFor("session.created", zcodeSessionCreatedEventPayloadSchema),
1447
+ zcodeSessionEventEnvelopeFor("session.resumed", zcodeSessionResumedEventPayloadSchema),
1448
+ zcodeSessionEventEnvelopeFor("session.updated", jsonObjectSchema),
1449
+ zcodeSessionEventEnvelopeFor("session.titleUpdated", zcodeSessionTitleUpdatedEventPayloadSchema),
1450
+ zcodeSessionEventEnvelopeFor("session.closed", zcodeSessionClosedEventPayloadSchema),
1451
+ zcodeSessionEventEnvelopeFor("turn.started", zcodeTurnStartedEventPayloadSchema),
1452
+ zcodeSessionEventEnvelopeFor("turn.steerQueued", zcodeTurnSteerQueuedEventPayloadSchema),
1453
+ zcodeSessionEventEnvelopeFor("turn.steerDrained", zcodeTurnSteerDrainedEventPayloadSchema),
1454
+ zcodeSessionEventEnvelopeFor("turn.completed", zcodeTurnCompletedEventPayloadSchema),
1455
+ zcodeSessionEventEnvelopeFor("turn.failed", zcodeTurnFailedEventPayloadSchema),
1456
+ zcodeSessionEventEnvelopeFor("message.upserted", zcodeMessageUpsertedEventPayloadSchema),
1457
+ zcodeSessionEventEnvelopeFor("message.removed", zcodeMessageRemovedEventPayloadSchema),
1458
+ zcodeSessionEventEnvelopeFor("part.started", zcodeMessagePartUpsertedEventPayloadSchema),
1459
+ zcodeSessionEventEnvelopeFor("part.delta", zcodeMessagePartDeltaEventPayloadSchema),
1460
+ zcodeSessionEventEnvelopeFor("part.upserted", zcodeMessagePartUpsertedEventPayloadSchema),
1461
+ zcodeSessionEventEnvelopeFor("part.removed", zcodeMessagePartRemovedEventPayloadSchema),
1462
+ zcodeSessionEventEnvelopeFor("model.streaming", zcodeModelStreamingEventPayloadSchema),
1463
+ zcodeSessionEventEnvelopeFor("tool.updated", zcodeToolUpdatedEventPayloadSchema),
1464
+ zcodeSessionEventEnvelopeFor("permission.requested", zcodePermissionRequestedEventPayloadSchema),
1465
+ zcodeSessionEventEnvelopeFor("permission.resolved", zcodePermissionResolvedEventPayloadSchema),
1466
+ zcodeSessionEventEnvelopeFor("userInput.requested", zcodeUserInputRequestedEventPayloadSchema),
1467
+ zcodeSessionEventEnvelopeFor("userInput.resolved", zcodeUserInputResolvedEventPayloadSchema),
1468
+ zcodeSessionEventEnvelopeFor("checkpoint.created", jsonObjectSchema),
1469
+ zcodeSessionEventEnvelopeFor("rewind.triggered", jsonObjectSchema),
1470
+ zcodeSessionEventEnvelopeFor("streamRecovery.updated", jsonObjectSchema),
1471
+ ]);
1472
+ export type ZCodeSessionEvent = z.infer<typeof zcodeSessionEventSchema>;
1473
+
1474
+ export const zcodeSessionEventsResultSchema = z
1475
+ .object({
1476
+ events: z.array(zcodeSessionEventSchema),
1477
+ })
1478
+ .strict();
1479
+ export const zcodeSessionMessagesResultSchema = z
1480
+ .object({
1481
+ messages: z.array(zcodeMessageWithPartsSchema),
1482
+ })
1483
+ .strict();
1484
+ export const zcodeStateUpdatedNotificationSchema = z
1485
+ .object({
1486
+ type: z.literal("state.updated"),
1487
+ scope: z.enum(["server", "workspace", "session"]),
1488
+ workspace: zcodeWorkspaceRefSchema.optional(),
1489
+ sessionId: nonEmptyString.optional(),
1490
+ revision: z.number().int().nonnegative(),
1491
+ reason: z.string().optional(),
1492
+ patch: z.unknown(),
1493
+ })
1494
+ .strict();
1495
+ export type ZCodeStateUpdatedNotification = z.infer<typeof zcodeStateUpdatedNotificationSchema>;
1496
+
1497
+ export const zcodeSessionSubscribeParamsSchema = z
1498
+ .object({
1499
+ sessionId: nonEmptyString,
1500
+ deliveryKind: zcodeDeliveryKindSchema,
1501
+ afterSeq: z.number().int().nonnegative().optional(),
1502
+ includeSnapshot: z.boolean().default(false),
1503
+ })
1504
+ .strict();
1505
+ export type ZCodeSessionSubscribeParams = z.infer<typeof zcodeSessionSubscribeParamsSchema>;
1506
+
1507
+ export const zcodeSessionSubscribeResultSchema = z
1508
+ .object({
1509
+ sessionId: nonEmptyString,
1510
+ eventSeq: z.number().int().nonnegative(),
1511
+ events: z.array(zcodeSessionEventSchema),
1512
+ snapshot: zcodeSessionStateSnapshotSchema.optional(),
1513
+ })
1514
+ .strict();
1515
+ export const zcodeSessionListResultSchema = z
1516
+ .object({
1517
+ sessions: z.array(zcodeSessionInfoSchema),
1518
+ })
1519
+ .strict();
1520
+
1521
+ const zcodeSessionSubagentBaseSchema = z
1522
+ .object({
1523
+ childSessionId: nonEmptyString,
1524
+ agentId: nonEmptyString.optional(),
1525
+ toolCallId: nonEmptyString.optional(),
1526
+ subagentType: nonEmptyString,
1527
+ title: nonEmptyString,
1528
+ summary: z.string().optional(),
1529
+ startedAt: z.number().int().nonnegative().optional(),
1530
+ endedAt: z.number().int().nonnegative().optional(),
1531
+ })
1532
+ .strict();
1533
+
1534
+ export const zcodeSessionRunningSubagentSchema = zcodeSessionSubagentBaseSchema.extend({
1535
+ status: z.enum(["running", "waiting", "blocked"]),
1536
+ });
1537
+ export type ZCodeSessionRunningSubagent = z.infer<typeof zcodeSessionRunningSubagentSchema>;
1538
+
1539
+ export const zcodeSessionEndedSubagentSchema = zcodeSessionSubagentBaseSchema.extend({
1540
+ status: z.enum(["success", "failed", "cancelled", "lost"]),
1541
+ });
1542
+ export type ZCodeSessionEndedSubagent = z.infer<typeof zcodeSessionEndedSubagentSchema>;
1543
+
1544
+ export const zcodeSessionSubagentsResultSchema = z
1545
+ .object({
1546
+ revision: z.number().int().nonnegative(),
1547
+ childSessionIds: z.array(nonEmptyString),
1548
+ running: z.array(zcodeSessionRunningSubagentSchema),
1549
+ ended: z
1550
+ .object({
1551
+ total: z.number().int().nonnegative(),
1552
+ items: z.array(zcodeSessionEndedSubagentSchema),
1553
+ nextCursor: nonEmptyString.optional(),
1554
+ })
1555
+ .strict(),
1556
+ })
1557
+ .strict();
1558
+ export type ZCodeSessionSubagentsResult = z.infer<typeof zcodeSessionSubagentsResultSchema>;
1559
+ export const zcodeSessionCreateParamsSchema = z
1560
+ .object({
1561
+ sessionId: nonEmptyString.optional(),
1562
+ workspace: zcodeWorkspaceRefSchema,
1563
+ parentSessionId: nonEmptyString.optional(),
1564
+ mode: zcodeSessionModeSchema.optional(),
1565
+ model: modelSelectionSchema.optional(),
1566
+ persistence: zcodeSessionPersistenceSchema.optional(),
1567
+ thoughtLevel: nonEmptyString.optional(),
1568
+ titleGenerationEnabled: z.boolean().optional(),
1569
+ mcpServers: z.array(zcodeProtocolMcpServerSchema).optional(),
1570
+ toolAllowlist: z.array(nonEmptyString).optional(),
1571
+ toolDenylist: z.array(nonEmptyString).optional(),
1572
+ importedHistory: zcodeSessionImportHistorySchema.optional(),
1573
+ // host 只按本地服务装配/远程/端形态决定是否注册工具,不读取灰度;
1574
+ // 缺省不下发 = 不注册;灰度与套餐准入在实际创建的 Host handler 校验。
1575
+ offPeakToolEnabled: z.boolean().optional(),
1576
+ // 动态工作流灰度:与 offPeakToolEnabled 同一
1577
+ // 模式——host 裁决后下发,缺省不下发 = 不注册工作流工具簇(fail-closed)。
1578
+ dynamicWorkflowEnabled: z.boolean().optional(),
1579
+ })
1580
+ .strict();
1581
+ export type ZCodeSessionCreateParams = z.infer<typeof zcodeSessionCreateParamsSchema>;
1582
+
1583
+ export const zcodeSessionResumeParamsSchema = z
1584
+ .object({
1585
+ sessionId: nonEmptyString,
1586
+ workspace: zcodeWorkspaceRefSchema.optional(),
1587
+ // 旧 session 尚无 runtime/model_selection entry 时,由同 task 的索引元数据提供迁移 hint。
1588
+ thoughtLevel: nonEmptyString.optional(),
1589
+ mcpServers: z.array(zcodeProtocolMcpServerSchema).optional(),
1590
+ // 冷恢复重建 runtime 时必须沿用 create 的工具面约束(否则会绕过 allow/deny,尤其 CUA 会话)。
1591
+ toolAllowlist: z.array(nonEmptyString).optional(),
1592
+ toolDenylist: z.array(nonEmptyString).optional(),
1593
+ // 与 create 同语义;resume 不带会导致冷恢复丢 Off-Peak 工具面。
1594
+ offPeakToolEnabled: z.boolean().optional(),
1595
+ // 与 create 同语义;resume 不带会导致冷恢复丢工作流工具簇。
1596
+ dynamicWorkflowEnabled: z.boolean().optional(),
1597
+ })
1598
+ .strict();
1599
+ export type ZCodeSessionResumeParams = z.infer<typeof zcodeSessionResumeParamsSchema>;
1600
+
1601
+ export const zcodeSessionListParamsSchema = z
1602
+ .object({
1603
+ workspace: zcodeWorkspaceRefSchema.optional(),
1604
+ // 显式身份查询包含隐藏会话;普通列表仍只返回主任务,避免索引修复激活 runtime。
1605
+ sessionIds: z.array(nonEmptyString).min(1).max(64).optional(),
1606
+ includeArchived: z.boolean().default(false),
1607
+ limit: z.number().int().positive().optional(),
1608
+ })
1609
+ .strict();
1610
+ export type ZCodeSessionListParams = z.infer<typeof zcodeSessionListParamsSchema>;
1611
+
1612
+ export const zcodeSessionSubagentsParamsSchema = z
1613
+ .object({
1614
+ sessionId: nonEmptyString,
1615
+ endedCursor: nonEmptyString.optional(),
1616
+ endedLimit: z.number().int().positive().max(100).default(20),
1617
+ })
1618
+ .strict();
1619
+ export type ZCodeSessionSubagentsParams = z.infer<typeof zcodeSessionSubagentsParamsSchema>;
1620
+
1621
+ export const zcodeUsageStatsParamsSchema = z
1622
+ .object({
1623
+ range: z.enum(APP_USAGE_RANGES),
1624
+ timeZone: z.string().optional(),
1625
+ })
1626
+ .strict();
1627
+ export const zcodeUsageStatsResultSchema = appUsageSnapshotSchema;
1628
+ export const zcodeTaskTokenUsageParamsSchema = z
1629
+ .object({
1630
+ sessionId: nonEmptyString,
1631
+ })
1632
+ .strict();
1633
+ export const zcodeTaskTokenUsageResultSchema = z
1634
+ .object({
1635
+ sessionId: nonEmptyString,
1636
+ totalTokens: z.number().int().nonnegative(),
1637
+ inputTokens: z.number().int().nonnegative(),
1638
+ outputTokens: z.number().int().nonnegative(),
1639
+ reasoningTokens: z.number().int().nonnegative(),
1640
+ cacheCreationTokens: z.number().int().nonnegative(),
1641
+ cacheReadTokens: z.number().int().nonnegative(),
1642
+ modelRequestCount: z.number().int().nonnegative(),
1643
+ modelErrorCount: z.number().int().nonnegative(),
1644
+ inputBaselineBySource: z.record(z.string(), z.number().int().nonnegative()),
1645
+ })
1646
+ .strict();
1647
+ export type ZCodeTaskTokenUsageResult = z.infer<typeof zcodeTaskTokenUsageResultSchema>;
1648
+
1649
+ export const zcodeSessionReadParamsSchema = z
1650
+ .object({
1651
+ sessionId: nonEmptyString,
1652
+ deliveryKind: zcodeDeliveryKindSchema.optional(),
1653
+ messageLimit: z.number().int().positive().optional(),
1654
+ afterSeq: z.number().int().nonnegative().optional(),
1655
+ })
1656
+ .strict();
1657
+ export type ZCodeSessionReadParams = z.infer<typeof zcodeSessionReadParamsSchema>;
1658
+
1659
+ export const zcodeSessionMessagesParamsSchema = z
1660
+ .object({
1661
+ sessionId: nonEmptyString,
1662
+ afterMessageId: nonEmptyString.optional(),
1663
+ limit: z.number().int().positive().optional(),
1664
+ })
1665
+ .strict();
1666
+ export type ZCodeSessionMessagesParams = z.infer<typeof zcodeSessionMessagesParamsSchema>;
1667
+
1668
+ export const zcodeSessionEventsParamsSchema = z
1669
+ .object({
1670
+ sessionId: nonEmptyString,
1671
+ afterSeq: z.number().int().nonnegative().optional(),
1672
+ limit: z.number().int().positive().optional(),
1673
+ })
1674
+ .strict();
1675
+ export type ZCodeSessionEventsParams = z.infer<typeof zcodeSessionEventsParamsSchema>;
1676
+
1677
+ export const zcodeSessionRuntimePreferencesScopeSchema = z.enum([
1678
+ "runtime-materialization",
1679
+ "user-execution",
1680
+ ]);
1681
+ export type ZCodeSessionRuntimePreferencesScope = z.infer<
1682
+ typeof zcodeSessionRuntimePreferencesScopeSchema
1683
+ >;
1684
+
1685
+ export const ZCODE_SESSION_RUNTIME_PREFERENCES_REQUEST_TIMEOUT_MS = 15_000;
1686
+
1687
+ export const zcodeSessionRequestRuntimePreferencesParamsSchema = z
1688
+ .object({
1689
+ sessionId: nonEmptyString,
1690
+ scope: zcodeSessionRuntimePreferencesScopeSchema,
1691
+ })
1692
+ .strict();
1693
+ export type ZCodeSessionRequestRuntimePreferencesParams = z.infer<
1694
+ typeof zcodeSessionRequestRuntimePreferencesParamsSchema
1695
+ >;
1696
+
1697
+ export const DEFAULT_ZCODE_MODEL_CONTEXT_BUDGET_STRATEGY = "preflight-v1" as const;
1698
+
1699
+ // 3.12.2:legacy 仅为旧协议接收兼容;Runtime 一律归一为上面的共享默认策略。
1700
+ export const zcodeModelContextBudgetStrategySchema = z.enum(["legacy", "preflight-v1"]);
1701
+ export type ZCodeModelContextBudgetStrategy = z.infer<typeof zcodeModelContextBudgetStrategySchema>;
1702
+
1703
+ export const zcodeSessionRuntimePreferencesResultSchema = z
1704
+ .object({
1705
+ nativeSearchEnhancementsEnabled: z.boolean(),
1706
+ memoryEnabled: z.boolean().default(false),
1707
+ askUserQuestionAutoResolutionEnabled: z.boolean().default(true),
1708
+ integratedTerminalShell: integratedTerminalShellSelectionSchema.optional(),
1709
+ // 兼容旧 Host:缺少字段时在协议解析边界使用当前默认策略。
1710
+ modelContextBudgetStrategy: zcodeModelContextBudgetStrategySchema.default(
1711
+ DEFAULT_ZCODE_MODEL_CONTEXT_BUDGET_STRATEGY,
1712
+ ),
1713
+ })
1714
+ .strict();
1715
+ export type ZCodeSessionRuntimePreferencesResult = z.infer<
1716
+ typeof zcodeSessionRuntimePreferencesResultSchema
1717
+ >;
1718
+
1719
+ /**
1720
+ * App 在提交 prompt 前只读采集的 IAB 可见状态。该字段只用于 provider-visible
1721
+ * ambient context,不进入用户可见 transcript;内容有界,禁止携带页面正文或凭据。
1722
+ */
1723
+ export const zcodeBrowserAmbientContextSchema = z
1724
+ .object({
1725
+ tabCount: z.number().int().positive().max(100),
1726
+ currentUrl: z.string().trim().min(1).max(4096).optional(),
1727
+ })
1728
+ .strict();
1729
+ export type ZCodeBrowserAmbientContext = z.infer<typeof zcodeBrowserAmbientContextSchema>;
1730
+
1731
+ export const zcodeSessionSendParamsSchema = z
1732
+ .object({
1733
+ sessionId: nonEmptyString,
1734
+ modelSelection: modelSelectionSchema.optional(),
1735
+ modelExecution: modelExecutionSchema.optional(),
1736
+ inputId: nonEmptyString.optional(),
1737
+ queryId: nonEmptyString.optional(),
1738
+ content: z.string(),
1739
+ attachments: z.array(jsonObjectSchema).optional(),
1740
+ browserAmbientContext: zcodeBrowserAmbientContextSchema.optional(),
1741
+ expectedRevision: z.number().int().nonnegative().optional(),
1742
+ expectedProviderRevision: nonEmptyString.optional(),
1743
+ automationId: nonEmptyString.optional(),
1744
+ offPeakTaskId: nonEmptyString.optional(),
1745
+ offPeakRunType: z.enum(["init", "resume"]).optional(),
1746
+ botDeliveryTarget: zcodeAutomationBotDeliveryTargetSchema.optional(),
1747
+ toolDenylist: z.array(nonEmptyString).optional(),
1748
+ })
1749
+ .strict()
1750
+ .superRefine((payload, context) => {
1751
+ if (payload.automationId && payload.offPeakTaskId) {
1752
+ context.addIssue({
1753
+ code: z.ZodIssueCode.custom,
1754
+ message: "automationId and offPeakTaskId are mutually exclusive",
1755
+ });
1756
+ }
1757
+ if (payload.offPeakRunType && !payload.offPeakTaskId) {
1758
+ context.addIssue({
1759
+ code: z.ZodIssueCode.custom,
1760
+ message: "offPeakRunType requires offPeakTaskId",
1761
+ path: ["offPeakRunType"],
1762
+ });
1763
+ }
1764
+ if (payload.modelExecution && !payload.modelSelection) {
1765
+ context.addIssue({
1766
+ code: z.ZodIssueCode.custom,
1767
+ message: "modelExecution requires modelSelection",
1768
+ path: ["modelExecution"],
1769
+ });
1770
+ }
1771
+ });
1772
+ export const zcodeSessionSendResultSchema = z
1773
+ .object({
1774
+ sessionId: nonEmptyString,
1775
+ accepted: z.literal(true),
1776
+ stateRevision: z.number().int().nonnegative(),
1777
+ })
1778
+ .strict();
1779
+ export type ZCodeSessionSendResult = z.infer<typeof zcodeSessionSendResultSchema>;
1780
+
1781
+ export const zcodeSessionHistoryTargetSchema = z.discriminatedUnion("kind", [
1782
+ z
1783
+ .object({
1784
+ kind: z.literal("turn"),
1785
+ turnIndex: z.number().int().nonnegative(),
1786
+ })
1787
+ .strict(),
1788
+ z
1789
+ .object({
1790
+ kind: z.literal("message"),
1791
+ messageId: nonEmptyString,
1792
+ })
1793
+ .strict(),
1794
+ z
1795
+ .object({
1796
+ kind: z.literal("checkpoint"),
1797
+ checkpointId: nonEmptyString,
1798
+ })
1799
+ .strict(),
1800
+ z
1801
+ .object({
1802
+ kind: z.literal("latestCheckpoint"),
1803
+ })
1804
+ .strict(),
1805
+ ]);
1806
+ export type ZCodeSessionHistoryTarget = z.infer<typeof zcodeSessionHistoryTargetSchema>;
1807
+
1808
+ export const zcodeSessionForkParamsSchema = z
1809
+ .object({
1810
+ sessionId: nonEmptyString,
1811
+ target: zcodeSessionHistoryTargetSchema.default({
1812
+ kind: "latestCheckpoint",
1813
+ }),
1814
+ expectedRevision: z.number().int().nonnegative().optional(),
1815
+ })
1816
+ .strict();
1817
+ export type ZCodeSessionForkParams = z.infer<typeof zcodeSessionForkParamsSchema>;
1818
+
1819
+ export const zcodeSessionForkResultSchema = z
1820
+ .object({
1821
+ forkedSessionId: nonEmptyString,
1822
+ parentSessionId: nonEmptyString.optional(),
1823
+ targetMessageId: nonEmptyString.optional(),
1824
+ targetCheckpointId: nonEmptyString.optional(),
1825
+ response: z.string(),
1826
+ snapshot: zcodeSessionStateSnapshotSchema,
1827
+ })
1828
+ .strict();
1829
+ export type ZCodeSessionForkResult = z.infer<typeof zcodeSessionForkResultSchema>;
1830
+
1831
+ export const zcodeSessionCompactParamsSchema = z
1832
+ .object({
1833
+ sessionId: nonEmptyString,
1834
+ inputId: nonEmptyString.optional(),
1835
+ instructions: z.string().optional(),
1836
+ expectedRevision: z.number().int().nonnegative().optional(),
1837
+ })
1838
+ .strict();
1839
+ export type ZCodeSessionCompactParams = z.infer<typeof zcodeSessionCompactParamsSchema>;
1840
+
1841
+ export const zcodeSessionCompactResultSchema = z
1842
+ .object({
1843
+ response: z.string(),
1844
+ snapshot: zcodeSessionStateSnapshotSchema,
1845
+ compact: z
1846
+ .object({
1847
+ state: z.enum(["accepted", "already_running"]),
1848
+ inputId: nonEmptyString.optional(),
1849
+ operationId: nonEmptyString.optional(),
1850
+ })
1851
+ .strict()
1852
+ .optional(),
1853
+ })
1854
+ .strict();
1855
+ export type ZCodeSessionCompactResult = z.infer<typeof zcodeSessionCompactResultSchema>;
1856
+
1857
+ export const zcodeSessionGoalActionSchema = z.enum([
1858
+ "show",
1859
+ "set",
1860
+ "replace",
1861
+ "pause",
1862
+ "resume",
1863
+ "clear",
1864
+ ]);
1865
+ export type ZCodeSessionGoalAction = z.infer<typeof zcodeSessionGoalActionSchema>;
1866
+
1867
+ export const zcodeSessionGoalParamsSchema = z
1868
+ .object({
1869
+ sessionId: nonEmptyString,
1870
+ inputId: nonEmptyString.optional(),
1871
+ action: zcodeSessionGoalActionSchema,
1872
+ objective: z.string().optional(),
1873
+ expectedRevision: z.number().int().nonnegative().optional(),
1874
+ })
1875
+ .strict();
1876
+ export type ZCodeSessionGoalParams = z.infer<typeof zcodeSessionGoalParamsSchema>;
1877
+
1878
+ export const zcodeSessionGoalResultSchema = z
1879
+ .object({
1880
+ response: z.string(),
1881
+ snapshot: zcodeSessionStateSnapshotSchema,
1882
+ startedTurn: z.boolean().optional(),
1883
+ })
1884
+ .strict();
1885
+ export type ZCodeSessionGoalResult = z.infer<typeof zcodeSessionGoalResultSchema>;
1886
+
1887
+ export const zcodeSessionStopParamsSchema = z
1888
+ .object({
1889
+ sessionId: nonEmptyString,
1890
+ })
1891
+ .strict();
1892
+ const zcodeBackgroundTaskInfoStatusSchema = z.enum([
1893
+ "running",
1894
+ "completed",
1895
+ "failed",
1896
+ "timed_out",
1897
+ "cancelled",
1898
+ "spawn_error",
1899
+ "lost",
1900
+ ]);
1901
+
1902
+ export const zcodeBackgroundTaskInfoSchema = z
1903
+ .object({
1904
+ taskId: nonEmptyString,
1905
+ toolCallId: nonEmptyString.optional(),
1906
+ toolName: nonEmptyString.optional(),
1907
+ taskKind: z.enum(["bash", "subagent"]).optional(),
1908
+ blocked: z.boolean().optional(),
1909
+ blockedReason: z.string().optional(),
1910
+ cancellable: z.boolean().optional(),
1911
+ cancelRequestedAt: protocolInstantSchema.optional(),
1912
+ command: z.string().optional(),
1913
+ description: z.string().optional(),
1914
+ status: zcodeBackgroundTaskInfoStatusSchema,
1915
+ pid: z.number().int().positive().optional(),
1916
+ startedAt: protocolInstantSchema.optional(),
1917
+ completedAt: protocolInstantSchema.optional(),
1918
+ outputPath: z.string().optional(),
1919
+ stderrPersistedOutputPath: z.string().optional(),
1920
+ stdoutPersistedOutputPath: z.string().optional(),
1921
+ outputBytes: z.number().int().nonnegative().optional(),
1922
+ outputTruncated: z.boolean().optional(),
1923
+ outputTail: z.string().optional(),
1924
+ stderrBytes: z.number().int().nonnegative().optional(),
1925
+ stderrTail: z.string().optional(),
1926
+ stdoutBytes: z.number().int().nonnegative().optional(),
1927
+ stdoutTail: z.string().optional(),
1928
+ terminalId: nonEmptyString.optional(),
1929
+ })
1930
+ .strict();
1931
+ export const zcodeSessionCancelBackgroundTaskParamsSchema = z
1932
+ .object({
1933
+ sessionId: nonEmptyString,
1934
+ taskId: nonEmptyString,
1935
+ })
1936
+ .strict();
1937
+ export type ZCodeSessionCancelBackgroundTaskParams = z.infer<
1938
+ typeof zcodeSessionCancelBackgroundTaskParamsSchema
1939
+ >;
1940
+
1941
+ export const zcodeSessionCancelBackgroundTaskResultSchema = z
1942
+ .object({
1943
+ cancelled: z.boolean(),
1944
+ reason: z.string().optional(),
1945
+ snapshot: zcodeBackgroundTaskInfoSchema.optional(),
1946
+ status: zcodeBackgroundTaskInfoStatusSchema,
1947
+ taskId: nonEmptyString,
1948
+ })
1949
+ .strict();
1950
+ export type ZCodeSessionCancelBackgroundTaskResult = z.infer<
1951
+ typeof zcodeSessionCancelBackgroundTaskResultSchema
1952
+ >;
1953
+
1954
+ export const zcodeSessionSetModelParamsSchema = z
1955
+ .object({
1956
+ sessionId: nonEmptyString,
1957
+ model: modelSelectionSchema,
1958
+ expectedRevision: z.number().int().nonnegative().optional(),
1959
+ persistAsWorkspaceLastUsed: z.boolean().default(true),
1960
+ })
1961
+ .strict();
1962
+ export type ZCodeSessionSetModelParams = z.infer<typeof zcodeSessionSetModelParamsSchema>;
1963
+
1964
+ export const zcodeSessionSetThoughtLevelParamsSchema = z
1965
+ .object({
1966
+ sessionId: nonEmptyString,
1967
+ thoughtLevel: nonEmptyString.optional(),
1968
+ expectedRevision: z.number().int().nonnegative().optional(),
1969
+ persistAsWorkspaceLastUsed: z.boolean().default(true),
1970
+ })
1971
+ .strict();
1972
+ export type ZCodeSessionSetThoughtLevelParams = z.infer<
1973
+ typeof zcodeSessionSetThoughtLevelParamsSchema
1974
+ >;
1975
+
1976
+ export const zcodeSessionSetModeParamsSchema = z
1977
+ .object({
1978
+ sessionId: nonEmptyString,
1979
+ mode: zcodeSessionModeSchema,
1980
+ expectedRevision: z.number().int().nonnegative().optional(),
1981
+ })
1982
+ .strict();
1983
+ export type ZCodeSessionSetModeParams = z.infer<typeof zcodeSessionSetModeParamsSchema>;
1984
+
1985
+ export const zcodeSessionCloseParamsSchema = z
1986
+ .object({
1987
+ sessionId: nonEmptyString,
1988
+ expectedPersistence: zcodeSessionPersistenceSchema.optional(),
1989
+ })
1990
+ .strict();
1991
+ export type ZCodeSessionCloseParams = z.infer<typeof zcodeSessionCloseParamsSchema>;
1992
+ export const zcodeSessionCloseResultSchema = z
1993
+ .object({
1994
+ closed: z.boolean().optional(),
1995
+ })
1996
+ .strict();
1997
+ export type ZCodeSessionCloseResult = z.infer<typeof zcodeSessionCloseResultSchema>;
1998
+ export const zcodeWorkspaceReadPresentationParamsSchema = z
1999
+ .object({ workspace: zcodeWorkspaceRefSchema })
2000
+ .strict();
2001
+ export const zcodeWorkspacePresentationSchema = z
2002
+ .object({
2003
+ workspace: zcodeWorkspaceRefSchema,
2004
+ mode: zcodeSessionModeSchema,
2005
+ slashCommands: z.array(zcodeSlashCommandSchema),
2006
+ })
2007
+ .strict();
2008
+ export type ZCodeWorkspacePresentation = z.infer<typeof zcodeWorkspacePresentationSchema>;
2009
+ const workspaceHookSha256DigestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
2010
+ export const zcodeWorkspaceHookTrustGrantParamsSchema = z
2011
+ .object({
2012
+ workspace: zcodeWorkspaceRefSchema,
2013
+ bundleDigest: workspaceHookSha256DigestSchema,
2014
+ hookDeclarationDigest: workspaceHookSha256DigestSchema,
2015
+ })
2016
+ .strict();
2017
+ export type ZCodeWorkspaceHookTrustGrantParams = z.infer<
2018
+ typeof zcodeWorkspaceHookTrustGrantParamsSchema
2019
+ >;
2020
+ export const zcodeWorkspaceHookTrustGrantReasonCodeSchema = z.enum([
2021
+ "workspace_hooks_blocked_by_policy",
2022
+ "workspace_hooks_bundle_changed",
2023
+ "workspace_hooks_snapshot_mismatch",
2024
+ "workspace_hooks_policy_requires_pretrust",
2025
+ "workspace_hooks_trust_store_corrupt",
2026
+ "workspace_hooks_config_unreadable",
2027
+ ]);
2028
+ export type ZCodeWorkspaceHookTrustGrantReasonCode = z.infer<
2029
+ typeof zcodeWorkspaceHookTrustGrantReasonCodeSchema
2030
+ >;
2031
+ export const zcodeWorkspaceHookTrustGrantResultSchema = z
2032
+ .object({
2033
+ accepted: z.boolean(),
2034
+ reasonCode: zcodeWorkspaceHookTrustGrantReasonCodeSchema.optional(),
2035
+ })
2036
+ .strict();
2037
+ export type ZCodeWorkspaceHookTrustGrantResult = z.infer<
2038
+ typeof zcodeWorkspaceHookTrustGrantResultSchema
2039
+ >;
2040
+ const zcodeWorkspaceModelToolCallSchema = z
2041
+ .object({
2042
+ id: nonEmptyString,
2043
+ name: nonEmptyString,
2044
+ input: z.unknown(),
2045
+ })
2046
+ .strict();
2047
+ const zcodeWorkspaceModelMessageSchema = z.discriminatedUnion("role", [
2048
+ z.object({ role: z.literal("system"), content: z.string() }).strict(),
2049
+ z.object({ role: z.literal("user"), content: z.string() }).strict(),
2050
+ z
2051
+ .object({
2052
+ role: z.literal("assistant"),
2053
+ content: z.string(),
2054
+ toolCalls: z.array(zcodeWorkspaceModelToolCallSchema).optional(),
2055
+ })
2056
+ .strict(),
2057
+ z
2058
+ .object({
2059
+ role: z.literal("tool"),
2060
+ content: z.string(),
2061
+ toolCallId: nonEmptyString,
2062
+ toolName: nonEmptyString,
2063
+ isError: z.boolean().optional(),
2064
+ })
2065
+ .strict(),
2066
+ ]);
2067
+ const zcodeWorkspaceModelToolSchema = z
2068
+ .object({
2069
+ name: nonEmptyString,
2070
+ description: z.string().optional(),
2071
+ inputSchema: z.record(z.string(), z.unknown()),
2072
+ })
2073
+ .strict();
2074
+
2075
+ export const zcodeWorkspaceGenerateTextParamsSchema = z
2076
+ .object({
2077
+ workspace: zcodeWorkspaceRefSchema,
2078
+ selection: modelSelectionSchema,
2079
+ prompt: nonEmptyString.optional(),
2080
+ messages: z.array(zcodeWorkspaceModelMessageSchema).min(1).optional(),
2081
+ tools: z.array(zcodeWorkspaceModelToolSchema).optional(),
2082
+ querySource: nonEmptyString,
2083
+ maxOutputTokens: z.number().int().positive().optional(),
2084
+ operationId: nonEmptyString.optional(),
2085
+ })
2086
+ .strict()
2087
+ .refine((value) => value.prompt !== undefined || value.messages !== undefined, {
2088
+ message: "prompt 或 messages 至少需要提供一个",
2089
+ });
2090
+ export const zcodeWorkspaceGenerateTextResultSchema = z
2091
+ .object({
2092
+ text: z.string(),
2093
+ selection: modelSelectionSchema,
2094
+ toolCalls: z.array(zcodeWorkspaceModelToolCallSchema).optional(),
2095
+ // 可选以兼容仍在运行的旧 app-server;新 CLI 始终返回结构化结束原因。
2096
+ finishReason: z.string().optional(),
2097
+ usage: z
2098
+ .object({
2099
+ inputTokens: z.number().nonnegative().optional(),
2100
+ outputTokens: z.number().nonnegative().optional(),
2101
+ totalTokens: z.number().nonnegative().optional(),
2102
+ cacheReadTokens: z.number().nonnegative().optional(),
2103
+ cacheWriteTokens: z.number().nonnegative().optional(),
2104
+ reasoningTokens: z.number().nonnegative().optional(),
2105
+ serverToolUse: z
2106
+ .object({
2107
+ webSearchRequests: z.number().nonnegative().optional(),
2108
+ webFetchRequests: z.number().nonnegative().optional(),
2109
+ })
2110
+ .strict()
2111
+ .optional(),
2112
+ })
2113
+ .strict()
2114
+ .optional(),
2115
+ })
2116
+ .strict();
2117
+ export type ZCodeWorkspaceGenerateTextParams = z.infer<
2118
+ typeof zcodeWorkspaceGenerateTextParamsSchema
2119
+ >;
2120
+ export type ZCodeWorkspaceModelMessage = z.infer<typeof zcodeWorkspaceModelMessageSchema>;
2121
+ export type ZCodeWorkspaceModelTool = z.infer<typeof zcodeWorkspaceModelToolSchema>;
2122
+ export type ZCodeWorkspaceGenerateTextResult = z.infer<
2123
+ typeof zcodeWorkspaceGenerateTextResultSchema
2124
+ >;
2125
+ export const zcodeWorkspaceCancelGenerateTextParamsSchema = z
2126
+ .object({ operationId: nonEmptyString })
2127
+ .strict();
2128
+ export const zcodeWorkspaceCancelGenerateTextResultSchema = z
2129
+ .object({ operationId: nonEmptyString, cancelled: z.boolean() })
2130
+ .strict();
2131
+
2132
+ export const zcodeProviderTestModelConnectivityParamsSchema = z
2133
+ .object({
2134
+ workspace: zcodeWorkspaceRefSchema,
2135
+ selection: modelSelectionSchema,
2136
+ })
2137
+ .strict();
2138
+ export const zcodeProviderTestModelConnectivityResultSchema = z
2139
+ .object({ success: z.literal(true) })
2140
+ .strict();
2141
+ export type ZCodeProviderTestModelConnectivityParams = z.infer<
2142
+ typeof zcodeProviderTestModelConnectivityParamsSchema
2143
+ >;
2144
+ export type ZCodeProviderTestModelConnectivityResult = z.infer<
2145
+ typeof zcodeProviderTestModelConnectivityResultSchema
2146
+ >;
2147
+
2148
+ export const zcodeProviderUpdateAccountConfigParamsSchema = z
2149
+ .object({
2150
+ revision: nonEmptyString,
2151
+ basedOnZCodeBuiltinRevision: nonEmptyString,
2152
+ // Provider Config 的字段校验由 @zcode/provider 负责;协议层只约束可传输信封。
2153
+ providers: z.record(z.string(), z.unknown()),
2154
+ // 账号状态与 Overlay 必须一起传递,否则 Worker 会丢失非当前套餐的执行门禁。
2155
+ states: z.record(
2156
+ z.string(),
2157
+ z
2158
+ .object({
2159
+ availability: z.enum(["available", "pending", "unavailable", "unknown"]),
2160
+ entitled: z.boolean(),
2161
+ unavailableReason: accountProviderUnavailableReasonSchema.optional(),
2162
+ current: z.boolean().optional(),
2163
+ connectionKey: z.string().optional(),
2164
+ effectiveAt: z.number().finite().optional(),
2165
+ })
2166
+ .strict(),
2167
+ ),
2168
+ })
2169
+ .strict();
2170
+ export const zcodeProviderUpdateAccountConfigResultSchema = z
2171
+ .object({
2172
+ // 收到账号结果不代表配套 Built-in 已到达;应用版本只能读取 Registry 快照。
2173
+ receivedRevision: nonEmptyString,
2174
+ providerCount: z.number().int().nonnegative(),
2175
+ status: z.enum(["received", "unchanged"]),
2176
+ })
2177
+ .strict();
2178
+ export type ZCodeProviderUpdateAccountConfigResult = z.infer<
2179
+ typeof zcodeProviderUpdateAccountConfigResultSchema
2180
+ >;
2181
+ export const zcodeInteractionPreferencesSchema = z
2182
+ .object({
2183
+ askUserQuestionAutoResolutionEnabled: z.boolean(),
2184
+ })
2185
+ .strict();
2186
+ export type ZCodeInteractionPreferences = z.infer<typeof zcodeInteractionPreferencesSchema>;
2187
+
2188
+ export const zcodeWorkspaceUpdateInteractionPreferencesParamsSchema = z
2189
+ .object({
2190
+ workspace: zcodeWorkspaceRefSchema,
2191
+ preferences: zcodeInteractionPreferencesSchema,
2192
+ })
2193
+ .strict();
2194
+ export type ZCodeWorkspaceUpdateInteractionPreferencesParams = z.infer<
2195
+ typeof zcodeWorkspaceUpdateInteractionPreferencesParamsSchema
2196
+ >;
2197
+
2198
+ export const zcodeWorkspaceUpdateInteractionPreferencesResultSchema = z
2199
+ .object({
2200
+ workspace: zcodeWorkspaceRefSchema,
2201
+ askUserQuestionAutoResolutionEnabled: z.boolean(),
2202
+ snoozedInteractionCount: z.number().int().nonnegative(),
2203
+ })
2204
+ .strict();
2205
+ export type ZCodeWorkspaceUpdateInteractionPreferencesResult = z.infer<
2206
+ typeof zcodeWorkspaceUpdateInteractionPreferencesResultSchema
2207
+ >;
2208
+
2209
+ export const zcodeModelIoPreferencesSchema = z
2210
+ .object({
2211
+ fullRetentionEnabled: z.boolean(),
2212
+ })
2213
+ .strict();
2214
+ export type ZCodeModelIoPreferences = z.infer<typeof zcodeModelIoPreferencesSchema>;
2215
+
2216
+ export const zcodeWorkspaceUpdateModelIoPreferencesParamsSchema = z
2217
+ .object({
2218
+ workspace: zcodeWorkspaceRefSchema,
2219
+ preferences: zcodeModelIoPreferencesSchema,
2220
+ })
2221
+ .strict();
2222
+ export type ZCodeWorkspaceUpdateModelIoPreferencesParams = z.infer<
2223
+ typeof zcodeWorkspaceUpdateModelIoPreferencesParamsSchema
2224
+ >;
2225
+
2226
+ export const zcodeWorkspaceUpdateModelIoPreferencesResultSchema = z
2227
+ .object({
2228
+ workspace: zcodeWorkspaceRefSchema,
2229
+ fullRetentionEnabled: z.boolean(),
2230
+ updatedSessionCount: z.number().int().nonnegative(),
2231
+ })
2232
+ .strict();
2233
+ export type ZCodeWorkspaceUpdateModelIoPreferencesResult = z.infer<
2234
+ typeof zcodeWorkspaceUpdateModelIoPreferencesResultSchema
2235
+ >;
2236
+
2237
+ export const zcodeWorkspaceUpdateOffPeakToolPolicyParamsSchema = z
2238
+ .object({
2239
+ workspace: zcodeWorkspaceRefSchema,
2240
+ enabled: z.boolean(),
2241
+ })
2242
+ .strict();
2243
+ export type ZCodeWorkspaceUpdateOffPeakToolPolicyParams = z.infer<
2244
+ typeof zcodeWorkspaceUpdateOffPeakToolPolicyParamsSchema
2245
+ >;
2246
+
2247
+ export const zcodeWorkspaceUpdateOffPeakToolPolicyResultSchema = z
2248
+ .object({
2249
+ workspace: zcodeWorkspaceRefSchema,
2250
+ enabled: z.boolean(),
2251
+ })
2252
+ .strict();
2253
+ export type ZCodeWorkspaceUpdateOffPeakToolPolicyResult = z.infer<
2254
+ typeof zcodeWorkspaceUpdateOffPeakToolPolicyResultSchema
2255
+ >;
2256
+
2257
+ // 动态工作流灰度门禁:workspace 级事实,
2258
+ // 与 Off-Peak 同一套 host→CLI 同步模式;旧 CLI method-not-found → host 降级忽略。
2259
+ export const zcodeWorkspaceUpdateDynamicWorkflowPolicyParamsSchema = z
2260
+ .object({
2261
+ workspace: zcodeWorkspaceRefSchema,
2262
+ enabled: z.boolean(),
2263
+ })
2264
+ .strict();
2265
+ export type ZCodeWorkspaceUpdateDynamicWorkflowPolicyParams = z.infer<
2266
+ typeof zcodeWorkspaceUpdateDynamicWorkflowPolicyParamsSchema
2267
+ >;
2268
+
2269
+ export const zcodeWorkspaceUpdateDynamicWorkflowPolicyResultSchema = z
2270
+ .object({
2271
+ workspace: zcodeWorkspaceRefSchema,
2272
+ enabled: z.boolean(),
2273
+ })
2274
+ .strict();
2275
+ export type ZCodeWorkspaceUpdateDynamicWorkflowPolicyResult = z.infer<
2276
+ typeof zcodeWorkspaceUpdateDynamicWorkflowPolicyResultSchema
2277
+ >;
2278
+
2279
+ export const zcodePermissionRequestParamsSchema = z
2280
+ .object({
2281
+ requestId: nonEmptyString,
2282
+ sessionId: nonEmptyString,
2283
+ turnId: nonEmptyString.optional(),
2284
+ toolCallId: nonEmptyString,
2285
+ toolName: nonEmptyString,
2286
+ reason: z.string(),
2287
+ riskLevel: z.enum(["low", "medium", "high", "critical"]),
2288
+ input: z.unknown(),
2289
+ origin: zcodeInteractionRequestOriginSchema.optional(),
2290
+ options: z.array(zcodePermissionOptionSchema).min(1),
2291
+ })
2292
+ .strict();
2293
+ export type ZCodePermissionRequestParams = z.infer<typeof zcodePermissionRequestParamsSchema>;
2294
+
2295
+ /** Agent 请求 app 枚举当前 workspace/session 可达且已完成握手的 browser backend。 */
2296
+ export const zcodeBrowserListParamsSchema = z
2297
+ .object({
2298
+ requestId: nonEmptyString,
2299
+ sessionId: nonEmptyString,
2300
+ turnId: nonEmptyString.optional(),
2301
+ workspaceKey: nonEmptyString,
2302
+ workspacePath: nonEmptyString,
2303
+ workspaceIdentity: nonEmptyString.optional(),
2304
+ remoteSessionId: nonEmptyString.optional(),
2305
+ clientMode: browserClientModeSchema,
2306
+ sessionContext: browserSessionContextKindSchema,
2307
+ })
2308
+ .strict();
2309
+ export type ZCodeBrowserListParams = z.infer<typeof zcodeBrowserListParamsSchema>;
2310
+
2311
+ export const zcodeBrowserListResultSchema = browserBackendListResultSchema;
2312
+ export type ZCodeBrowserListResult = z.infer<typeof zcodeBrowserListResultSchema>;
2313
+
2314
+ /** Agent 把一条 browser-use 命令发送给 app 执行。 */
2315
+ export const zcodeBrowserExecuteParamsSchema = z
2316
+ .object({
2317
+ requestId: nonEmptyString,
2318
+ sessionId: nonEmptyString,
2319
+ turnId: nonEmptyString.optional(),
2320
+ browserId: nonEmptyString.optional(),
2321
+ browserGeneration: z.number().int().nonnegative().optional(),
2322
+ workspaceKey: nonEmptyString.optional(),
2323
+ workspacePath: nonEmptyString.optional(),
2324
+ workspaceIdentity: nonEmptyString.optional(),
2325
+ remoteSessionId: nonEmptyString.optional(),
2326
+ clientMode: browserClientModeSchema.optional(),
2327
+ sessionContext: browserSessionContextKindSchema.optional(),
2328
+ command: browserCommandSchema,
2329
+ })
2330
+ .strict();
2331
+ export type ZCodeBrowserExecuteParams = z.infer<typeof zcodeBrowserExecuteParamsSchema>;
2332
+
2333
+ // browser command result 是 app/agent 的同源协议结果;其中 duplicate_request_id 用于在真正维护
2334
+ // pending/running 生命周期的边界拒绝 correlation key 冲突,不能依赖上游 UUID 概率保证。
2335
+ export const zcodeBrowserExecuteResultSchema = browserCommandResultSchema;
2336
+ export type ZCodeBrowserExecuteResult = z.infer<typeof zcodeBrowserExecuteResultSchema>;
2337
+
2338
+ export const zcodeUserInputOptionSchema = z
2339
+ .object({
2340
+ value: nonEmptyString,
2341
+ label: nonEmptyString,
2342
+ description: z.string().optional(),
2343
+ preview: z.string().optional(),
2344
+ })
2345
+ .strict();
2346
+ export const zcodeUserInputQuestionSchema = z
2347
+ .object({
2348
+ question: nonEmptyString,
2349
+ header: nonEmptyString,
2350
+ options: z.array(zcodeUserInputOptionSchema).min(1),
2351
+ multiSelect: z.boolean().optional(),
2352
+ })
2353
+ .strict();
2354
+ export type ZCodeUserInputQuestion = z.infer<typeof zcodeUserInputQuestionSchema>;
2355
+
2356
+ export const zcodeUserInputRequestParamsSchema = z
2357
+ .object({
2358
+ requestId: nonEmptyString,
2359
+ sessionId: nonEmptyString,
2360
+ turnId: nonEmptyString.optional(),
2361
+ toolCallId: nonEmptyString.optional(),
2362
+ toolName: nonEmptyString.optional(),
2363
+ prompt: z.string().optional(),
2364
+ questions: z.array(zcodeUserInputQuestionSchema).min(1).optional(),
2365
+ input: z.unknown().optional(),
2366
+ origin: zcodeInteractionRequestOriginSchema.optional(),
2367
+ schema: z.unknown().optional(),
2368
+ })
2369
+ .strict();
2370
+ export type ZCodeUserInputRequestParams = z.infer<typeof zcodeUserInputRequestParamsSchema>;
2371
+
2372
+ export const zcodeUserInputResponseSchema = z
2373
+ .object({
2374
+ action: z.enum(["accept", "decline", "cancel"]),
2375
+ content: jsonObjectSchema.optional(),
2376
+ reason: z.string().optional(),
2377
+ })
2378
+ .strict();
2379
+ export type ZCodeUserInputResponse = z.infer<typeof zcodeUserInputResponseSchema>;
2380
+
2381
+ export const zcodeProviderRuntimeHeadersRequestReasonSchema = z.enum(["model-request"]);
2382
+ export const zcodeProviderRuntimeHeadersRequestParamsSchema = z
2383
+ .object({
2384
+ requestId: nonEmptyString,
2385
+ sessionId: nonEmptyString,
2386
+ turnId: nonEmptyString.optional(),
2387
+ workspace: zcodeWorkspaceRefSchema,
2388
+ modelSelection: modelSelectionSchema,
2389
+ providerId: nonEmptyString,
2390
+ accountAccess: zcodeProviderAccountAccessSchema.optional(),
2391
+ reason: zcodeProviderRuntimeHeadersRequestReasonSchema,
2392
+ })
2393
+ .strict();
2394
+ export type ZCodeProviderRuntimeHeadersRequestParams = z.infer<
2395
+ typeof zcodeProviderRuntimeHeadersRequestParamsSchema
2396
+ >;
2397
+
2398
+ /** 请求取消只作用于同 workspace/session 的这一轮凭据刷新。 */
2399
+ export const zcodeProviderRuntimeHeadersCancelledSchema = z
2400
+ .object({
2401
+ requestId: nonEmptyString,
2402
+ sessionId: nonEmptyString,
2403
+ workspace: zcodeWorkspaceRefSchema,
2404
+ })
2405
+ .strict();
2406
+ export type ZCodeProviderRuntimeHeadersCancelled = z.infer<
2407
+ typeof zcodeProviderRuntimeHeadersCancelledSchema
2408
+ >;
2409
+
2410
+ export const zcodeProviderRuntimeHeadersResponseSchema = z.discriminatedUnion("headersApplied", [
2411
+ z
2412
+ .object({
2413
+ headersApplied: z.literal(true),
2414
+ // 合并重接:成功必须携带当前请求的鉴权材料,不依赖旧 Registry 已被写入。
2415
+ requestAuth: z
2416
+ .object({
2417
+ apiKey: nonEmptyString.optional(),
2418
+ headers: z.record(nonEmptyString, nonEmptyString).optional(),
2419
+ })
2420
+ .strict(),
2421
+ errorMessage: nonEmptyString.optional(),
2422
+ })
2423
+ .strict(),
2424
+ z
2425
+ .object({
2426
+ headersApplied: z.literal(false),
2427
+ errorMessage: nonEmptyString.optional(),
2428
+ })
2429
+ .strict(),
2430
+ ]);
2431
+ export type ZCodeProviderRuntimeHeadersResponse = z.infer<
2432
+ typeof zcodeProviderRuntimeHeadersResponseSchema
2433
+ >;
2434
+
2435
+ // ── 官方 Server MCP 鉴权──
2436
+ // Agent 进程不是用户身份权威:它把 (pluginId, mcpKey, targetOrigin) 报给 host,由 host
2437
+ // 解析当前 Coding Plan 凭证并回传本次请求的身份头。请求侧不含任何秘密。
2438
+ // 与 interaction/requestProviderRuntimeHeaders 同类:Agent 发起、host 自动响应、零 UI。
2439
+ export const zcodeOfficialMcpAuthHeadersRequestParamsSchema = z
2440
+ .object({
2441
+ requestId: nonEmptyString,
2442
+ workspace: zcodeWorkspaceRefSchema,
2443
+ pluginId: nonEmptyString,
2444
+ mcpKey: nonEmptyString,
2445
+ targetOrigin: nonEmptyString,
2446
+ })
2447
+ .strict();
2448
+ export type ZCodeOfficialMcpAuthHeadersRequestParams = z.infer<
2449
+ typeof zcodeOfficialMcpAuthHeadersRequestParamsSchema
2450
+ >;
2451
+
2452
+ /**
2453
+ * 失败原因必须可枚举,避免调用方按文本分流;因此响应不含 errorMessage。
2454
+ *
2455
+ * `official_mcp_origin_untrusted` 是 host 侧二次校验的拒绝原因:`targetOrigin` 不等于当前
2456
+ * ZCode API origin。判定只看 origin,`pluginId` / `mcpKey` 仅用于日志归属。与"未登录/无凭据"
2457
+ * 分开,才能在排查时区分"被拒绝"和"没身份"。
2458
+ */
2459
+ export const zcodeOfficialMcpAuthFailureReasonSchema = z.enum(
2460
+ OFFICIAL_MCP_AUTH_PORT_FAILURE_REASONS,
2461
+ );
2462
+
2463
+ export const zcodeOfficialMcpAuthHeadersResponseSchema = z.discriminatedUnion("ok", [
2464
+ z
2465
+ .object({
2466
+ ok: z.literal(true),
2467
+ headers: z.record(z.string(), z.string()),
2468
+ })
2469
+ .strict(),
2470
+ z
2471
+ .object({
2472
+ ok: z.literal(false),
2473
+ reason: zcodeOfficialMcpAuthFailureReasonSchema,
2474
+ })
2475
+ .strict(),
2476
+ ]);
2477
+ export type ZCodeOfficialMcpAuthHeadersResponse = z.infer<
2478
+ typeof zcodeOfficialMcpAuthHeadersResponseSchema
2479
+ >;
2480
+
2481
+ // ── Plugin management (list + enable/disable) ──
2482
+ // 镜像 @zcode/contracts 的 PluginMetadata, 仅保留 UI 需要的可序列化字段。
2483
+ export const zcodePluginOptionValueSchema = z.union([z.string(), z.number(), z.boolean()]);
2484
+ export type ZCodePluginOptionValue = z.infer<typeof zcodePluginOptionValueSchema>;
2485
+ export const zcodePluginScopeSchema = z.enum(["user", "workspace"]);
2486
+ export type ZCodePluginScope = z.infer<typeof zcodePluginScopeSchema>;
2487
+ export const zcodePluginHookDetailSchema = z
2488
+ .object({
2489
+ event: nonEmptyString,
2490
+ matcher: z.string().optional(),
2491
+ type: z.enum(["command", "process"]),
2492
+ command: nonEmptyString,
2493
+ args: z.array(z.string()).optional(),
2494
+ async: z.boolean().optional(),
2495
+ shell: z.union([z.literal(true), z.string()]).optional(),
2496
+ timeout: z.number().positive().optional(),
2497
+ timeoutMs: z.number().int().positive().optional(),
2498
+ statusMessage: z.string().optional(),
2499
+ sourcePath: z.string(),
2500
+ runnable: z.boolean(),
2501
+ })
2502
+ .strict();
2503
+ export const zcodePluginUserConfigOptionSchema = z
2504
+ .object({
2505
+ default: zcodePluginOptionValueSchema.optional(),
2506
+ description: z.string().optional(),
2507
+ required: z.boolean().optional(),
2508
+ sensitive: z.boolean().optional(),
2509
+ title: z.string().optional(),
2510
+ type: z.enum(["string", "number", "boolean", "directory", "file"]).optional(),
2511
+ })
2512
+ .strict();
2513
+ export type ZCodePluginUserConfigOption = z.infer<typeof zcodePluginUserConfigOptionSchema>;
2514
+
2515
+ // 组件类型与详情弹窗/市场详情共用的分组顺序保持一致:agent / command / skill / hook / mcp。
2516
+ // 注意:这三个 schema 必须定义在 zcodePluginInfoSchema 之前,因为后者(.strict())的 components 字段引用了它们。
2517
+ export const zcodePluginComponentKindSchema = z.enum(["agent", "command", "skill", "hook", "mcp"]);
2518
+ export type ZCodePluginComponentKind = z.infer<typeof zcodePluginComponentKindSchema>;
2519
+
2520
+ export const zcodePluginComponentItemSchema = z
2521
+ .object({
2522
+ name: nonEmptyString,
2523
+ // 描述来自组件 frontmatter(SKILL.md / command / agent)或 manifest;缺失时省略,不伪造。
2524
+ description: z.string().optional(),
2525
+ })
2526
+ .strict();
2527
+ export const zcodePluginComponentGroupSchema = z
2528
+ .object({
2529
+ kind: zcodePluginComponentKindSchema,
2530
+ items: z.array(zcodePluginComponentItemSchema),
2531
+ })
2532
+ .strict();
2533
+ export type ZCodePluginComponentGroup = z.infer<typeof zcodePluginComponentGroupSchema>;
2534
+
2535
+ export const zcodePluginInfoSchema = z
2536
+ .object({
2537
+ id: nonEmptyString,
2538
+ name: nonEmptyString,
2539
+ description: z.string().optional(),
2540
+ version: z.string().optional(),
2541
+ enabled: z.boolean(),
2542
+ source: nonEmptyString,
2543
+ marketplace: nonEmptyString,
2544
+ // manifest(plugin.json)的作者/主页回退字段;商店 listing 缺失时详情页信息区用它兜底。
2545
+ author: z.string().optional(),
2546
+ authorUrl: z.string().optional(),
2547
+ homepage: z.string().optional(),
2548
+ skillCount: z.number().int().nonnegative().optional(),
2549
+ skillRootCount: z.number().int().nonnegative(),
2550
+ commandRootCount: z.number().int().nonnegative(),
2551
+ // 权威组件清单(名称 + 可选描述),由 CLI 对插件根目录枚举得出,与启用态无关。
2552
+ // 详情 UI 直接展示,取代旧的「数量取协议、名称靠 UI 侧 join」脆弱方案。optional 兼容旧 payload。
2553
+ components: z.array(zcodePluginComponentGroupSchema).optional(),
2554
+ declaredMcpServerNames: z.array(z.string()).optional(),
2555
+ hostMcpServerNames: z.array(z.string()).optional(),
2556
+ mcpServerNames: z.array(z.string()),
2557
+ hookDetails: z.array(zcodePluginHookDetailSchema).optional(),
2558
+ rootPath: z.string(),
2559
+ userConfig: z.record(z.string(), zcodePluginUserConfigOptionSchema).optional(),
2560
+ configuredOptions: z.record(z.string(), zcodePluginOptionValueSchema).optional(),
2561
+ // 缺省表示 package 可用;missing 用于保留已声明但目标 Host 尚未物化的配置行。
2562
+ packageStatus: z.literal("missing").optional(),
2563
+ rootSource: zcodePluginScopeSchema.optional(),
2564
+ enabledSource: zcodePluginScopeSchema.optional(),
2565
+ optionSources: z.record(z.string(), zcodePluginScopeSchema).optional(),
2566
+ })
2567
+ .strict();
2568
+ export type ZCodePluginInfo = z.infer<typeof zcodePluginInfoSchema>;
2569
+
2570
+ export const zcodePluginDiagnosticSchema = z
2571
+ .object({
2572
+ code: z.string(),
2573
+ message: z.string(),
2574
+ severity: z.enum(["warning", "error"]).optional(),
2575
+ pluginId: z.string().optional(),
2576
+ })
2577
+ .strict();
2578
+ export type ZCodePluginDiagnostic = z.infer<typeof zcodePluginDiagnosticSchema>;
2579
+
2580
+ export const zcodePluginsListParamsSchema = z
2581
+ .object({
2582
+ workspace: zcodeWorkspaceRefSchema,
2583
+ configScope: zcodePluginScopeSchema.optional(),
2584
+ })
2585
+ .strict();
2586
+ export const zcodePluginsListResultSchema = z
2587
+ .object({
2588
+ plugins: z.array(zcodePluginInfoSchema),
2589
+ diagnostics: z.array(zcodePluginDiagnosticSchema),
2590
+ })
2591
+ .strict();
2592
+ export type ZCodePluginsListResult = z.infer<typeof zcodePluginsListResultSchema>;
2593
+
2594
+ // ── Plugin 对话引用 catalog──
2595
+ // Session-scoped 只读投影:带 sessionId → 该 Session 创建时冻结的身份 catalog;
2596
+ // 不带 → workspace 当前 catalog(新建草稿 Picker)。身份与能力字段保持
2597
+ // identifiers-only,不携带 rootPath/配置等;可选 icon/displayName(I18n)/description(I18n)
2598
+ // 仅供 UI 展示与 Picker 搜索,不参与身份、权限或 runtime reminder。
2599
+ export const zcodePluginReferenceCatalogEntrySchema = z
2600
+ .object({
2601
+ // 仅 referenceCatalogWithCategory 返回;旧入口保持原结构。
2602
+ category: nonEmptyString.optional(),
2603
+ pluginId: nonEmptyString,
2604
+ name: nonEmptyString,
2605
+ marketplace: nonEmptyString,
2606
+ icon: z.string().optional(),
2607
+ // 商店 listing 的 display-only 本地化显示名投影(沿 icon 先例):让 Picker 能按
2608
+ // 中文显示名搜索/展示;locale 解析复用 shared 的 plugin-display-name helper。
2609
+ displayName: z.string().optional(),
2610
+ displayNameI18n: z.record(z.string(), z.string()).optional(),
2611
+ // 仅供 Picker 展示,不进入能力身份或 model-only reminder。
2612
+ description: z.string().optional(),
2613
+ descriptionI18n: z.record(z.string(), z.string()).optional(),
2614
+ enabled: z.boolean(),
2615
+ // 非空 = 与其他 enabled Plugin 共享 manifest name 的 V1 fail closed 冲突:
2616
+ // Picker 禁选并展示原因,runtime 解析按 ambiguous 跳过。
2617
+ conflictingPluginIds: z.array(nonEmptyString),
2618
+ skillQualifiedNames: z.array(nonEmptyString),
2619
+ mcpServerNames: z.array(nonEmptyString),
2620
+ // 旧 Host 不投影该字段时按空数组兼容;只有新 Agent 会把它用于 reminder live 交集。
2621
+ subagentNames: z.array(nonEmptyString).default([]),
2622
+ })
2623
+ .strict();
2624
+ export type ZCodePluginReferenceCatalogEntry = z.infer<
2625
+ typeof zcodePluginReferenceCatalogEntrySchema
2626
+ >;
2627
+
2628
+ export const zcodePluginsReferenceCatalogParamsSchema = z
2629
+ .object({
2630
+ workspace: zcodeWorkspaceRefSchema,
2631
+ // 已有 Session 的 Picker 必须带 sessionId 才能拿到 session-owned catalog;
2632
+ // session 不存在时按协议错误 fail closed,禁止静默回退 workspace authority。
2633
+ sessionId: nonEmptyString.optional(),
2634
+ })
2635
+ .strict();
2636
+ export type ZCodePluginsReferenceCatalogParams = z.infer<
2637
+ typeof zcodePluginsReferenceCatalogParamsSchema
2638
+ >;
2639
+ export const zcodePluginsReferenceCatalogResultSchema = z
2640
+ .object({
2641
+ authority: z.enum(["session", "workspace"]),
2642
+ plugins: z.array(zcodePluginReferenceCatalogEntrySchema),
2643
+ })
2644
+ .strict();
2645
+ export type ZCodePluginsReferenceCatalogResult = z.infer<
2646
+ typeof zcodePluginsReferenceCatalogResultSchema
2647
+ >;
2648
+
2649
+ // ── Skill 对话引用 catalog──
2650
+ // 新草稿读取 workspace 当前目录;已有 Session 读取 AgentRuntime 首次 context
2651
+ // 初始化时冻结的发现结果。该协议只承载 Composer 的只读引用投影,不替代 Settings
2652
+ // 的 Skill 管理接口,也不持久化 runtime 快照。
2653
+ export const zcodeSkillReferenceCatalogEntrySchema = z
2654
+ .object({
2655
+ id: nonEmptyString,
2656
+ name: nonEmptyString,
2657
+ description: z.string(),
2658
+ path: nonEmptyString,
2659
+ scope: z.enum(["workspace", "user", "plugin"]),
2660
+ enabled: z.literal(true),
2661
+ pluginName: nonEmptyString.optional(),
2662
+ })
2663
+ .strict();
2664
+ export type ZCodeSkillReferenceCatalogEntry = z.infer<typeof zcodeSkillReferenceCatalogEntrySchema>;
2665
+
2666
+ export const zcodeSkillsReferenceCatalogParamsSchema = z
2667
+ .object({
2668
+ workspace: zcodeWorkspaceRefSchema,
2669
+ // 带 sessionId 时必须命中该进程内的 resident Session;未知 Session fail closed,
2670
+ // 禁止回退到 workspace 当前目录而把新 Skill 泄漏进旧对话。
2671
+ sessionId: nonEmptyString.optional(),
2672
+ })
2673
+ .strict();
2674
+ export type ZCodeSkillsReferenceCatalogParams = z.infer<
2675
+ typeof zcodeSkillsReferenceCatalogParamsSchema
2676
+ >;
2677
+ export const zcodeSkillsReferenceCatalogResultSchema = z
2678
+ .object({
2679
+ authority: z.enum(["session", "workspace"]),
2680
+ skills: z.array(zcodeSkillReferenceCatalogEntrySchema),
2681
+ })
2682
+ .strict();
2683
+ export type ZCodeSkillsReferenceCatalogResult = z.infer<
2684
+ typeof zcodeSkillsReferenceCatalogResultSchema
2685
+ >;
2686
+
2687
+ // ── 已保存工作流的 GUI 中枢──
2688
+ // workspace 级、无会话的五个方法,照 skills/referenceCatalog 的先例:每次调用现扫
2689
+ // `<cwd>/.zcode/workflows/`(挂载时快照会漏掉手改的文件)。形状与 @zcode/contracts 的
2690
+ // saved-workflow.ts 逐字对齐——依赖方向是 contracts → shared,所以这里结构化地再声明一遍,
2691
+ // 而不是 import;两边的 strict 形状由 bootstrap 侧的协议测试互相钉住。
2692
+ export const zcodeSavedWorkflowArgTypeSchema = z.enum(["string", "number", "boolean", "json"]);
2693
+ export type ZCodeSavedWorkflowArgType = z.infer<typeof zcodeSavedWorkflowArgTypeSchema>;
2694
+ export const zcodeSavedWorkflowArgDeclarationSchema = z
2695
+ .object({
2696
+ type: zcodeSavedWorkflowArgTypeSchema,
2697
+ description: z.string().optional(),
2698
+ required: z.boolean().optional(),
2699
+ default: z.unknown().optional(),
2700
+ })
2701
+ .strict();
2702
+ export type ZCodeSavedWorkflowArgDeclaration = z.infer<
2703
+ typeof zcodeSavedWorkflowArgDeclarationSchema
2704
+ >;
2705
+ export const zcodeSavedWorkflowArgsDeclarationSchema = z.record(
2706
+ z.string(),
2707
+ zcodeSavedWorkflowArgDeclarationSchema,
2708
+ );
2709
+ export type ZCodeSavedWorkflowArgsDeclaration = z.infer<
2710
+ typeof zcodeSavedWorkflowArgsDeclarationSchema
2711
+ >;
2712
+ export const zcodeSavedWorkflowMetaSchema = z
2713
+ .object({
2714
+ description: nonEmptyString,
2715
+ whenToUse: nonEmptyString.optional(),
2716
+ args: zcodeSavedWorkflowArgsDeclarationSchema.optional(),
2717
+ })
2718
+ .strict();
2719
+ export type ZCodeSavedWorkflowMeta = z.infer<typeof zcodeSavedWorkflowMetaSchema>;
2720
+ // 作用域两档:项目档落 `<cwd>/.zcode/workflows/`、全局档落 agent 机器的 `~/.zcode/workflows/`。作用域由文件所在目录推得,frontmatter 不存 scope。
2721
+ export const zcodeSavedWorkflowScopeSchema = z.enum(["project", "global"]);
2722
+ export type ZCodeSavedWorkflowScope = z.infer<typeof zcodeSavedWorkflowScopeSchema>;
2723
+ export const zcodeSavedWorkflowEntrySchema = z
2724
+ .object({
2725
+ name: nonEmptyString,
2726
+ description: z.string(),
2727
+ whenToUse: z.string().optional(),
2728
+ args: zcodeSavedWorkflowArgsDeclarationSchema.optional(),
2729
+ scope: zcodeSavedWorkflowScopeSchema,
2730
+ path: nonEmptyString,
2731
+ })
2732
+ .strict();
2733
+ export type ZCodeSavedWorkflowEntry = z.infer<typeof zcodeSavedWorkflowEntrySchema>;
2734
+ export const zcodeSavedWorkflowInvalidEntrySchema = z
2735
+ .object({ path: nonEmptyString, reason: nonEmptyString })
2736
+ .strict();
2737
+ export type ZCodeSavedWorkflowInvalidEntry = z.infer<typeof zcodeSavedWorkflowInvalidEntrySchema>;
2738
+ /** 名字非法 / 未找到 / frontmatter 坏 / 读错——与 core store 的 resolve 失败四态逐字对应。 */
2739
+ export const zcodeSavedWorkflowFailureReasonSchema = z.enum([
2740
+ "invalid_name",
2741
+ "not_found",
2742
+ "parse_error",
2743
+ "read_error",
2744
+ ]);
2745
+ export type ZCodeSavedWorkflowFailureReason = z.infer<typeof zcodeSavedWorkflowFailureReasonSchema>;
2746
+ const zcodeSavedWorkflowFailureSchema = z
2747
+ .object({
2748
+ ok: z.literal(false),
2749
+ reason: zcodeSavedWorkflowFailureReasonSchema,
2750
+ detail: z.string().optional(),
2751
+ })
2752
+ .strict();
2753
+
2754
+ export const zcodeWorkflowsListParamsSchema = z
2755
+ .object({
2756
+ workspace: zcodeWorkspaceRefSchema,
2757
+ // 缺省即 `project`(本项目档)。给 `global` 时改扫本机 `~/.zcode/workflows/`;此时 `workspace`
2758
+ // 仍必填,但只是**载体运行时**——协议处理器对全局档不读它的路径。
2759
+ scope: zcodeSavedWorkflowScopeSchema.optional(),
2760
+ })
2761
+ .strict();
2762
+ export type ZCodeWorkflowsListParams = z.infer<typeof zcodeWorkflowsListParamsSchema>;
2763
+ export const zcodeWorkflowsListResultSchema = z
2764
+ .object({
2765
+ workflows: z.array(zcodeSavedWorkflowEntrySchema),
2766
+ invalid: z.array(zcodeSavedWorkflowInvalidEntrySchema),
2767
+ // 扫过的目录(本地绝对路径),即使目录还不存在也回:GUI 的文件监听靠它 watch。
2768
+ dir: nonEmptyString,
2769
+ })
2770
+ .strict();
2771
+ export type ZCodeWorkflowsListResult = z.infer<typeof zcodeWorkflowsListResultSchema>;
2772
+
2773
+ export const zcodeWorkflowsGetParamsSchema = z
2774
+ .object({
2775
+ workspace: zcodeWorkspaceRefSchema,
2776
+ name: nonEmptyString,
2777
+ // 缺省 `project`;`global` 时只查本机全局根。`workspace` 语义同 list(全局档只当载体)。
2778
+ scope: zcodeSavedWorkflowScopeSchema.optional(),
2779
+ })
2780
+ .strict();
2781
+ export type ZCodeWorkflowsGetParams = z.infer<typeof zcodeWorkflowsGetParamsSchema>;
2782
+ export const zcodeWorkflowsGetResultSchema = z.union([
2783
+ z
2784
+ .object({
2785
+ ok: z.literal(true),
2786
+ name: nonEmptyString,
2787
+ path: nonEmptyString,
2788
+ scope: zcodeSavedWorkflowScopeSchema,
2789
+ meta: zcodeSavedWorkflowMetaSchema,
2790
+ /** 脚本本体(frontmatter 之后逐字节),即被类型检查与执行的那一份。 */
2791
+ script: z.string(),
2792
+ })
2793
+ .strict(),
2794
+ zcodeSavedWorkflowFailureSchema,
2795
+ ]);
2796
+ export type ZCodeWorkflowsGetResult = z.infer<typeof zcodeWorkflowsGetResultSchema>;
2797
+
2798
+ export const zcodeWorkflowsUpdateMetaParamsSchema = z
2799
+ .object({
2800
+ workspace: zcodeWorkspaceRefSchema,
2801
+ name: nonEmptyString,
2802
+ meta: zcodeSavedWorkflowMetaSchema,
2803
+ // 缺省 `project`;`global` 时只写本机全局根那一份。`workspace` 语义同 list。
2804
+ scope: zcodeSavedWorkflowScopeSchema.optional(),
2805
+ })
2806
+ .strict();
2807
+ export type ZCodeWorkflowsUpdateMetaParams = z.infer<typeof zcodeWorkflowsUpdateMetaParamsSchema>;
2808
+ export const zcodeWorkflowsUpdateMetaResultSchema = z.union([
2809
+ z.object({ ok: z.literal(true), path: nonEmptyString }).strict(),
2810
+ zcodeSavedWorkflowFailureSchema,
2811
+ ]);
2812
+ export type ZCodeWorkflowsUpdateMetaResult = z.infer<typeof zcodeWorkflowsUpdateMetaResultSchema>;
2813
+
2814
+ export const zcodeWorkflowsDeleteParamsSchema = z
2815
+ .object({
2816
+ workspace: zcodeWorkspaceRefSchema,
2817
+ name: nonEmptyString,
2818
+ // 缺省 `project`;`global` 时按 scope 选根删除(不再写死 roots[0])。`workspace` 语义同 list。
2819
+ scope: zcodeSavedWorkflowScopeSchema.optional(),
2820
+ })
2821
+ .strict();
2822
+ export type ZCodeWorkflowsDeleteParams = z.infer<typeof zcodeWorkflowsDeleteParamsSchema>;
2823
+ export const zcodeWorkflowsDeleteResultSchema = z.union([
2824
+ z.object({ ok: z.literal(true), path: nonEmptyString }).strict(),
2825
+ zcodeSavedWorkflowFailureSchema,
2826
+ ]);
2827
+ export type ZCodeWorkflowsDeleteResult = z.infer<typeof zcodeWorkflowsDeleteResultSchema>;
2828
+
2829
+ export const ZCODE_WORKFLOWS_RUNS_MAX_LIMIT = 50;
2830
+ export const zcodeWorkflowsRunsParamsSchema = z
2831
+ .object({
2832
+ workspace: zcodeWorkspaceRefSchema,
2833
+ /** 只要这个名字的 run(`dwf_run.name` 字面等值);缺省即本项目全部 run。 */
2834
+ name: nonEmptyString.optional(),
2835
+ limit: z.number().int().min(1).max(ZCODE_WORKFLOWS_RUNS_MAX_LIMIT),
2836
+ // 缺省 `project`:只查 `dwf_run.cwd === workspacePath` 的 run。`global` 时**不**按 cwd 过滤,
2837
+ // 跨所有项目取该名字的运行历史(全局工作流在任何项目里跑,历史因此跨 cwd);结果行带 `cwd`
2838
+ // 供 GUI 标项目。`workspace` 语义同 list(全局档只当载体)。
2839
+ scope: zcodeSavedWorkflowScopeSchema.optional(),
2840
+ })
2841
+ .strict();
2842
+ export type ZCodeWorkflowsRunsParams = z.infer<typeof zcodeWorkflowsRunsParamsSchema>;
2843
+ // 三终态词汇:errored = 脚本之错,stopped = 被停下(可恢复)。
2844
+ export const zcodeSavedWorkflowRunStatusSchema = z.enum([
2845
+ "pending",
2846
+ "running",
2847
+ "completed",
2848
+ "errored",
2849
+ "stopped",
2850
+ ]);
2851
+ export type ZCodeSavedWorkflowRunStatus = z.infer<typeof zcodeSavedWorkflowRunStatusSchema>;
2852
+ export const zcodeSavedWorkflowRunStopReasonSchema = z.enum([
2853
+ "user",
2854
+ "model",
2855
+ "provider",
2856
+ "interrupted",
2857
+ "superseded",
2858
+ ]);
2859
+ export const zcodeSavedWorkflowRunSchema = z
2860
+ .object({
2861
+ runId: nonEmptyString,
2862
+ name: z.string().optional(),
2863
+ status: zcodeSavedWorkflowRunStatusSchema,
2864
+ // `status === "stopped"` 才在场。
2865
+ stopReason: zcodeSavedWorkflowRunStopReasonSchema.optional(),
2866
+ createdAt: z.number(),
2867
+ updatedAt: z.number(),
2868
+ spentTokens: z.number(),
2869
+ /** 发起它的会话与 CreateWorkflow 工具调用:有这两个才能从中枢打开实例详情。老行可缺。 */
2870
+ parentSessionId: z.string().optional(),
2871
+ toolCallId: z.string().optional(),
2872
+ args: z.record(z.string(), z.unknown()).optional(),
2873
+ // 实际运行的项目目录(`dwf_run.cwd`)。全局档的 `workflows/runs` 跨 cwd 查询,GUI 用它给
2874
+ // 每行标项目;项目档变体里它恒等于 workspacePath,GUI 可忽略。老行可缺。
2875
+ cwd: z.string().optional(),
2876
+ // 这次运行发布的**用户面产物**:中枢的运行历史行在
2877
+ // 状态词之后画一串 kind chips,详情页头部的「最近产物」条取最近一次 completed run 的这一份。
2878
+ // ⚠ 术语:这里的 artifact 是脚本经 `artifact.*` 发布给用户看的产出,不是脚本的顶层返回值。
2879
+ // 只带 chip 画得下的字段(≤ 8 件,取最新版的元数据);字节与条目经 v4 查询按需读。
2880
+ // optional,照上面 `cwd` 的先例:老 CLI 不发,少一个键是退化不是错误。
2881
+ artifacts: z
2882
+ .array(
2883
+ z
2884
+ .object({
2885
+ id: nonEmptyString,
2886
+ kind: z.enum(["file", "markdown", "chart", "table", "metrics", "board"]),
2887
+ title: z.string().optional(),
2888
+ version: z.number(),
2889
+ contentType: z.string().optional(),
2890
+ })
2891
+ .strict(),
2892
+ )
2893
+ .max(8)
2894
+ .optional(),
2895
+ })
2896
+ .strict();
2897
+ export type ZCodeSavedWorkflowRun = z.infer<typeof zcodeSavedWorkflowRunSchema>;
2898
+ export const zcodeWorkflowsRunsResultSchema = z
2899
+ .object({
2900
+ runs: z.array(zcodeSavedWorkflowRunSchema),
2901
+ /** 为真时才在场:还有更多 run 没进这一页(多取一条判定,不是 length === limit)。 */
2902
+ truncated: z.literal(true).optional(),
2903
+ })
2904
+ .strict();
2905
+ export type ZCodeWorkflowsRunsResult = z.infer<typeof zcodeWorkflowsRunsResultSchema>;
2906
+
2907
+ // workflows/move:把本机全局根的同名文件搬到 `workspace` 项目根。**只此一向**:项目→全局不是搬文件而是模型的概括(「提升为
2908
+ // 全局」在该项目开新会话、经 SaveWorkflow 另存),所以没有 `to` 参数。同机同用户,rename 优先、EXDEV
2909
+ // 回落 copy+unlink;逐字节搬,不改内容(frontmatter 不存 scope);`move` 不覆盖——目标已存在即拒绝
2910
+ // (覆盖是 SaveWorkflow 经确认窗才有的动作,不变式 7)。`workspace` 既是载体运行时也是目标项目。
2911
+ export const zcodeWorkflowsMoveParamsSchema = z
2912
+ .object({
2913
+ workspace: zcodeWorkspaceRefSchema,
2914
+ name: nonEmptyString,
2915
+ })
2916
+ .strict();
2917
+ export type ZCodeWorkflowsMoveParams = z.infer<typeof zcodeWorkflowsMoveParamsSchema>;
2918
+ export const zcodeWorkflowsMoveResultSchema = z.union([
2919
+ z
2920
+ .object({
2921
+ ok: z.literal(true),
2922
+ /** 源落点路径(全局根,搬走前)。 */
2923
+ from: nonEmptyString,
2924
+ /** 目标落点路径(项目根,搬到处)。 */
2925
+ to: nonEmptyString,
2926
+ })
2927
+ .strict(),
2928
+ z
2929
+ .object({
2930
+ ok: z.literal(false),
2931
+ // target_exists:目标档已有同名(move 不覆盖);not_found:源档没有这个名字;
2932
+ // read_error / write_error:搬运时的 I/O 失败;invalid_name:名字先验没过。
2933
+ reason: z.enum(["invalid_name", "not_found", "target_exists", "read_error", "write_error"]),
2934
+ path: z.string().optional(),
2935
+ detail: z.string().optional(),
2936
+ })
2937
+ .strict(),
2938
+ ]);
2939
+ export type ZCodeWorkflowsMoveResult = z.infer<typeof zcodeWorkflowsMoveResultSchema>;
2940
+
2941
+ // 推荐 Prompt 的可信插件解析:UI 不拆解 stableId,也不从旧目录快照推断可安装性。
2942
+ export const zcodePluginSuggestedReferenceStatusSchema = z.enum([
2943
+ "ready",
2944
+ "disabled",
2945
+ "missing",
2946
+ "conflict",
2947
+ "unavailable",
2948
+ ]);
2949
+ export type ZCodePluginSuggestedReferenceStatus = z.infer<
2950
+ typeof zcodePluginSuggestedReferenceStatusSchema
2951
+ >;
2952
+ export const zcodePluginOperationStateSchema = z.enum([
2953
+ "checking",
2954
+ "refreshing",
2955
+ "installing",
2956
+ "enabling",
2957
+ "cancelling",
2958
+ "cancelled",
2959
+ "complete",
2960
+ "failed",
2961
+ ]);
2962
+ export type ZCodePluginOperationState = z.infer<typeof zcodePluginOperationStateSchema>;
2963
+ export const zcodePluginOperationProgressNotificationSchema = z
2964
+ .object({
2965
+ operationId: nonEmptyString,
2966
+ state: z.literal("refreshing"),
2967
+ })
2968
+ .strict();
2969
+ export type ZCodePluginOperationProgressNotification = z.infer<
2970
+ typeof zcodePluginOperationProgressNotificationSchema
2971
+ >;
2972
+ export const zcodePluginsResolveSuggestedReferenceParamsSchema = z
2973
+ .object({
2974
+ workspace: zcodeWorkspaceRefSchema,
2975
+ stableId: nonEmptyString,
2976
+ operationId: nonEmptyString,
2977
+ clientMode: zcodeDeliveryKindSchema,
2978
+ deliveryKind: zcodeDeliveryKindSchema,
2979
+ })
2980
+ .strict();
2981
+ export type ZCodePluginsResolveSuggestedReferenceParams = z.infer<
2982
+ typeof zcodePluginsResolveSuggestedReferenceParamsSchema
2983
+ >;
2984
+ export const zcodePluginsSetEnabledParamsSchema = z
2985
+ .object({
2986
+ workspace: zcodeWorkspaceRefSchema,
2987
+ pluginId: nonEmptyString,
2988
+ enabled: z.boolean(),
2989
+ operationId: nonEmptyString.optional(),
2990
+ scope: zcodePluginScopeSchema.optional(),
2991
+ })
2992
+ .strict();
2993
+ export const zcodePluginsSetEnabledResultSchema = z
2994
+ .object({
2995
+ plugin: zcodePluginInfoSchema,
2996
+ enabled: z.boolean(),
2997
+ })
2998
+ .strict();
2999
+ export type ZCodePluginsSetEnabledResult = z.infer<typeof zcodePluginsSetEnabledResultSchema>;
3000
+
3001
+ // 商店信息(Store Listing):目录条目携带的展示性元数据(显示名/icon/分类/作者/链接/hero/
3002
+ // 示例提示词),全部可选,UI 缺失时按降级矩阵处理(字母头像/隐藏区块/省略信息行)。
3003
+ // i18n 采用 `<字段>I18n` map,locale 解析复用 shared 的 plugin-display-name helper。
3004
+ export const zcodePluginStoreListingSchema = z
3005
+ .object({
3006
+ displayName: z.string().optional(),
3007
+ displayNameI18n: z.record(z.string(), z.string()).optional(),
3008
+ descriptionI18n: z.record(z.string(), z.string()).optional(),
3009
+ icon: z.string().optional(),
3010
+ category: z.string().optional(),
3011
+ author: z.string().optional(),
3012
+ authorUrl: z.string().optional(),
3013
+ homepage: z.string().optional(),
3014
+ privacyPolicy: z.string().optional(),
3015
+ termsOfService: z.string().optional(),
3016
+ heroImage: z.string().optional(),
3017
+ examplePrompts: z.array(z.string()).optional(),
3018
+ examplePromptsI18n: z.record(z.string(), z.array(z.string())).optional(),
3019
+ /**
3020
+ * 需要付费套餐才好用的插件:市场目录条目声明 `requiresPaidPlan: true`,
3021
+ * UI 在标题右侧展示提示图标。描述的是「使用条件」而非「插件是收费商品」——
3022
+ * 不参与安装门禁与计费,命名也不绑定具体套餐商品名。
3023
+ */
3024
+ requiresPaidPlan: z.boolean().optional(),
3025
+ })
3026
+ .strict();
3027
+ export type ZCodePluginStoreListing = z.infer<typeof zcodePluginStoreListingSchema>;
3028
+
3029
+ export const zcodePluginsResolveSuggestedReferenceResultSchema = z
3030
+ .object({
3031
+ stableId: nonEmptyString,
3032
+ status: zcodePluginSuggestedReferenceStatusSchema,
3033
+ marketplace: nonEmptyString.optional(),
3034
+ pluginName: nonEmptyString.optional(),
3035
+ sourceTrust: z.literal("official").optional(),
3036
+ // 官方 Marketplace listing 的可选展示投影;不参与身份、安装或权限判断。
3037
+ icon: z.string().optional(),
3038
+ listing: zcodePluginStoreListingSchema.optional(),
3039
+ diagnostics: z.array(zcodePluginDiagnosticSchema),
3040
+ })
3041
+ .strict()
3042
+ .superRefine((value, context) => {
3043
+ if (value.status !== "ready" && value.status !== "disabled" && value.status !== "missing") {
3044
+ return;
3045
+ }
3046
+ if (!value.marketplace || !value.pluginName || value.sourceTrust !== "official") {
3047
+ context.addIssue({
3048
+ code: "custom",
3049
+ message: "actionable suggested Plugin results require trusted install identity",
3050
+ });
3051
+ }
3052
+ });
3053
+ export type ZCodePluginsResolveSuggestedReferenceResult = z.infer<
3054
+ typeof zcodePluginsResolveSuggestedReferenceResultSchema
3055
+ >;
3056
+
3057
+ export const zcodePluginMarketplaceSummarySchema = z
3058
+ .object({
3059
+ id: nonEmptyString,
3060
+ name: nonEmptyString,
3061
+ source: jsonObjectSchema,
3062
+ description: z.string().optional(),
3063
+ lastUpdated: z.string().optional(),
3064
+ pluginCount: z.number().int().nonnegative(),
3065
+ isOfficial: z.boolean().optional(),
3066
+ // 目录顶层 featured 策展名单(商店「公开」分段 Featured 区)。
3067
+ featured: z.array(z.string()).optional(),
3068
+ refreshFailure: z
3069
+ .object({
3070
+ code: z.string(),
3071
+ failedAt: z.string(),
3072
+ message: z.string(),
3073
+ })
3074
+ .strict()
3075
+ .optional(),
3076
+ })
3077
+ .strict();
3078
+ export type ZCodePluginMarketplaceSummary = z.infer<typeof zcodePluginMarketplaceSummarySchema>;
3079
+
3080
+ export const zcodeAvailablePluginSummarySchema = z
3081
+ .object({
3082
+ id: nonEmptyString,
3083
+ name: nonEmptyString,
3084
+ marketplace: nonEmptyString,
3085
+ description: z.string().optional(),
3086
+ version: z.string().optional(),
3087
+ installed: z.boolean(),
3088
+ componentTypes: z.array(z.string()).optional(),
3089
+ listing: zcodePluginStoreListingSchema.optional(),
3090
+ })
3091
+ .strict();
3092
+ export type ZCodeAvailablePluginSummary = z.infer<typeof zcodeAvailablePluginSummarySchema>;
3093
+
3094
+ export const zcodeInstalledPluginSummarySchema = z
3095
+ .object({
3096
+ id: nonEmptyString,
3097
+ name: nonEmptyString,
3098
+ marketplace: nonEmptyString,
3099
+ description: z.string().optional(),
3100
+ version: z.string().optional(),
3101
+ enabled: z.boolean(),
3102
+ scope: zcodePluginScopeSchema,
3103
+ installPath: z.string().optional(),
3104
+ installedAt: z.string().optional(),
3105
+ componentTypes: z.array(z.string()).optional(),
3106
+ hookDetails: z.array(zcodePluginHookDetailSchema).optional(),
3107
+ updateStatus: z.enum(["none", "update-available", "version-changed"]).optional(),
3108
+ latestVersion: z.string().optional(),
3109
+ listing: zcodePluginStoreListingSchema.optional(),
3110
+ })
3111
+ .strict();
3112
+ export type ZCodeInstalledPluginSummary = z.infer<typeof zcodeInstalledPluginSummarySchema>;
3113
+
3114
+ export const zcodePluginsOverviewParamsSchema = z
3115
+ .object({
3116
+ workspace: zcodeWorkspaceRefSchema,
3117
+ configScope: zcodePluginScopeSchema.optional(),
3118
+ })
3119
+ .strict();
3120
+ export const zcodePluginsOverviewResultSchema = z
3121
+ .object({
3122
+ marketplaces: z.array(zcodePluginMarketplaceSummarySchema),
3123
+ availablePlugins: z.array(zcodeAvailablePluginSummarySchema),
3124
+ installedPlugins: z.array(zcodeInstalledPluginSummarySchema),
3125
+ restorableBuiltins: z.array(zcodeAvailablePluginSummarySchema),
3126
+ diagnostics: z.array(zcodePluginDiagnosticSchema),
3127
+ capability: z
3128
+ .object({
3129
+ supported: z.boolean(),
3130
+ reason: z.string().optional(),
3131
+ })
3132
+ .strict(),
3133
+ })
3134
+ .strict();
3135
+ export type ZCodePluginsOverviewResult = z.infer<typeof zcodePluginsOverviewResultSchema>;
3136
+
3137
+ export const zcodePluginsMarketplaceAddParamsSchema = z
3138
+ .object({
3139
+ workspace: zcodeWorkspaceRefSchema,
3140
+ source: nonEmptyString,
3141
+ dryRun: z.boolean().optional(),
3142
+ operationId: nonEmptyString.optional(),
3143
+ })
3144
+ .strict();
3145
+ export const zcodePluginsMarketplaceRemoveParamsSchema = z
3146
+ .object({
3147
+ workspace: zcodeWorkspaceRefSchema,
3148
+ marketplace: nonEmptyString,
3149
+ })
3150
+ .strict();
3151
+ export const zcodePluginsMarketplaceUpdateParamsSchema = z
3152
+ .object({
3153
+ workspace: zcodeWorkspaceRefSchema,
3154
+ marketplace: nonEmptyString.optional(),
3155
+ operationId: nonEmptyString.optional(),
3156
+ })
3157
+ .strict();
3158
+ export const zcodePluginsMarketplaceMutationResultSchema = z
3159
+ .object({
3160
+ marketplace: zcodePluginMarketplaceSummarySchema.optional(),
3161
+ marketplaces: z.array(zcodePluginMarketplaceSummarySchema).optional(),
3162
+ diagnostics: z.array(zcodePluginDiagnosticSchema).optional(),
3163
+ })
3164
+ .strict();
3165
+ export type ZCodePluginsMarketplaceMutationResult = z.infer<
3166
+ typeof zcodePluginsMarketplaceMutationResultSchema
3167
+ >;
3168
+
3169
+ export const zcodePluginsInstallParamsSchema = z
3170
+ .object({
3171
+ workspace: zcodeWorkspaceRefSchema,
3172
+ pluginName: nonEmptyString,
3173
+ marketplace: nonEmptyString,
3174
+ scope: zcodePluginScopeSchema.optional(),
3175
+ dryRun: z.boolean().optional(),
3176
+ operationId: nonEmptyString.optional(),
3177
+ })
3178
+ .strict();
3179
+ export const zcodePluginsCancelOperationParamsSchema = z
3180
+ .object({
3181
+ operationId: nonEmptyString,
3182
+ })
3183
+ .strict();
3184
+ export type ZCodePluginsCancelOperationParams = z.infer<
3185
+ typeof zcodePluginsCancelOperationParamsSchema
3186
+ >;
3187
+
3188
+ export const zcodePluginsCancelOperationResultSchema = z
3189
+ .object({
3190
+ operationId: nonEmptyString,
3191
+ cancelled: z.boolean(),
3192
+ })
3193
+ .strict();
3194
+ export type ZCodePluginsCancelOperationResult = z.infer<
3195
+ typeof zcodePluginsCancelOperationResultSchema
3196
+ >;
3197
+ export const zcodePluginsUninstallParamsSchema = z
3198
+ .object({
3199
+ workspace: zcodeWorkspaceRefSchema,
3200
+ pluginId: nonEmptyString.optional(),
3201
+ pluginName: nonEmptyString.optional(),
3202
+ marketplace: nonEmptyString.optional(),
3203
+ removeCache: z.boolean().optional(),
3204
+ })
3205
+ .strict();
3206
+ export const zcodePluginsInstallResultSchema = z
3207
+ .object({
3208
+ installedPlugins: z.array(zcodeInstalledPluginSummarySchema),
3209
+ dependencyClosure: z.array(z.string()),
3210
+ diagnostics: z.array(zcodePluginDiagnosticSchema),
3211
+ })
3212
+ .strict();
3213
+ export type ZCodePluginsInstallResult = z.infer<typeof zcodePluginsInstallResultSchema>;
3214
+
3215
+ export const zcodePluginsUninstallResultSchema = z
3216
+ .object({
3217
+ removedPlugin: zcodeInstalledPluginSummarySchema.optional(),
3218
+ diagnostics: z.array(zcodePluginDiagnosticSchema),
3219
+ })
3220
+ .strict();
3221
+ export type ZCodePluginsUninstallResult = z.infer<typeof zcodePluginsUninstallResultSchema>;
3222
+
3223
+ export const zcodePluginsUpdateParamsSchema = z
3224
+ .object({
3225
+ workspace: zcodeWorkspaceRefSchema,
3226
+ pluginId: nonEmptyString.optional(),
3227
+ marketplace: nonEmptyString.optional(),
3228
+ })
3229
+ .strict();
3230
+ export const zcodePluginsRestoreBuiltinParamsSchema = z
3231
+ .object({
3232
+ workspace: zcodeWorkspaceRefSchema,
3233
+ pluginId: nonEmptyString,
3234
+ })
3235
+ .strict();
3236
+ export const zcodePluginsRestoreBuiltinResultSchema = z
3237
+ .object({
3238
+ pluginId: nonEmptyString,
3239
+ diagnostics: z.array(zcodePluginDiagnosticSchema),
3240
+ })
3241
+ .strict();
3242
+ export type ZCodePluginsRestoreBuiltinResult = z.infer<
3243
+ typeof zcodePluginsRestoreBuiltinResultSchema
3244
+ >;
3245
+
3246
+ export const zcodePluginsConfigureParamsSchema = z
3247
+ .object({
3248
+ workspace: zcodeWorkspaceRefSchema,
3249
+ pluginId: nonEmptyString,
3250
+ options: jsonObjectSchema,
3251
+ clearOptionKeys: z.array(nonEmptyString).optional(),
3252
+ scope: zcodePluginScopeSchema.optional(),
3253
+ dryRun: z.boolean().optional(),
3254
+ })
3255
+ .strict();
3256
+ export const zcodePluginsConfigureResultSchema = z
3257
+ .object({
3258
+ pluginId: nonEmptyString,
3259
+ diagnostics: z.array(zcodePluginDiagnosticSchema),
3260
+ })
3261
+ .strict();
3262
+ export type ZCodePluginsConfigureResult = z.infer<typeof zcodePluginsConfigureResultSchema>;
3263
+
3264
+ export const zcodePluginsResetConfigParamsSchema = z
3265
+ .object({
3266
+ workspace: zcodeWorkspaceRefSchema,
3267
+ pluginId: nonEmptyString,
3268
+ scope: zcodePluginScopeSchema.optional(),
3269
+ })
3270
+ .strict();
3271
+ export type ZCodePluginsResetConfigParams = z.infer<typeof zcodePluginsResetConfigParamsSchema>;
3272
+
3273
+ export const zcodePluginsValidateParamsSchema = z
3274
+ .object({
3275
+ workspace: zcodeWorkspaceRefSchema,
3276
+ pluginName: nonEmptyString.optional(),
3277
+ marketplace: nonEmptyString.optional(),
3278
+ source: nonEmptyString.optional(),
3279
+ })
3280
+ .strict();
3281
+ export const zcodePluginsValidateResultSchema = z
3282
+ .object({
3283
+ ok: z.boolean(),
3284
+ diagnostics: z.array(zcodePluginDiagnosticSchema),
3285
+ compatibility: z
3286
+ .object({
3287
+ runnable: z.array(z.string()),
3288
+ diagnosticOnly: z.array(z.string()),
3289
+ unsupported: z.array(z.string()),
3290
+ })
3291
+ .strict(),
3292
+ })
3293
+ .strict();
3294
+ export type ZCodePluginsValidateResult = z.infer<typeof zcodePluginsValidateResultSchema>;
3295
+
3296
+ // plugins/describe:按需枚举单个插件的组件「名称 + 描述」。
3297
+ // 已安装插件读本地缓存目录;未安装候选按需解析/临时 clone 源后枚举再清理。
3298
+ export const zcodePluginsDescribeParamsSchema = z
3299
+ .object({
3300
+ workspace: zcodeWorkspaceRefSchema,
3301
+ pluginName: nonEmptyString,
3302
+ marketplace: nonEmptyString,
3303
+ })
3304
+ .strict();
3305
+ export const zcodePluginsDescribeResultSchema = z
3306
+ .object({
3307
+ components: z.array(zcodePluginComponentGroupSchema),
3308
+ diagnostics: z.array(zcodePluginDiagnosticSchema).optional(),
3309
+ // 插件包内 plugin.json 的展示性回退字段;未安装候选详情页信息区在商店 listing 缺失时兜底。
3310
+ metadata: z
3311
+ .object({
3312
+ author: z.string().optional(),
3313
+ authorUrl: z.string().optional(),
3314
+ homepage: z.string().optional(),
3315
+ version: z.string().optional(),
3316
+ })
3317
+ .strict()
3318
+ .optional(),
3319
+ })
3320
+ .strict();
3321
+ export type ZCodePluginsDescribeResult = z.infer<typeof zcodePluginsDescribeResultSchema>;
3322
+
3323
+ export const zcodeAutomationScheduleRuleSchema = z
3324
+ .object({
3325
+ unit: z.enum(["minute", "hourly", "daily", "weekly", "monthly", "yearly"]),
3326
+ interval: z.number().int().positive(),
3327
+ hour: z.number().int().min(0).max(23),
3328
+ minute: z.number().int().min(0).max(59),
3329
+ anchorAt: z.number().int(),
3330
+ weekdays: z.array(z.number().int().min(0).max(6)).optional(),
3331
+ monthDays: z.array(z.number().int().min(1).max(31)).optional(),
3332
+ /** yearly 用:1-12 人类月份。缺省回退 anchorAt 的月份(兼容未写该字段的旧记录)。 */
3333
+ months: z.array(z.number().int().min(1).max(12)).optional(),
3334
+ monthlyMode: z.enum(["date", "weekday"]).optional(),
3335
+ })
3336
+ .strict();
3337
+ export type ZCodeAutomationScheduleRuleProtocol = z.infer<typeof zcodeAutomationScheduleRuleSchema>;
3338
+
3339
+ /** 会话侧长间隔周期 carrier 的 unit 枚举(与 scheduleRule.unit 同集)。 */
3340
+ export const zcodeAutomationIntervalUnitSchema = z.enum([
3341
+ "minute",
3342
+ "hourly",
3343
+ "daily",
3344
+ "weekly",
3345
+ "monthly",
3346
+ "yearly",
3347
+ ]);
3348
+
3349
+ export const zcodeAutomationProtocolSchema = z
3350
+ .object({
3351
+ automationId: nonEmptyString,
3352
+ title: z.string(),
3353
+ cronExpr: nonEmptyString,
3354
+ prompt: nonEmptyString,
3355
+ modelSelection: modelSelectionSchema.optional(),
3356
+ mode: zcodeTaskModeSchema.optional(),
3357
+ targetTaskId: nonEmptyString.optional(),
3358
+ enabled: z.boolean(),
3359
+ lifecycleStatus: z.enum(["active", "completed", "failed", "paused"]),
3360
+ nextRunAt: timestampMsSchema.optional(),
3361
+ lastRunAt: timestampMsSchema.optional(),
3362
+ runCount: z.number().int().nonnegative(),
3363
+ recurring: z.boolean(),
3364
+ maxRuns: z.number().int().positive().optional(),
3365
+ // 自定义重复规则;缺省时调度回退到解析 cronExpr。会话卡片必须读到本字段才能展示
3366
+ // cron 无法表达的真实间隔(如每50小时、每40天,兼容 cronExpr 只是 0 * * * *)。
3367
+ scheduleRule: zcodeAutomationScheduleRuleSchema.optional(),
3368
+ })
3369
+ .strict();
3370
+ export type ZCodeAutomationProtocol = z.infer<typeof zcodeAutomationProtocolSchema>;
3371
+
3372
+ export const zcodeAutomationCreateParamsSchema = z
3373
+ .object({
3374
+ title: z.string().optional(),
3375
+ cronExpr: nonEmptyString,
3376
+ relativeDelayMinutes: z.number().int().positive().max(525_600).optional(),
3377
+ prompt: nonEmptyString,
3378
+ modelSelection: modelSelectionSchema.optional(),
3379
+ mode: zcodeTaskModeSchema.optional(),
3380
+ targetTaskId: nonEmptyString.optional(),
3381
+ botDeliveryTarget: zcodeAutomationBotDeliveryTargetSchema.optional(),
3382
+ recurring: z.boolean().optional(),
3383
+ maxRuns: z.number().int().positive().optional(),
3384
+ // 会话侧自定义重复 carrier:每 N 分钟/小时/天/周/月/年均通过此字段归一化为权威 scheduleRule,
3385
+ // cronExpr 仅作合法兼容展示。
3386
+ intervalUnit: zcodeAutomationIntervalUnitSchema.optional(),
3387
+ interval: z.number().int().min(1).max(200).optional(),
3388
+ })
3389
+ .strict()
3390
+ // intervalUnit 与 interval 必须配对提交(只传一个无法确定真实间隔)。
3391
+ .refine((input) => (input.intervalUnit === undefined) === (input.interval === undefined), {
3392
+ message: "intervalUnit and interval must be set together",
3393
+ path: ["interval"],
3394
+ })
3395
+ // 周期 carrier 与一次性相对延迟语义冲突,禁止同传。
3396
+ .refine((input) => input.intervalUnit === undefined || input.relativeDelayMinutes === undefined, {
3397
+ message: "intervalUnit cannot combine with a relative delayMinutes",
3398
+ path: ["intervalUnit"],
3399
+ })
3400
+ .refine((input) => input.intervalUnit === undefined || input.recurring !== false, {
3401
+ message: "intervalUnit is a recurring carrier and cannot combine with recurring=false",
3402
+ path: ["recurring"],
3403
+ })
3404
+ .refine((input) => input.intervalUnit === undefined || input.maxRuns === undefined, {
3405
+ message: "intervalUnit is a recurring carrier and cannot combine with maxRuns",
3406
+ path: ["maxRuns"],
3407
+ });
3408
+ export type ZCodeAutomationCreateProtocolParams = z.infer<typeof zcodeAutomationCreateParamsSchema>;
3409
+
3410
+ export const zcodeAutomationCreateResultSchema = z
3411
+ .object({ automation: zcodeAutomationProtocolSchema })
3412
+ .strict();
3413
+ export type ZCodeAutomationCreateProtocolResult = z.infer<typeof zcodeAutomationCreateResultSchema>;
3414
+
3415
+ export const zcodeAutomationUpdateParamsSchema = z
3416
+ .object({
3417
+ automationId: nonEmptyString,
3418
+ title: nonEmptyString.optional(),
3419
+ cronExpr: nonEmptyString.optional(),
3420
+ prompt: nonEmptyString.optional(),
3421
+ recurring: z.boolean().optional(),
3422
+ maxRuns: z.number().int().positive().nullable().optional(),
3423
+ // 会话侧自定义重复 carrier(同 create 侧语义)。
3424
+ intervalUnit: zcodeAutomationIntervalUnitSchema.optional(),
3425
+ interval: z.number().int().min(1).max(200).optional(),
3426
+ })
3427
+ .strict()
3428
+ .refine(
3429
+ (input) =>
3430
+ input.title !== undefined ||
3431
+ input.cronExpr !== undefined ||
3432
+ input.prompt !== undefined ||
3433
+ input.recurring !== undefined ||
3434
+ input.maxRuns !== undefined ||
3435
+ input.intervalUnit !== undefined,
3436
+ { message: "automation update requires at least one field" },
3437
+ )
3438
+ .refine((input) => input.maxRuns !== null || input.recurring === true, {
3439
+ message: "clearing maxRuns requires recurring=true",
3440
+ path: ["maxRuns"],
3441
+ })
3442
+ .refine((input) => input.recurring !== true || typeof input.maxRuns !== "number", {
3443
+ message: "recurring=true cannot be combined with a numeric maxRuns",
3444
+ path: ["maxRuns"],
3445
+ })
3446
+ // intervalUnit 与 interval 必须配对提交(同 create 侧语义)。
3447
+ .refine((input) => (input.intervalUnit === undefined) === (input.interval === undefined), {
3448
+ message: "intervalUnit and interval must be set together",
3449
+ path: ["interval"],
3450
+ })
3451
+ .refine((input) => input.intervalUnit === undefined || input.recurring !== false, {
3452
+ message: "intervalUnit is a recurring carrier and cannot combine with recurring=false",
3453
+ path: ["recurring"],
3454
+ })
3455
+ .refine(
3456
+ (input) =>
3457
+ input.intervalUnit === undefined ||
3458
+ input.maxRuns === undefined ||
3459
+ (input.maxRuns === null && input.recurring === true),
3460
+ {
3461
+ message:
3462
+ "intervalUnit is a recurring carrier and only allows maxRuns=null with recurring=true",
3463
+ path: ["maxRuns"],
3464
+ },
3465
+ );
3466
+ export type ZCodeAutomationUpdateProtocolParams = z.infer<typeof zcodeAutomationUpdateParamsSchema>;
3467
+ export const zcodeAutomationUpdateResultSchema = z
3468
+ .object({ automation: zcodeAutomationProtocolSchema })
3469
+ .strict();
3470
+ export type ZCodeAutomationUpdateProtocolResult = z.infer<typeof zcodeAutomationUpdateResultSchema>;
3471
+
3472
+ export const zcodeAutomationListParamsSchema = z.object({}).strict();
3473
+ export type ZCodeAutomationListProtocolParams = z.infer<typeof zcodeAutomationListParamsSchema>;
3474
+ export const zcodeAutomationListResultSchema = z
3475
+ .object({ automations: z.array(zcodeAutomationProtocolSchema) })
3476
+ .strict();
3477
+ export type ZCodeAutomationListProtocolResult = z.infer<typeof zcodeAutomationListResultSchema>;
3478
+
3479
+ export const zcodeAutomationCheckTaskBindingParamsSchema = z
3480
+ .object({ targetTaskId: nonEmptyString })
3481
+ .strict();
3482
+ export type ZCodeAutomationCheckTaskBindingProtocolParams = z.infer<
3483
+ typeof zcodeAutomationCheckTaskBindingParamsSchema
3484
+ >;
3485
+ export const zcodeAutomationCheckTaskBindingResultSchema = z
3486
+ .object({ bound: z.boolean() })
3487
+ .strict();
3488
+ export type ZCodeAutomationCheckTaskBindingProtocolResult = z.infer<
3489
+ typeof zcodeAutomationCheckTaskBindingResultSchema
3490
+ >;
3491
+
3492
+ export const zcodeAutomationDeleteParamsSchema = z
3493
+ .object({ automationId: nonEmptyString })
3494
+ .strict();
3495
+ export type ZCodeAutomationDeleteProtocolParams = z.infer<typeof zcodeAutomationDeleteParamsSchema>;
3496
+ export const zcodeAutomationDeleteResultSchema = z.object({ deleted: z.boolean() }).strict();
3497
+ export type ZCodeAutomationDeleteProtocolResult = z.infer<typeof zcodeAutomationDeleteResultSchema>;
3498
+
3499
+ // ---- Off-Peak(闲时任务)会话内创建协议----
3500
+ // 与 automation 兄弟并列(独立域,禁止互相复用标记/表)。workspace 由 host 端从
3501
+ // 当前 session 注入,不进协议参数(对称 automation/create)。permissionMode 只开放产品
3502
+ // 四档词表;缺省解析在 host 端(yolo / allowed_models 末位 / 最高推理档)。
3503
+ export const zcodeOffPeakPermissionModeSchema = z.enum(["build", "edit", "plan", "yolo"]);
3504
+ export type ZCodeOffPeakProtocolPermissionMode = z.infer<typeof zcodeOffPeakPermissionModeSchema>;
3505
+
3506
+ export const zcodeOffPeakCreateParamsSchema = z
3507
+ .object({
3508
+ title: nonEmptyString,
3509
+ prompt: nonEmptyString,
3510
+ permissionMode: zcodeOffPeakPermissionModeSchema.optional(),
3511
+ model: nonEmptyString.optional(),
3512
+ thoughtLevel: nonEmptyString.optional(),
3513
+ // 会话内创建绑定当前会话(对齐 automation/create 的 targetTaskId),由 CLI 端口填入。
3514
+ boundSessionId: nonEmptyString.optional(),
3515
+ })
3516
+ .strict();
3517
+ export type ZCodeOffPeakCreateProtocolParams = z.infer<typeof zcodeOffPeakCreateParamsSchema>;
3518
+
3519
+ // 协议侧任务快照:轮尾卡片与 OffPeakList 的最小字段面。
3520
+ // 不暴露 serverTicketId(跨边界禁带)。
3521
+ export const zcodeOffPeakTaskSnapshotSchema = z
3522
+ .object({
3523
+ offPeakTaskId: nonEmptyString,
3524
+ title: z.string(),
3525
+ status: z.enum(["queued", "paused", "running", "completed", "failed", "cancelled"]),
3526
+ queuePosition: z.number().int().positive().optional(),
3527
+ sessionId: nonEmptyString.optional(),
3528
+ createdAt: z.number().int().nonnegative(),
3529
+ })
3530
+ .strict();
3531
+ export type ZCodeOffPeakTaskProtocolSnapshot = z.infer<typeof zcodeOffPeakTaskSnapshotSchema>;
3532
+
3533
+ // 失败分类跨协议保真(镜像 shared OffPeakTaskCreateResult 的判别联合,错误不降级为字符串)。
3534
+ // model 白名单预校失败复用 client_validation 分类 + errorCode "model_not_allowed",不扩分类枚举。
3535
+ export const zcodeOffPeakCreateResultSchema = z.discriminatedUnion("ok", [
3536
+ z.object({ ok: z.literal(true), task: zcodeOffPeakTaskSnapshotSchema }).strict(),
3537
+ z
3538
+ .object({
3539
+ ok: z.literal(false),
3540
+ failureStage: z.enum(["client_validation", "ticket_request", "local_persist"]),
3541
+ errorCategory: z.enum([
3542
+ "client_validation",
3543
+ "eligibility_3101",
3544
+ "quota_3103",
3545
+ "network",
3546
+ "invalid_response",
3547
+ "local_persist",
3548
+ "unknown",
3549
+ ]),
3550
+ errorCode: z.string(),
3551
+ })
3552
+ .strict(),
3553
+ ]);
3554
+ export type ZCodeOffPeakCreateProtocolResult = z.infer<typeof zcodeOffPeakCreateResultSchema>;
3555
+
3556
+ export const zcodeOffPeakListParamsSchema = z.object({}).strict();
3557
+ export type ZCodeOffPeakListProtocolParams = z.infer<typeof zcodeOffPeakListParamsSchema>;
3558
+ export const zcodeOffPeakListResultSchema = z
3559
+ .object({ tasks: z.array(zcodeOffPeakTaskSnapshotSchema) })
3560
+ .strict();
3561
+ export type ZCodeOffPeakListProtocolResult = z.infer<typeof zcodeOffPeakListResultSchema>;
3562
+
3563
+ export const zcodeProtocolMethods = {
3564
+ runtimeCapabilities: "runtime/capabilities",
3565
+ computerUseOperationEvent: "computer-use/operation-event",
3566
+ sessionCreate: "session/create",
3567
+ sessionResume: "session/resume",
3568
+ sessionList: "session/list",
3569
+ sessionSubagents: "session/subagents",
3570
+ sessionRequestRuntimePreferences: "session/requestRuntimePreferences",
3571
+ sessionRead: "session/read",
3572
+ sessionMessages: "session/messages",
3573
+ sessionEvents: "session/events",
3574
+ sessionDebug: "session/debug",
3575
+ sessionSubscribe: "session/subscribe",
3576
+ // @deprecated(部分):send 主路径已收敛 v4 sendText;仅剩 adapter 附件
3577
+ // 回退分支消费(v4 attachmentRef 上传/寄存命令面未建模),待附件命令面落地后移除。
3578
+ sessionSend: "session/send",
3579
+ // @deprecated:host 客户端方法已删(stop 已收敛 v4 stop 命令)。
3580
+ // wire case 留兼容(transport bypass 名单仍引用),随旧词整体删除时一并移除。
3581
+ sessionStop: "session/stop",
3582
+ // @deprecated:host 客户端方法已删(已收敛 v4 cancelBackgroundWork 命令)。
3583
+ // wire case 留兼容,随旧词整体删除时一并移除。
3584
+ sessionCancelBackgroundTask: "session/cancelBackgroundTask",
3585
+ // @deprecated:host 客户端方法已删(v4 forkAssistant 原生 handler 经
3586
+ // forkSessionAtMessage 钩子直调 server-operations.forkSession op)。wire case 与
3587
+ // fork params/result schema 保留=op 存活面;fork record 归 v4 原生重写。
3588
+ sessionFork: "session/fork",
3589
+ sessionCompact: "session/compact",
3590
+ sessionGoal: "session/goal",
3591
+ sessionClose: "session/close",
3592
+ // setModel 仍被 zcodeSessionService 的 desktop 旧链路消费;replayable
3593
+ // switchModelConfig 已直接由目标 Environment Registry 解析 Selection。
3594
+ sessionSetModel: "session/setModel",
3595
+ // replayable facade 的思考深度/模式已收敛 v4 switchModelConfig/
3596
+ // switchCollaborationMode;剩余消费 = zcodeSessionService(desktop 旧链路,随
3597
+ // 桌面 v4 UI 收口清零)与 setMode 的 auto 值残留(v4 值域刻意排除 auto)。
3598
+ sessionSetThoughtLevel: "session/setThoughtLevel",
3599
+ sessionSetMode: "session/setMode",
3600
+ workspaceReadPresentation: "workspace/readPresentation",
3601
+ workspaceHookTrustGrant: "workspace/hooks/trustGrant",
3602
+ // 进程级 Account Provider Config 与 workspace 运行目录分离。
3603
+ providerUpdateAccountConfig: "provider/updateAccountConfig",
3604
+ workspaceUpdateInteractionPreferences: "workspace/updateInteractionPreferences",
3605
+ workspaceUpdateModelIoPreferences: "workspace/updateModelIoPreferences",
3606
+ // Off-Peak 工具面门禁是 workspace 级事实(灰度 + 本地/远程),由 host 在 agent 就绪时同步;
3607
+ // CLI 对 legacy create/resume 与 v4 冷恢复统一读取。旧 CLI method-not-found → host 降级忽略。
3608
+ workspaceUpdateOffPeakToolPolicy: "workspace/updateOffPeakToolPolicy",
3609
+ // 动态工作流灰度门禁:同 Off-Peak 的同步模式。
3610
+ workspaceUpdateDynamicWorkflowPolicy: "workspace/updateDynamicWorkflowPolicy",
3611
+ // LLM 执行面在 CLI,直连不可行;消费仅 services 内部
3612
+ // (commit message),待 v4 workspace 查询/命令面覆盖后移除。
3613
+ workspaceGenerateText: "workspace/generateText",
3614
+ workspaceCancelGenerateText: "workspace/cancelGenerateText",
3615
+ providerTestModelConnectivity: "provider/testModelConnectivity",
3616
+ mcpList: "mcp/list",
3617
+ pluginsList: "plugins/list",
3618
+ pluginsReferenceCatalog: "plugins/referenceCatalog",
3619
+ pluginsReferenceCatalogWithCategory: "plugins/referenceCatalogWithCategory",
3620
+ skillsReferenceCatalog: "skills/referenceCatalog",
3621
+ // 已保存工作流的 GUI 中枢:workspace 级、无会话。
3622
+ workflowsList: "workflows/list",
3623
+ workflowsGet: "workflows/get",
3624
+ workflowsUpdateMeta: "workflows/updateMeta",
3625
+ workflowsDelete: "workflows/delete",
3626
+ workflowsRuns: "workflows/runs",
3627
+ // 在项目档 / 全局档之间移动同名文件。
3628
+ workflowsMove: "workflows/move",
3629
+ pluginsResolveSuggestedReference: "plugins/resolveSuggestedReference",
3630
+ pluginsSetEnabled: "plugins/setEnabled",
3631
+ pluginsOverview: "plugins/overview",
3632
+ pluginsMarketplaceAdd: "plugins/marketplace/add",
3633
+ pluginsMarketplaceRemove: "plugins/marketplace/remove",
3634
+ pluginsMarketplaceUpdate: "plugins/marketplace/update",
3635
+ pluginsInstall: "plugins/install",
3636
+ pluginsCancelOperation: "plugins/cancelOperation",
3637
+ pluginsUninstall: "plugins/uninstall",
3638
+ pluginsUpdate: "plugins/update",
3639
+ pluginsRestoreBuiltin: "plugins/restoreBuiltin",
3640
+ pluginsConfigure: "plugins/configure",
3641
+ pluginsResetConfig: "plugins/resetConfig",
3642
+ pluginsValidate: "plugins/validate",
3643
+ pluginsDescribe: "plugins/describe",
3644
+ automationCreate: "automation/create",
3645
+ automationUpdate: "automation/update",
3646
+ automationCheckTaskBinding: "automation/checkTaskBinding",
3647
+ automationList: "automation/list",
3648
+ automationDelete: "automation/delete",
3649
+ // Off-Peak 会话内创建:与 automation 兄弟并列的独立方法族。
3650
+ offPeakCreate: "offPeak/create",
3651
+ offPeakList: "offPeak/list",
3652
+ // @deprecated:host 消费已清零(zcodeAgentService 改走 v4/usage/stats)。
3653
+ // 仅剩 CLI server 的 wire 兼容 case;随旧词整体删除时一并移除。
3654
+ usageStats: "usage/stats",
3655
+ // ZCode Protocol 对 agent 只暴露 session-first 方法;task 是 UI 投影概念,不能泄露进协议方法名。
3656
+ // @deprecated:host 已改走 v4/conversation/usage;后续与 usage/stats 一并移除。
3657
+ sessionUsage: "session/usage",
3658
+ // 资源管理器:CLI 回报其 MCP 子进程 pid 与插件归属(纯内存,无 I/O),采样在 Host 侧完成。
3659
+ processChildProcesses: "process/childProcesses",
3660
+ interactionRequestPermission: "interaction/requestPermission",
3661
+ interactionRequestUserInput: "interaction/requestUserInput",
3662
+ interactionRequestProviderRuntimeHeaders: "interaction/requestProviderRuntimeHeaders",
3663
+ interactionRequestOfficialMcpAuthHeaders: "interaction/requestOfficialMcpAuthHeaders",
3664
+ // browser-use 反向请求由 agent 发起,host 转给 main 中的 CDP executor。
3665
+ interactionBrowserList: "interaction/browserList",
3666
+ interactionBrowserExecute: "interaction/browserExecute",
3667
+ } as const;
3668
+
3669
+ export type ZCodeProtocolMethod = (typeof zcodeProtocolMethods)[keyof typeof zcodeProtocolMethods];
3670
+
3671
+ export const zcodeProtocolEmptyResultSchema = z.object({}).strict();
3672
+
3673
+ // 最新 V4 主链已不再依赖旧版全量方法表;这里仅保留仍被兼容测试和 browser broker
3674
+ // 消费的最小契约集合,避免重新引入已移除的 legacy 方法。
3675
+ export const zcodeProtocolSessionMethodContracts = {
3676
+ [zcodeProtocolMethods.workspaceHookTrustGrant]: {
3677
+ params: zcodeWorkspaceHookTrustGrantParamsSchema,
3678
+ result: zcodeWorkspaceHookTrustGrantResultSchema,
3679
+ },
3680
+ [zcodeProtocolMethods.mcpList]: {
3681
+ params: zcodeMcpListParamsSchema,
3682
+ result: zcodeMcpListResultSchema,
3683
+ },
3684
+ [zcodeProtocolMethods.interactionBrowserList]: {
3685
+ params: zcodeBrowserListParamsSchema,
3686
+ result: zcodeBrowserListResultSchema,
3687
+ },
3688
+ [zcodeProtocolMethods.interactionBrowserExecute]: {
3689
+ params: zcodeBrowserExecuteParamsSchema,
3690
+ result: zcodeBrowserExecuteResultSchema,
3691
+ },
3692
+ } as const satisfies Partial<
3693
+ Record<ZCodeProtocolMethod, { params: z.ZodTypeAny; result: z.ZodTypeAny }>
3694
+ >;
3695
+
3696
+ export type ZCodeProtocolSessionMethodContract =
3697
+ (typeof zcodeProtocolSessionMethodContracts)[keyof typeof zcodeProtocolSessionMethodContracts];
3698
+
3699
+ /** 仅存储准备子进程的私有控制帧,原始路径不进入业务事件或遥测。 */
3700
+ export const zcodeStoragePreparationFrameSchema = z.discriminatedUnion("method", [
3701
+ z
3702
+ .object({
3703
+ method: z.literal("startup/storagePath"),
3704
+ params: z.object({ path: z.string().min(1).max(32768) }).strict(),
3705
+ })
3706
+ .strict(),
3707
+ z
3708
+ .object({ method: z.literal("startup/storagePrepared"), params: z.object({}).strict() })
3709
+ .strict(),
3710
+ z
3711
+ .object({ method: z.literal("startup/storageState"), params: zcodeStorageStartupStateSchema })
3712
+ .strict(),
3713
+ ]);
3714
+ export const zcodeStoragePathReadySchema = z
3715
+ .object({ method: z.literal("startup/storagePathReady"), reuse: z.boolean().optional() })
3716
+ .strict();
3717
+ export * from "../localTtft.js";
3718
+
3719
+ // 桌面本地 TTFT 的严格事实合同;检查点不能替代实际内容帧。
3720
+ export { localTtftFactsSchema } from "../localTtft.js";