validation.ts 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193
  1. import { mobilePluginDiscoveryTelemetrySchema, telemetryUiModeSchema } from "./telemetry.js";
  2. import { remoteConversationTelemetryEventSchema } from "./conversation-telemetry/remoteTelemetryEvent.js";
  3. import { databaseStartupControlSchema, databaseStartupStateSchema } from "./database-startup.js";
  4. import { mcpAppInstanceSchema } from "./mcp-apps/instance.js";
  5. import {
  6. automationSessionCreateTelemetrySchema,
  7. sessionCreateTelemetrySchema,
  8. } from "./sessionCreateTelemetry.js";
  9. /* eslint-disable max-lines -- 运行时 schema 当前集中在共享包入口,外部 relay payload 校验加入后先保持单一导出面。 */
  10. import { z } from "zod";
  11. export const CREDENTIAL_PLAINTEXT_MAX_BYTES = 1_048_576;
  12. // UTF-8 明文经过 Base64 后会膨胀;保留 IV、tag、版本和指纹的固定开销。
  13. export const CREDENTIAL_CIPHERTEXT_MAX_CHARS =
  14. Math.ceil(CREDENTIAL_PLAINTEXT_MAX_BYTES / 3) * 4 + 128;
  15. export const credentialPlaintextSchema = z
  16. .string()
  17. .max(CREDENTIAL_PLAINTEXT_MAX_BYTES)
  18. .refine(
  19. (value) => new TextEncoder().encode(value).byteLength <= CREDENTIAL_PLAINTEXT_MAX_BYTES,
  20. "Credential plaintext exceeds the UTF-8 byte limit",
  21. );
  22. export const credentialCiphertextSchema = z.string().max(CREDENTIAL_CIPHERTEXT_MAX_CHARS);
  23. export const credentialCipherRequestSchema = z
  24. .object({
  25. requestId: z.string().uuid(),
  26. operation: z.enum(["encrypt", "decrypt"]),
  27. value: credentialCiphertextSchema,
  28. })
  29. .strict()
  30. .superRefine((request, ctx) => {
  31. if (
  32. request.operation === "encrypt" &&
  33. !credentialPlaintextSchema.safeParse(request.value).success
  34. )
  35. ctx.addIssue({
  36. code: "custom",
  37. path: ["value"],
  38. message: "Credential plaintext exceeds the UTF-8 byte limit",
  39. });
  40. });
  41. export const credentialCipherResultSchema = z.discriminatedUnion("ok", [
  42. z.object({ ok: z.literal(true), value: credentialCiphertextSchema }).strict(),
  43. z
  44. .object({
  45. ok: z.literal(false),
  46. error: z.object({ code: z.string(), message: z.string() }).strict(),
  47. })
  48. .strict(),
  49. ]);
  50. export const credentialCipherReplySchema = z
  51. .object({ requestId: z.string().uuid(), result: credentialCipherResultSchema })
  52. .strict();
  53. export type CredentialCipherRequest = z.infer<typeof credentialCipherRequestSchema>;
  54. export type CredentialCipherReply = z.infer<typeof credentialCipherReplySchema>;
  55. import { networkCaptureControlSchema, networkCaptureBatchSchema } from "./networkCapture.js";
  56. import { browserCommandSchema } from "./browser-use/commands.js";
  57. import { browserCommandResultSchema } from "./browser-use/result.js";
  58. import { modelSelectionSchema } from "./model-selection.js";
  59. import { localeSchema, replyLanguageSchema } from "./validationAppSettings.js";
  60. import { zcodeProcessDiagnosticSchema } from "./process-diagnostic.js";
  61. import { PROCESS_RESOURCE_CLI_LANES } from "./processResourceTelemetry.js";
  62. import {
  63. providerProvisioningErrorCodeSchema,
  64. providerProvisioningLaneStatusSchema,
  65. providerProvisioningTriggerSchema,
  66. } from "./provider-provisioning.js";
  67. import { zcodeProviderSchema } from "./providers.js";
  68. import { REMOTE_ASSET_INSTALL_MODES } from "./remoteAssetInstallMode.js";
  69. import { isKnownRemoteResourcePackageId } from "./remoteResourcePackages.js";
  70. import type { WebRemoteControlAppPayload } from "./web-remote-control.js";
  71. import { webRemoteControlMobileLogAppPayloadSchemas } from "#src/web-remote-relay/index.js";
  72. import { PROTOCOL_V4_LIMITS } from "./zcode-protocol-v4/core.js";
  73. import { sourceServerArtifactPolicySchema } from "./source-server/release.js";
  74. import { sessionWorkflowActivitySchema } from "./zcode-protocol-v4/sessions-index-workflow-activity.js";
  75. import {
  76. webRemoteControlRpcTransportAckSchema,
  77. webRemoteControlRpcTransportFrameSchema,
  78. } from "./web-remote-control-rpc-transport.js";
  79. import {
  80. taskOwnerCommandDeliverySchema,
  81. taskOwnerCommandRequestSchema,
  82. taskOwnerCommandResultSchema,
  83. taskRealtimeDeliveredEventSchema,
  84. taskRealtimeEventSchema,
  85. taskRealtimeHostDeliveryKindSchema,
  86. taskRunLeaseAcquireRequestSchema,
  87. taskRunLeaseResultSchema,
  88. taskRunLeaseTargetSchema,
  89. taskStreamMirrorPublishOpSchema,
  90. taskStreamMirrorTargetSchema,
  91. } from "./task-realtime-core.js";
  92. import { wslUserSchema } from "./wslUserValidation.js";
  93. import { legacyZCodeProviderSchema } from "./zcode-agent-policy.js";
  94. import { errorAttributionSchema } from "./zcode-protocol-v4/snapshot.js";
  95. import {
  96. zcodeMcpResourceSamplesSchema,
  97. zcodeMcpTelemetryEventSchema,
  98. zcodeProcessResourceSampleSchema,
  99. zcodeToolExecResourceSchema,
  100. } from "./zcode-protocol/index.js";
  101. import { zcodeTaskModeSchema } from "./zcode-task-mode-schema.js";
  102. export {
  103. appSettingsOccupationEnum,
  104. appSettingsPatchSchema,
  105. appSettingsSchema,
  106. localeSchema,
  107. postUpdateReleaseNotesPayloadSchema,
  108. REPLY_LANGUAGE_MAX_LENGTH,
  109. } from "./validationAppSettings.js";
  110. export { isValidWslUser, WSL_USER_MAX_LENGTH, wslUserSchema } from "./wslUserValidation.js";
  111. export { zcodeTaskModeSchema } from "./zcode-task-mode-schema.js";
  112. export function formatZodError(error: z.ZodError): string {
  113. return error.issues
  114. .map((issue) => {
  115. const path = issue.path.length > 0 ? issue.path.join(".") : "<root>";
  116. return `${path}: ${issue.message}`;
  117. })
  118. .join("; ");
  119. }
  120. export const nonEmptyStringSchema = z.string().trim().min(1);
  121. export const stringArraySchema = z.array(z.string());
  122. // Task04B:topic physical-frame 计量器按 bridge/recovery id 的协议最大长度计算
  123. // mobile relay 外壳;不在不可信 payload 入口机械限长,1MiB 上限就只是估算。
  124. const webRemoteControlTransportIdSchema = nonEmptyStringSchema
  125. .max(PROTOCOL_V4_LIMITS.transportEnvelopeIdMaxChars)
  126. .regex(/^[A-Za-z0-9._~-]+$/u);
  127. export const webRemoteControlWorkspaceTargetSchema = z.object({
  128. workspacePath: nonEmptyStringSchema,
  129. workspaceIdentity: nonEmptyStringSchema.optional(),
  130. remoteSessionId: nonEmptyStringSchema.optional(),
  131. label: nonEmptyStringSchema,
  132. workspacePurpose: z.enum(["project", "conversation"]).optional(),
  133. kind: z.enum(["local", "remote"]),
  134. connectionState: z.enum(["connected", "disconnected", "reconnecting"]).optional(),
  135. lastConnectionError: z.string().optional(),
  136. });
  137. export const webRemoteControlWorkspaceTargetsSchema = z.array(
  138. webRemoteControlWorkspaceTargetSchema,
  139. );
  140. export const webRemoteControlReconnectWorkspaceRequestSchema = z.object({
  141. requestId: nonEmptyStringSchema,
  142. workspaceKey: nonEmptyStringSchema,
  143. });
  144. export const webRemoteControlReconnectWorkspaceResultSchema = z.union([
  145. z.object({
  146. requestId: nonEmptyStringSchema,
  147. workspaceKey: nonEmptyStringSchema,
  148. success: z.literal(true),
  149. }),
  150. z.object({
  151. requestId: nonEmptyStringSchema,
  152. workspaceKey: nonEmptyStringSchema,
  153. success: z.literal(false),
  154. error: z.string(),
  155. }),
  156. ]);
  157. export const webRemoteControlFailureReasonSchema = z.enum([
  158. "session-not-found",
  159. "session-expired",
  160. "session-conflict",
  161. "workspace-closed",
  162. "desktop-disconnected",
  163. "invalid-mobile-connection",
  164. "desktop-bootstrap-timeout",
  165. "connection-recovery-timeout",
  166. "relay-unavailable",
  167. "unsupported-action",
  168. "unexpected-error",
  169. ]);
  170. export const webRemoteControlExternalWorkspaceBridgeSchema = z.discriminatedUnion("kind", [
  171. z.object({
  172. terminalOwnerId: webRemoteControlTransportIdSchema.optional(),
  173. bridgeSessionId: webRemoteControlTransportIdSchema,
  174. bridgeGeneration: z.number().int().nonnegative().optional(),
  175. recoveryId: webRemoteControlTransportIdSchema.optional(),
  176. kind: z.literal("local"),
  177. workspaceKey: nonEmptyStringSchema,
  178. workspacePath: nonEmptyStringSchema,
  179. initialTaskId: nonEmptyStringSchema.optional(),
  180. }),
  181. z.object({
  182. terminalOwnerId: webRemoteControlTransportIdSchema.optional(),
  183. bridgeSessionId: webRemoteControlTransportIdSchema,
  184. bridgeGeneration: z.number().int().nonnegative().optional(),
  185. recoveryId: webRemoteControlTransportIdSchema.optional(),
  186. kind: z.literal("remote"),
  187. workspaceKey: nonEmptyStringSchema,
  188. workspacePath: nonEmptyStringSchema,
  189. workspaceIdentity: nonEmptyStringSchema,
  190. workspacePurpose: z.enum(["project", "conversation"]).optional(),
  191. remoteSessionId: nonEmptyStringSchema,
  192. initialTaskId: nonEmptyStringSchema.optional(),
  193. capabilities: z.object({ windowProjectDirectory: z.literal(true).optional() }).optional(),
  194. }),
  195. ]);
  196. export const webRemoteControlMobileViewStateSchema = z.object({
  197. activeWorkspaceKey: nonEmptyStringSchema.optional(),
  198. activeTaskId: nonEmptyStringSchema.optional(),
  199. updatedAt: z.number().finite(),
  200. });
  201. export const webRemoteControlMobileTaskViewSchema = z
  202. .object({
  203. workspacePath: nonEmptyStringSchema,
  204. workspaceIdentity: nonEmptyStringSchema.optional(),
  205. taskId: nonEmptyStringSchema,
  206. })
  207. .strict();
  208. export const webRemoteControlMobileDeviceInfoSchema = z.object({
  209. platform: nonEmptyStringSchema,
  210. version: nonEmptyStringSchema,
  211. name: nonEmptyStringSchema,
  212. userAgent: z.string().optional(),
  213. language: z.string().optional(),
  214. languages: z.array(z.string()).optional(),
  215. browserPlatform: z.string().optional(),
  216. viewport: z
  217. .object({
  218. width: z.number().finite(),
  219. height: z.number().finite(),
  220. devicePixelRatio: z.number().finite(),
  221. })
  222. .optional(),
  223. screen: z
  224. .object({
  225. width: z.number().finite(),
  226. height: z.number().finite(),
  227. })
  228. .optional(),
  229. timezone: z.string().optional(),
  230. online: z.boolean().optional(),
  231. updatedAt: z.number().finite(),
  232. });
  233. export const webRemoteControlWindowBootstrapResultSchema = z.object({
  234. windowControlSessionId: nonEmptyStringSchema,
  235. desktopAppVersion: nonEmptyStringSchema.optional(),
  236. workspaces: webRemoteControlWorkspaceTargetsSchema,
  237. initialViewState: webRemoteControlMobileViewStateSchema.optional(),
  238. mobileViewState: webRemoteControlMobileViewStateSchema.optional(),
  239. mobileTaskViewEpoch: webRemoteControlTransportIdSchema.optional(),
  240. });
  241. export const webRemoteControlWorkspaceListResultSchema = z.object({
  242. workspaces: webRemoteControlWorkspaceTargetsSchema,
  243. activeWorkspaceKey: nonEmptyStringSchema.optional(),
  244. activeTaskId: nonEmptyStringSchema.optional(),
  245. });
  246. export const webRemoteControlPlatformMethodSchema = z.enum([
  247. "isDockerAvailable",
  248. "listWSLDistros",
  249. "listDockerContainers",
  250. "listSSHConfigAliases",
  251. "loadMcpFromUserDirectory",
  252. "saveMcpToUserDirectory",
  253. "migrateLegacyCommonMcp",
  254. ]);
  255. // 手机动作请求:workspaceIdentity 与 KMP 一致为可选;远程任务缺 identity 时由 controller 按路径解析。
  256. const webRemoteControlTaskActionTargetShape = {
  257. requestId: nonEmptyStringSchema,
  258. taskId: nonEmptyStringSchema,
  259. workspacePath: nonEmptyStringSchema,
  260. workspaceIdentity: nonEmptyStringSchema.optional(),
  261. };
  262. export const webRemoteControlRendererActionRequestSchema = z.discriminatedUnion("kind", [
  263. z.object({
  264. kind: z.literal("task-pin"),
  265. ...webRemoteControlTaskActionTargetShape,
  266. pinned: z.boolean(),
  267. }),
  268. z.object({
  269. kind: z.literal("task-archive"),
  270. ...webRemoteControlTaskActionTargetShape,
  271. archived: z.boolean(),
  272. }),
  273. z.object({
  274. kind: z.literal("workspace-create"),
  275. requestId: nonEmptyStringSchema,
  276. name: z.string(),
  277. }),
  278. ]);
  279. export const webRemoteControlRendererActionResultSchema = z.union([
  280. z.object({
  281. requestId: nonEmptyStringSchema,
  282. success: z.literal(true),
  283. workspacePath: nonEmptyStringSchema.optional(),
  284. projectId: nonEmptyStringSchema.optional(),
  285. hostId: nonEmptyStringSchema.optional(),
  286. }),
  287. z.object({
  288. requestId: nonEmptyStringSchema,
  289. success: z.literal(false),
  290. error: z.string(),
  291. }),
  292. ]);
  293. const webRemoteControlActionPayloadSchemas = [
  294. z.object({
  295. zcode_type: z.literal("workspace-create-request"),
  296. requestId: nonEmptyStringSchema,
  297. name: z.string(),
  298. }),
  299. z.object({
  300. zcode_type: z.literal("workspace-create-response"),
  301. requestId: nonEmptyStringSchema,
  302. success: z.literal(true),
  303. workspacePath: nonEmptyStringSchema,
  304. workspaceKey: nonEmptyStringSchema,
  305. projectId: nonEmptyStringSchema.optional(),
  306. hostId: nonEmptyStringSchema.optional(),
  307. }),
  308. z.object({
  309. zcode_type: z.literal("workspace-create-response"),
  310. requestId: nonEmptyStringSchema,
  311. success: z.literal(false),
  312. error: z.string(),
  313. }),
  314. z.object({
  315. zcode_type: z.literal("task-pin-request"),
  316. ...webRemoteControlTaskActionTargetShape,
  317. pinned: z.boolean(),
  318. }),
  319. z.object({
  320. zcode_type: z.literal("task-pin-response"),
  321. requestId: nonEmptyStringSchema,
  322. taskId: nonEmptyStringSchema,
  323. success: z.literal(true),
  324. pinned: z.boolean(),
  325. }),
  326. z.object({
  327. zcode_type: z.literal("task-pin-response"),
  328. requestId: nonEmptyStringSchema,
  329. taskId: nonEmptyStringSchema,
  330. success: z.literal(false),
  331. error: z.string(),
  332. }),
  333. z.object({
  334. zcode_type: z.literal("task-archive-request"),
  335. ...webRemoteControlTaskActionTargetShape,
  336. archived: z.boolean().optional(),
  337. }),
  338. z.object({
  339. zcode_type: z.literal("task-archive-response"),
  340. requestId: nonEmptyStringSchema,
  341. taskId: nonEmptyStringSchema,
  342. success: z.literal(true),
  343. archived: z.boolean(),
  344. }),
  345. z.object({
  346. zcode_type: z.literal("task-archive-response"),
  347. requestId: nonEmptyStringSchema,
  348. taskId: nonEmptyStringSchema,
  349. success: z.literal(false),
  350. error: z.string(),
  351. }),
  352. ] as const;
  353. const webRemoteControlAppPayloadSchemas = [
  354. z
  355. .object({
  356. zcode_type: z.literal("telemetry-report"),
  357. event: z.union([sessionCreateTelemetrySchema, mobilePluginDiscoveryTelemetrySchema]),
  358. })
  359. .strict(),
  360. z.object({
  361. zcode_type: z.literal("bootstrap-request"),
  362. terminalClientSessionId: webRemoteControlTransportIdSchema.optional(),
  363. requestId: nonEmptyStringSchema,
  364. }),
  365. z.object({
  366. zcode_type: z.literal("bootstrap-response"),
  367. requestId: nonEmptyStringSchema,
  368. success: z.literal(true),
  369. result: webRemoteControlWindowBootstrapResultSchema,
  370. }),
  371. z.object({
  372. zcode_type: z.literal("workspace-list-request"),
  373. requestId: nonEmptyStringSchema,
  374. }),
  375. z.object({
  376. zcode_type: z.literal("workspace-list-response"),
  377. requestId: nonEmptyStringSchema,
  378. success: z.literal(true),
  379. result: webRemoteControlWorkspaceListResultSchema,
  380. }),
  381. z.object({
  382. zcode_type: z.literal("workspace-list-updated"),
  383. result: webRemoteControlWorkspaceListResultSchema,
  384. }),
  385. z
  386. .object({
  387. zcode_type: z.literal("workspace-bridge-open"),
  388. terminalClientSessionId: webRemoteControlTransportIdSchema.optional(),
  389. requestId: nonEmptyStringSchema,
  390. bridgeSessionId: webRemoteControlTransportIdSchema,
  391. bridgeGeneration: z.number().int().nonnegative().optional(),
  392. recoveryId: webRemoteControlTransportIdSchema.optional(),
  393. workspaceKey: nonEmptyStringSchema,
  394. taskId: nonEmptyStringSchema.optional(),
  395. taskHostId: nonEmptyStringSchema.optional(),
  396. fileTreeTaskId: nonEmptyStringSchema.optional(),
  397. project: z
  398. .object({
  399. projectId: nonEmptyStringSchema.nullable(),
  400. hostId: nonEmptyStringSchema.optional(),
  401. draftId: z.string().uuid().optional(),
  402. reuseDraft: z.boolean().optional(),
  403. })
  404. .strict()
  405. .refine(
  406. (intent) =>
  407. (!intent.draftId || intent.projectId === null) &&
  408. (!intent.reuseDraft || Boolean(intent.draftId)),
  409. "Only an unclassified draft can reuse its directory",
  410. )
  411. .optional(),
  412. })
  413. .refine(
  414. (request) =>
  415. (!request.project || (!request.taskId && !request.fileTreeTaskId)) &&
  416. !(request.taskId && request.fileTreeTaskId) &&
  417. (!request.fileTreeTaskId || Boolean(request.taskHostId)) &&
  418. (!request.taskHostId || Boolean(request.taskId || request.fileTreeTaskId)),
  419. "Project draft cannot target an existing task",
  420. ),
  421. z.object({
  422. zcode_type: z.literal("workspace-bridge-ready"),
  423. requestId: nonEmptyStringSchema,
  424. bridgeSessionId: webRemoteControlTransportIdSchema,
  425. bridgeGeneration: z.number().int().nonnegative().optional(),
  426. recoveryId: webRemoteControlTransportIdSchema.optional(),
  427. bridge: webRemoteControlExternalWorkspaceBridgeSchema,
  428. }),
  429. z.object({
  430. zcode_type: z.literal("workspace-bridge-error"),
  431. requestId: nonEmptyStringSchema,
  432. bridgeSessionId: webRemoteControlTransportIdSchema.optional(),
  433. bridgeGeneration: z.number().int().nonnegative().optional(),
  434. recoveryId: webRemoteControlTransportIdSchema.optional(),
  435. reason: webRemoteControlFailureReasonSchema,
  436. error: z.string(),
  437. }),
  438. z.object({
  439. zcode_type: z.literal("workspace-reconnect-request"),
  440. requestId: nonEmptyStringSchema,
  441. workspaceKey: nonEmptyStringSchema,
  442. }),
  443. z.object({
  444. zcode_type: z.literal("workspace-reconnect-response"),
  445. requestId: nonEmptyStringSchema,
  446. workspaceKey: nonEmptyStringSchema,
  447. success: z.literal(true),
  448. }),
  449. z.object({
  450. zcode_type: z.literal("workspace-reconnect-response"),
  451. requestId: nonEmptyStringSchema,
  452. workspaceKey: nonEmptyStringSchema,
  453. success: z.literal(false),
  454. error: z.string(),
  455. }),
  456. z.object({
  457. zcode_type: z.literal("mobile-view-state-update"),
  458. viewState: webRemoteControlMobileViewStateSchema,
  459. deviceInfo: webRemoteControlMobileDeviceInfoSchema.optional(),
  460. }),
  461. z
  462. .object({
  463. zcode_type: z.literal("mobile-task-view-update"),
  464. epoch: webRemoteControlTransportIdSchema,
  465. seq: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
  466. bridgeSessionId: webRemoteControlTransportIdSchema,
  467. bridgeGeneration: z.number().int().nonnegative().optional(),
  468. view: webRemoteControlMobileTaskViewSchema.nullable(),
  469. })
  470. .strict(),
  471. z
  472. .object({
  473. zcode_type: z.literal("mobile-task-view-request"),
  474. epoch: webRemoteControlTransportIdSchema,
  475. })
  476. .strict(),
  477. z.object({
  478. zcode_type: z.literal("platform-request"),
  479. requestId: nonEmptyStringSchema,
  480. method: webRemoteControlPlatformMethodSchema,
  481. args: z.unknown().optional(),
  482. }),
  483. z.object({
  484. zcode_type: z.literal("platform-response"),
  485. requestId: nonEmptyStringSchema,
  486. method: webRemoteControlPlatformMethodSchema,
  487. success: z.literal(true),
  488. result: z.unknown(),
  489. }),
  490. z.object({
  491. zcode_type: z.literal("platform-response"),
  492. requestId: nonEmptyStringSchema,
  493. method: webRemoteControlPlatformMethodSchema,
  494. success: z.literal(false),
  495. error: z.string(),
  496. }),
  497. // Bugfix:04D-3 必须让 fragment/ACK 与 acknowledged adapter 原子切换。
  498. // 继续接受 legacy 单片会让 raw bytes 绕过 ACK/replay owner 和 1MiB 外壳硬边界。
  499. webRemoteControlRpcTransportFrameSchema,
  500. webRemoteControlRpcTransportAckSchema,
  501. z.object({
  502. zcode_type: z.literal("bridge-degraded"),
  503. bridgeSessionId: webRemoteControlTransportIdSchema,
  504. bridgeGeneration: z.number().int().nonnegative().optional(),
  505. recoveryId: webRemoteControlTransportIdSchema.optional(),
  506. reason: z.enum([
  507. "rpc-transport-fault",
  508. "rpc-frame-gap",
  509. "buffer-overflow",
  510. "buffer-timeout",
  511. "source-session-replaced",
  512. "terminal-owner-ended",
  513. ]),
  514. seq: z.number().int().nonnegative().optional(),
  515. expectedSeq: z.number().int().nonnegative().optional(),
  516. droppedCount: z.number().int().nonnegative().optional(),
  517. }),
  518. z.object({
  519. zcode_type: z.literal("app-error"),
  520. requestId: nonEmptyStringSchema.optional(),
  521. bridgeSessionId: webRemoteControlTransportIdSchema.optional(),
  522. reason: webRemoteControlFailureReasonSchema,
  523. error: z.string(),
  524. }),
  525. z.object({
  526. zcode_type: z.literal("mobile-diagnostic"),
  527. event: z.enum([
  528. "state-transition",
  529. "socket-close",
  530. "socket-error",
  531. "recover-start",
  532. "recover-scheduled",
  533. "pair-status",
  534. "failure",
  535. ]),
  536. timestamp: z.number().int().nonnegative(),
  537. state: z.string().optional(),
  538. previousState: z.string().optional(),
  539. pairStatus: z.enum(["waiting", "matched"]).optional(),
  540. closeCode: z.number().int().optional(),
  541. closeReason: z.string().optional(),
  542. wasClean: z.boolean().optional(),
  543. wasPaired: z.boolean().optional(),
  544. failureReason: webRemoteControlFailureReasonSchema.optional(),
  545. failureMessage: z.string().optional(),
  546. visibilityState: z.string().optional(),
  547. online: z.boolean().optional(),
  548. hiddenDurationMs: z.number().int().nonnegative().optional(),
  549. }),
  550. ...webRemoteControlActionPayloadSchemas,
  551. // 手机日志通道(推送 + 拉取),线格式见 docs/web-remote-control/mobile-log-channel.md。
  552. ...webRemoteControlMobileLogAppPayloadSchemas,
  553. ] as const;
  554. // Bugfix: app payload 里多个消息共享 zcode_type(例如 platform-response),
  555. // 不能直接用 z.discriminatedUnion("zcode_type"),否则 schema 初始化会因重复值失败。
  556. // 这里保留同一批运行时约束,改用普通 union,让外部 relay 的不可信 payload
  557. // 在进入 desktop/web 路由前仍然先被机械校验。
  558. export const webRemoteControlAppPayloadSchema = z.union(webRemoteControlAppPayloadSchemas);
  559. export function parseWebRemoteControlAppPayload(
  560. payload: unknown,
  561. ): WebRemoteControlAppPayload | null {
  562. const result = webRemoteControlAppPayloadSchema.safeParse(payload);
  563. return result.success ? (result.data as WebRemoteControlAppPayload) : null;
  564. }
  565. export const credentialRecordSchema = z.record(z.string(), z.string());
  566. export const credentialKeySchema = nonEmptyStringSchema;
  567. export const credentialValueSchema = z.string();
  568. export const sshConnectOptionsSchema = z.object({
  569. kind: z.literal("ssh"),
  570. host: nonEmptyStringSchema,
  571. port: z.number().int().positive().max(65535).optional(),
  572. username: nonEmptyStringSchema,
  573. sshConfigAlias: nonEmptyStringSchema.optional(),
  574. password: z.string().optional(),
  575. privateKeyPath: z.string().optional(),
  576. privateKeyPassphrase: z.string().optional(),
  577. assetInstallMode: z.enum(REMOTE_ASSET_INSTALL_MODES).optional(),
  578. resourcePackages: z
  579. .object({
  580. selectedPackageIds: z.array(z.string().refine(isKnownRemoteResourcePackageId)).optional(),
  581. })
  582. .optional(),
  583. });
  584. export const wslConnectOptionsSchema = z.object({
  585. kind: z.literal("wsl"),
  586. distro: z.string().optional(),
  587. user: wslUserSchema.optional(),
  588. });
  589. export const dockerConnectOptionsSchema = z.object({
  590. kind: z.literal("docker"),
  591. container: nonEmptyStringSchema,
  592. });
  593. export const serverConnectOptionsSchema = z.object({
  594. kind: z.literal("server"),
  595. url: z.string().url(),
  596. name: nonEmptyStringSchema.optional(),
  597. token: z.string().optional(),
  598. workspacePath: z.string().optional(),
  599. serverId: nonEmptyStringSchema.optional(),
  600. });
  601. export const remoteTargetSchema = z.discriminatedUnion("kind", [
  602. sshConnectOptionsSchema,
  603. wslConnectOptionsSchema,
  604. dockerConnectOptionsSchema,
  605. serverConnectOptionsSchema,
  606. ]);
  607. export const helloMessageSchema = z.object({
  608. type: z.literal("zcode-hello"),
  609. version: z.string(),
  610. platform: z.string(),
  611. arch: z.string(),
  612. pid: z.number().int(),
  613. });
  614. export const helloAckMessageSchema = z.object({
  615. type: z.literal("zcode-hello-ack"),
  616. version: z.string(),
  617. clientId: nonEmptyStringSchema,
  618. });
  619. export const rendererLogPayloadSchema = z.object({
  620. level: z.enum(["info", "warn", "error"]),
  621. args: z.array(z.unknown()),
  622. });
  623. export const taskNotificationPayloadSchema = z.object({
  624. taskId: nonEmptyStringSchema,
  625. status: z.enum([
  626. "completed",
  627. "failed",
  628. "permission_request",
  629. "elicitation_request",
  630. "feedback_update",
  631. ]),
  632. requestId: nonEmptyStringSchema.optional(),
  633. title: z.string(),
  634. body: z.string(),
  635. });
  636. export const telemetryRendererContextSchema = z.object({
  637. uiMode: telemetryUiModeSchema.optional(),
  638. clientTimezone: nonEmptyStringSchema,
  639. clientLanguage: nonEmptyStringSchema,
  640. screenResolution: nonEmptyStringSchema,
  641. });
  642. export const rendererTelemetryEventPayloadSchema = z.object({
  643. context: telemetryRendererContextSchema,
  644. elementName: nonEmptyStringSchema,
  645. eventRegion: nonEmptyStringSchema,
  646. eventType: nonEmptyStringSchema,
  647. eventText: z.string().optional(),
  648. eventExtraDetail: z.record(z.string(), z.string()),
  649. userId: z.string().optional(),
  650. talkId: z.string().optional(),
  651. messageId: z.string().optional(),
  652. });
  653. export const armsCustomEventPayloadSchema = z.object({
  654. name: nonEmptyStringSchema,
  655. group: nonEmptyStringSchema,
  656. value: z.number().finite().optional(),
  657. properties: z
  658. .record(z.string(), z.union([z.string(), z.number().finite(), z.boolean(), z.undefined()]))
  659. .optional(),
  660. });
  661. export const broadcastMessageSchema = z.object({
  662. channel: nonEmptyStringSchema,
  663. payload: z.unknown(),
  664. sourceWindowId: z.number().int().optional(),
  665. });
  666. export const remoteAssetDirsSchema = z.object({
  667. mockCdnDir: z.string().optional(),
  668. remoteCdnBaseUrl: z.string().optional(),
  669. remoteCdnBaseUrls: z.array(z.string()).optional(),
  670. remoteCacheDir: z.string().optional(),
  671. sourceServerArtifactPolicy: sourceServerArtifactPolicySchema.optional(),
  672. });
  673. const hostAgentWarmupTargetSchema = z.object({
  674. workspacePath: nonEmptyStringSchema,
  675. workspaceIdentity: nonEmptyStringSchema.optional(),
  676. });
  677. export const hostInitLocalMessageSchema = z.object({
  678. browserBackendIdentity: z
  679. .object({ id: nonEmptyStringSchema, generation: z.number().int().nonnegative() })
  680. .optional(),
  681. type: z.literal("init-local"),
  682. databaseStartupId: z.string().min(1).max(128).optional(),
  683. hostId: nonEmptyStringSchema.optional(),
  684. deliveryKind: taskRealtimeHostDeliveryKindSchema.optional(),
  685. deviceMid: z.string().optional(),
  686. feedbackApiBase: z.string().url().optional(),
  687. workspacePath: nonEmptyStringSchema.optional(),
  688. workspaceIdentity: nonEmptyStringSchema.optional(),
  689. // 启动只预热 active workspace(desktop STARTUP_AGENT_WARMUP_LIMIT = 1),协议层同步收紧上限。
  690. agentWarmupTargets: z.array(hostAgentWarmupTargetSchema).max(1).optional(),
  691. agentSpawnFallbackCwd: nonEmptyStringSchema.optional(),
  692. remoteAssets: remoteAssetDirsSchema.optional(),
  693. /** spawn 时刻 Main 的实时界面语言;后续变化由 application-locale-changed 推送。 */
  694. locale: localeSchema.optional(),
  695. /** spawn 时刻 Main 持有的 Agent 回复语言(null 为未设置);后续变化由 reply-language-changed 推送。 */
  696. replyLanguage: replyLanguageSchema.nullable().optional(),
  697. zcodeBuiltinProviderConfigFilePath: nonEmptyStringSchema,
  698. runtimeProcessEnvPatch: z
  699. .record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), z.string())
  700. .optional(),
  701. });
  702. export const windowHostRemoteWorkspaceDescriptorSchema = z
  703. .object({
  704. /** 本次请求直接复用的在线连接;只包含脱敏目标,不是 session 持久状态。 */
  705. reusedConnectionTarget: remoteTargetSchema.optional(),
  706. sourceServerId: nonEmptyStringSchema.optional(),
  707. remoteSessionId: nonEmptyStringSchema,
  708. target: remoteTargetSchema,
  709. workspacePath: nonEmptyStringSchema.optional(),
  710. workspaceIdentity: nonEmptyStringSchema.optional(),
  711. workspacePurpose: z.enum(["project", "conversation"]).optional(),
  712. generation: z.number().int().positive(),
  713. })
  714. .strict();
  715. export type WindowHostRemoteWorkspaceDescriptor = z.infer<
  716. typeof windowHostRemoteWorkspaceDescriptorSchema
  717. >;
  718. /** Desktop Main → Preload → Renderer 的 remote workspace MessagePort 元数据合同。 */
  719. export const scopedServicePortPayloadSchema = windowHostRemoteWorkspaceDescriptorSchema
  720. .pick({
  721. sourceServerId: true,
  722. target: true,
  723. workspacePurpose: true,
  724. })
  725. .extend({
  726. attachmentId: nonEmptyStringSchema,
  727. sessionId: nonEmptyStringSchema,
  728. workspacePath: nonEmptyStringSchema,
  729. workspaceIdentity: nonEmptyStringSchema,
  730. })
  731. .strict();
  732. export type ScopedServicePortPayload = z.infer<typeof scopedServicePortPayloadSchema>;
  733. export const windowHostAttachmentScopeSchema = z.discriminatedUnion("kind", [
  734. z.object({ kind: z.literal("local") }).strict(),
  735. z
  736. .object({
  737. kind: z.literal("source-settings"),
  738. sourceServerId: nonEmptyStringSchema,
  739. })
  740. .strict(),
  741. z
  742. .object({
  743. kind: z.literal("remote"),
  744. sourceServerId: nonEmptyStringSchema.optional(),
  745. remoteSessionId: nonEmptyStringSchema,
  746. workspacePath: nonEmptyStringSchema,
  747. workspaceIdentity: nonEmptyStringSchema,
  748. })
  749. .strict(),
  750. ]);
  751. export type WindowHostAttachmentScope = z.infer<typeof windowHostAttachmentScopeSchema>;
  752. export const hostConnectRemoteWorkspaceMessageSchema = z
  753. .object({
  754. type: z.literal("connect-remote-workspace"),
  755. requestId: nonEmptyStringSchema,
  756. target: remoteTargetSchema,
  757. remoteAssets: remoteAssetDirsSchema,
  758. workspacePath: nonEmptyStringSchema.optional(),
  759. workspaceIdentity: nonEmptyStringSchema.optional(),
  760. confirmSourceServerInstall: z.boolean().optional(),
  761. })
  762. .strict();
  763. export const hostCancelRemoteWorkspaceConnectMessageSchema = z
  764. .object({
  765. type: z.literal("cancel-remote-workspace-connect"),
  766. requestId: nonEmptyStringSchema,
  767. })
  768. .strict();
  769. export const hostBindRemoteWorkspaceContextMessageSchema = z
  770. .object({
  771. type: z.literal("bind-remote-workspace-context"),
  772. requestId: nonEmptyStringSchema,
  773. remoteSessionId: nonEmptyStringSchema,
  774. workspacePath: nonEmptyStringSchema,
  775. workspaceIdentity: nonEmptyStringSchema,
  776. workspacePurpose: z.enum(["project", "conversation"]).optional(),
  777. legacyRouteHint: nonEmptyStringSchema.optional(),
  778. })
  779. .strict();
  780. export const hostCancelRemoteWorkspaceBindMessageSchema = z
  781. .object({
  782. type: z.literal("cancel-remote-workspace-bind"),
  783. requestId: nonEmptyStringSchema,
  784. remoteSessionId: nonEmptyStringSchema,
  785. })
  786. .strict();
  787. export const hostDisposeRemoteWorkspaceSessionMessageSchema = z
  788. .object({
  789. type: z.literal("dispose-remote-workspace-session"),
  790. requestId: nonEmptyStringSchema,
  791. remoteSessionId: nonEmptyStringSchema,
  792. })
  793. .strict();
  794. export const hostAttachServicePortMessageSchema = z
  795. .object({
  796. type: z.literal("attach-service-port"),
  797. terminalOwnerId: nonEmptyStringSchema.optional(),
  798. // main 只能声明 attachment 来源;connectionId 仍由 host process 分配。
  799. // desktop reload/remote reattach 必须显式 continuous,手机 shared-host 必须 replayable。
  800. requestId: nonEmptyStringSchema,
  801. attachmentId: nonEmptyStringSchema,
  802. clientMode: z.enum(["desktop-continuous", "web-remote-replayable"]),
  803. scope: windowHostAttachmentScopeSchema,
  804. })
  805. .strict();
  806. export const hostDetachServicePortMessageSchema = z.object({
  807. type: z.literal("detach-service-port"),
  808. attachmentId: nonEmptyStringSchema,
  809. });
  810. export const hostDisposeMessageSchema = z.object({
  811. type: z.literal("dispose"),
  812. });
  813. export const hostBroadcastEnvelopeSchema = z.object({
  814. type: z.literal("broadcast"),
  815. message: broadcastMessageSchema,
  816. });
  817. export const hostBroadcastClaimResultMessageSchema = z.discriminatedUnion("status", [
  818. z.object({
  819. type: z.literal("broadcast-claim-result"),
  820. requestId: nonEmptyStringSchema,
  821. status: z.literal("acquired"),
  822. claimToken: nonEmptyStringSchema,
  823. }),
  824. z.object({
  825. type: z.literal("broadcast-claim-result"),
  826. requestId: nonEmptyStringSchema,
  827. status: z.literal("busy"),
  828. retryAfterMs: z.number().int().nonnegative(),
  829. }),
  830. z.object({
  831. type: z.literal("broadcast-claim-result"),
  832. requestId: nonEmptyStringSchema,
  833. status: z.literal("committed"),
  834. }),
  835. ]);
  836. export const hostTaskRealtimeDeliverMessageSchema = z.object({
  837. type: z.literal("task-realtime-deliver"),
  838. event: taskRealtimeDeliveredEventSchema,
  839. });
  840. export const hostTaskRunLeaseResultMessageSchema = z.object({
  841. type: z.literal("task-run-lease-result"),
  842. result: taskRunLeaseResultSchema,
  843. });
  844. export const hostTaskOwnerCommandDeliverMessageSchema = z.object({
  845. type: z.literal("task-owner-command-deliver"),
  846. command: taskOwnerCommandDeliverySchema,
  847. });
  848. export const hostTaskOwnerCommandResultMessageSchema = z.object({
  849. type: z.literal("task-owner-command-result"),
  850. result: taskOwnerCommandResultSchema,
  851. });
  852. export const sessionMessageRequestSchema = z.object({
  853. content: nonEmptyStringSchema,
  854. createdAt: nonEmptyStringSchema,
  855. fromSessionId: nonEmptyStringSchema,
  856. messageId: nonEmptyStringSchema,
  857. requestId: nonEmptyStringSchema,
  858. toSessionId: nonEmptyStringSchema,
  859. });
  860. export const sessionMessageDeliveryResultSchema = z.object({
  861. error: z.string().optional(),
  862. messageId: nonEmptyStringSchema,
  863. requestId: nonEmptyStringSchema,
  864. sessionId: nonEmptyStringSchema,
  865. status: z.enum(["success", "failed"]),
  866. });
  867. export const sessionRouteSchema = z.object({
  868. sessionId: nonEmptyStringSchema,
  869. });
  870. export const hostSessionMessageDeliverMessageSchema = z.object({
  871. type: z.literal("session-message-deliver"),
  872. request: sessionMessageRequestSchema,
  873. });
  874. export const hostSessionMessageDeliveryResultMessageSchema = z.object({
  875. type: z.literal("session-message-delivery-result"),
  876. result: sessionMessageDeliveryResultSchema,
  877. });
  878. export const hostFeedbackLogArchiveResultMessageSchema = z.object({
  879. type: z.literal("feedback-log-archive-result"),
  880. requestId: nonEmptyStringSchema,
  881. ok: z.boolean(),
  882. path: z.string().optional(),
  883. size: z.number().int().nonnegative().optional(),
  884. error: z.string().optional(),
  885. });
  886. // main → host:定时任务到点派发。会话内 cron 带 targetTaskId 时直接 sendPrompt 到当前会话;
  887. // 历史未绑定任务才 fallback createTask + sendPrompt 建 session。
  888. export const hostCronRunMessageSchema = z.object({
  889. type: z.literal("cron-run"),
  890. automationId: nonEmptyStringSchema,
  891. runId: nonEmptyStringSchema,
  892. workspacePath: nonEmptyStringSchema,
  893. workspaceIdentity: z.string().optional(),
  894. projectId: nonEmptyStringSchema.nullable().optional(),
  895. hostId: nonEmptyStringSchema.optional(),
  896. additionalDirectories: z.array(nonEmptyStringSchema).max(256).optional(),
  897. prompt: nonEmptyStringSchema,
  898. targetTaskId: nonEmptyStringSchema.optional(),
  899. modelSelection: modelSelectionSchema.optional(),
  900. mode: z.string().optional(),
  901. });
  902. // main → host:闲时任务派发(仿 cron-run,字段独立不复用)。首跑不带 conversationId/sessionId,
  903. // host createTask 新建 session;3h 续跑 / 中断恢复带上两者 resume 同一会话。
  904. // serverTicketId 供 idle plan 适配层注入 X-Off-Peak-Ticket-ID 请求头(run 作用域)。
  905. export const hostOffPeakRunMessageSchema = z.object({
  906. type: z.literal("off-peak-run"),
  907. offPeakTaskId: nonEmptyStringSchema,
  908. workspacePath: nonEmptyStringSchema,
  909. workspaceIdentity: z.string().optional(),
  910. projectId: nonEmptyStringSchema.nullable().optional(),
  911. hostId: nonEmptyStringSchema.optional(),
  912. additionalDirectories: z.array(nonEmptyStringSchema).max(256).optional(),
  913. prompt: nonEmptyStringSchema,
  914. // 权限四档映射现有 ZCodeTaskMode;与 cron-run 的 mode 同样按宽松 string 传输
  915. permissionMode: nonEmptyStringSchema,
  916. modelSelection: modelSelectionSchema,
  917. conversationId: z.string().optional(),
  918. sessionId: z.string().optional(),
  919. serverTicketId: z.string().optional(),
  920. });
  921. // main → host:browser-use 命令执行结果(按 requestId 关联到 host 的 pending)。
  922. export const hostBrowserExecuteResultMessageSchema = z.object({
  923. type: z.literal("browser-execute-result"),
  924. requestId: nonEmptyStringSchema,
  925. result: browserCommandResultSchema,
  926. });
  927. export const hostCredentialCipherResultMessageSchema = credentialCipherReplySchema
  928. .extend({
  929. type: z.literal("credential-cipher-result"),
  930. })
  931. .strict();
  932. export const hostCredentialCipherRequestResponseSchema = credentialCipherRequestSchema
  933. .safeExtend({
  934. type: z.literal("credential-cipher-request"),
  935. })
  936. .strict();
  937. /** 目标数据根路径上限:覆盖 Windows 长路径,同时限制私有通道载荷。 */
  938. const CREDENTIAL_KEY_SHARE_TARGET_MAX_CHARS = 32_767;
  939. export const CREDENTIAL_KEY_SHARE_UNAVAILABLE_ERROR_CODE = "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE";
  940. // Host → Main:数据存储路径切换后请求登记系统密钥。路径保持原值,不做 trim 等改写。
  941. export const hostCredentialKeyShareRequestResponseSchema = z
  942. .object({
  943. type: z.literal("credential-key-share-request"),
  944. requestId: z.string().uuid(),
  945. targetBaseDir: z.string().min(1).max(CREDENTIAL_KEY_SHARE_TARGET_MAX_CHARS),
  946. })
  947. .strict();
  948. // Main → Host:登记结果。失败只返回受控错误码,原生异常不穿过通道。
  949. export const hostCredentialKeyShareResultMessageSchema = z
  950. .object({
  951. type: z.literal("credential-key-share-result"),
  952. requestId: z.string().uuid(),
  953. ok: z.boolean(),
  954. errorCode: z.literal(CREDENTIAL_KEY_SHARE_UNAVAILABLE_ERROR_CODE).optional(),
  955. })
  956. .strict();
  957. export const hostLocalMediaPreviewPathAuthorizeResultMessageSchema = z
  958. .object({
  959. type: z.literal("local-media-preview-path-authorize-result"),
  960. requestId: nonEmptyStringSchema,
  961. ok: z.boolean(),
  962. path: nonEmptyStringSchema.optional(),
  963. error: z.string().optional(),
  964. })
  965. .strict();
  966. /** main → host:插件 UI 沙箱登记结果(PluginSandboxRegisterResultPayload)。 */
  967. export const hostPluginSandboxRegisterResultMessageSchema = z
  968. .object({
  969. type: z.literal("plugin-sandbox-register-result"),
  970. requestId: nonEmptyStringSchema,
  971. ok: z.boolean(),
  972. instance: mcpAppInstanceSchema.optional(),
  973. sandboxId: nonEmptyStringSchema.optional(),
  974. initId: z.number().int().nonnegative().optional(),
  975. shellUrl: nonEmptyStringSchema.optional(),
  976. partition: nonEmptyStringSchema.optional(),
  977. // 登记时生效的呈现字段(资源级优先合并后的值),回 renderer 定初始高度 / 边框。
  978. // Bugfix:这条 schema 是 strict 的——句柄多带一个未声明字段,整条回包会被 host 拒收,桥永远等不到句柄,
  979. // 卡片卡在 preparing(2026-09-12 inline e2e 复现)。改 PluginSandboxHandle 必须同步这里。
  980. resourceMeta: z
  981. .object({
  982. prefersBorder: z.boolean().optional(),
  983. heightHint: z.number().int().positive().optional(),
  984. minFrameHeight: z.number().int().positive().optional(),
  985. showInline: z.boolean().optional(),
  986. backgroundRetention: z.boolean().optional(),
  987. // 资源声明的浏览器权限随句柄回 renderer(进 hostContext.permissions);与登记请求的 permissions 同一枚举。
  988. permissions: z
  989. .array(z.enum(["camera", "microphone", "geolocation", "clipboardWrite"]))
  990. .optional(),
  991. })
  992. .strict()
  993. .optional(),
  994. error: z.string().optional(),
  995. })
  996. .strict();
  997. export const hostCuaPipFocusChangedMessageSchema = z
  998. .object({
  999. type: z.literal("cua-pip-focus-changed"),
  1000. event: z
  1001. .object({
  1002. kind: z.literal("focus-changed"),
  1003. revision: z.number().int().nonnegative().safe(),
  1004. sourceWindowId: nonEmptyStringSchema.max(255),
  1005. sessionId: nonEmptyStringSchema.max(255).nullable(),
  1006. })
  1007. .strict(),
  1008. })
  1009. .strict();
  1010. export const hostApplicationLocaleChangedMessageSchema = z
  1011. .object({
  1012. type: z.literal("application-locale-changed"),
  1013. locale: localeSchema,
  1014. })
  1015. .strict();
  1016. export const hostReplyLanguageChangedMessageSchema = z
  1017. .object({
  1018. type: z.literal("reply-language-changed"),
  1019. replyLanguage: replyLanguageSchema.nullable(),
  1020. })
  1021. .strict();
  1022. export const hostProviderProvisioningExecuteMessageSchema = z
  1023. .object({
  1024. type: z.literal("provider-provisioning-execute"),
  1025. requestId: nonEmptyStringSchema,
  1026. environmentKey: nonEmptyStringSchema,
  1027. remoteSessionId: nonEmptyStringSchema,
  1028. trigger: providerProvisioningTriggerSchema,
  1029. })
  1030. .strict();
  1031. /** main → host:数据同步页读取 / 重试 Provisioning lane 的结果(按 requestId 关联)。 */
  1032. export const hostProviderProvisioningLaneResultMessageSchema = z
  1033. .object({
  1034. type: z.literal("provider-provisioning-lane-result"),
  1035. requestId: nonEmptyStringSchema,
  1036. status: providerProvisioningLaneStatusSchema,
  1037. })
  1038. .strict();
  1039. /** 手机只提交项目意图;实际目录和远端 scope 必须由窗口 Host 准备。 */
  1040. export const hostPrepareProjectWorkspaceMessageSchema = z
  1041. .object({
  1042. type: z.literal("prepare-project-workspace"),
  1043. requestId: nonEmptyStringSchema,
  1044. clientMode: z.literal("web-remote-replayable"),
  1045. projectId: nonEmptyStringSchema.nullable().optional(),
  1046. hostId: nonEmptyStringSchema.optional(),
  1047. draftId: z.string().uuid().optional(),
  1048. reuseDraft: z.boolean().optional(),
  1049. task: z
  1050. .object({ taskId: nonEmptyStringSchema, workspaceKey: nonEmptyStringSchema })
  1051. .strict()
  1052. .optional(),
  1053. })
  1054. .strict()
  1055. .refine(
  1056. (request) => (request.task ? request.projectId === undefined : request.projectId !== undefined),
  1057. "Exactly one task or draft intent is required",
  1058. )
  1059. .refine(
  1060. (request) =>
  1061. (!request.draftId || request.projectId === null) &&
  1062. (!request.reuseDraft || Boolean(request.draftId)),
  1063. "Only an unclassified draft can reuse its directory",
  1064. );
  1065. export type HostProjectWorkspaceNavigationInput = Pick<
  1066. z.infer<typeof hostPrepareProjectWorkspaceMessageSchema>,
  1067. "projectId" | "hostId" | "task" | "draftId" | "reuseDraft"
  1068. >;
  1069. export const hostProjectWorkspacePreparedValueSchema = z
  1070. .object({
  1071. hostId: nonEmptyStringSchema,
  1072. projectId: nonEmptyStringSchema.nullable(),
  1073. workspacePath: nonEmptyStringSchema,
  1074. workspaceIdentity: nonEmptyStringSchema.optional(),
  1075. additionalDirectories: z.array(nonEmptyStringSchema),
  1076. remote: windowHostRemoteWorkspaceDescriptorSchema.optional(),
  1077. })
  1078. .strict();
  1079. export type HostPreparedProjectWorkspace = z.infer<typeof hostProjectWorkspacePreparedValueSchema>;
  1080. export const hostProjectWorkspacePreparedResponseSchema = z
  1081. .object({
  1082. type: z.literal("project-workspace-prepared"),
  1083. requestId: nonEmptyStringSchema,
  1084. result: z.discriminatedUnion("ok", [
  1085. z.object({ ok: z.literal(true), value: hostProjectWorkspacePreparedValueSchema }).strict(),
  1086. z.object({ ok: z.literal(false), error: nonEmptyStringSchema }).strict(),
  1087. ]),
  1088. })
  1089. .strict();
  1090. export const hostResourceUsageSnapshotRequestMessageSchema = z
  1091. .object({
  1092. type: z.literal("resource-usage-snapshot-request"),
  1093. requestId: nonEmptyStringSchema,
  1094. })
  1095. .strict();
  1096. export type HostResourceUsageSnapshotRequestMessage = z.infer<
  1097. typeof hostResourceUsageSnapshotRequestMessageSchema
  1098. >;
  1099. export const hostIncomingMessageSchema = z.discriminatedUnion("type", [
  1100. hostPrepareProjectWorkspaceMessageSchema,
  1101. z.object({ type: z.literal("network-capture"), control: networkCaptureControlSchema }).strict(),
  1102. z
  1103. .object({ type: z.literal("database-startup-control"), control: databaseStartupControlSchema })
  1104. .strict(),
  1105. hostResourceUsageSnapshotRequestMessageSchema,
  1106. z
  1107. .object({ type: z.literal("resource-usage-snapshot-cancel"), requestId: nonEmptyStringSchema })
  1108. .strict(),
  1109. hostInitLocalMessageSchema,
  1110. hostConnectRemoteWorkspaceMessageSchema,
  1111. hostCancelRemoteWorkspaceConnectMessageSchema,
  1112. hostBindRemoteWorkspaceContextMessageSchema,
  1113. hostCancelRemoteWorkspaceBindMessageSchema,
  1114. hostDisposeRemoteWorkspaceSessionMessageSchema,
  1115. z
  1116. .object({ type: z.literal("set-terminal-owner"), ownerId: nonEmptyStringSchema.nullable() })
  1117. .strict(),
  1118. hostAttachServicePortMessageSchema,
  1119. hostDetachServicePortMessageSchema,
  1120. hostDisposeMessageSchema,
  1121. hostBroadcastEnvelopeSchema,
  1122. hostBroadcastClaimResultMessageSchema,
  1123. hostTaskRealtimeDeliverMessageSchema,
  1124. hostTaskRunLeaseResultMessageSchema,
  1125. hostTaskOwnerCommandDeliverMessageSchema,
  1126. hostTaskOwnerCommandResultMessageSchema,
  1127. hostSessionMessageDeliverMessageSchema,
  1128. hostSessionMessageDeliveryResultMessageSchema,
  1129. hostFeedbackLogArchiveResultMessageSchema,
  1130. hostCronRunMessageSchema,
  1131. hostOffPeakRunMessageSchema,
  1132. hostBrowserExecuteResultMessageSchema,
  1133. hostLocalMediaPreviewPathAuthorizeResultMessageSchema,
  1134. hostCredentialCipherResultMessageSchema,
  1135. hostCredentialKeyShareResultMessageSchema,
  1136. hostPluginSandboxRegisterResultMessageSchema,
  1137. hostCuaPipFocusChangedMessageSchema,
  1138. hostApplicationLocaleChangedMessageSchema,
  1139. hostReplyLanguageChangedMessageSchema,
  1140. hostProviderProvisioningExecuteMessageSchema,
  1141. hostProviderProvisioningLaneResultMessageSchema,
  1142. ]);
  1143. export const hostRemoteWorkspaceConnectedResponseSchema = z
  1144. .object({
  1145. type: z.literal("remote-workspace-connected"),
  1146. requestId: nonEmptyStringSchema,
  1147. descriptor: windowHostRemoteWorkspaceDescriptorSchema,
  1148. })
  1149. .strict();
  1150. export const hostRemoteWorkspaceContextBoundResponseSchema = z
  1151. .object({
  1152. type: z.literal("remote-workspace-context-bound"),
  1153. requestId: nonEmptyStringSchema,
  1154. // Desktop tab rekey only;手机 replayable attachment 不消费该提示。
  1155. previousWorkspaceIdentity: nonEmptyStringSchema.optional(),
  1156. })
  1157. .strict();
  1158. export const hostRemoteWorkspaceContextBindFailedResponseSchema = z
  1159. .object({
  1160. type: z.literal("remote-workspace-context-bind-failed"),
  1161. requestId: nonEmptyStringSchema,
  1162. error: nonEmptyStringSchema,
  1163. reasonCode: nonEmptyStringSchema.optional(),
  1164. retryable: z.boolean().optional(),
  1165. })
  1166. .strict();
  1167. export const hostRemoteWorkspaceReconnectedResponseSchema = z
  1168. .object({
  1169. type: z.literal("remote-workspace-reconnected"),
  1170. previousRemoteSessionId: nonEmptyStringSchema,
  1171. descriptor: windowHostRemoteWorkspaceDescriptorSchema,
  1172. })
  1173. .strict();
  1174. export const hostRemoteWorkspaceConnectionLogResponseSchema = z
  1175. .object({
  1176. type: z.literal("remote-workspace-connection-log"),
  1177. requestId: nonEmptyStringSchema,
  1178. level: z.enum(["info", "warn", "error"]),
  1179. message: nonEmptyStringSchema,
  1180. })
  1181. .strict();
  1182. export const hostRemoteWorkspaceConnectFailedResponseSchema = z
  1183. .object({
  1184. type: z.literal("remote-workspace-connect-failed"),
  1185. requestId: nonEmptyStringSchema,
  1186. error: nonEmptyStringSchema,
  1187. reasonCode: nonEmptyStringSchema.optional(),
  1188. retryable: z.boolean().optional(),
  1189. profileId: z.string().uuid().optional(),
  1190. resolvedWslTarget: z
  1191. .object({
  1192. kind: z.literal("wsl"),
  1193. distro: nonEmptyStringSchema,
  1194. user: wslUserSchema.refine((value) => value.length > 0),
  1195. })
  1196. .strict()
  1197. .optional(),
  1198. })
  1199. .strict();
  1200. export const hostRemoteWorkspaceClosedResponseSchema = z
  1201. .object({
  1202. type: z.literal("remote-workspace-closed"),
  1203. remoteSessionId: nonEmptyStringSchema,
  1204. reason: z.enum(["connection-closed", "disposed", "connect-cancelled"]),
  1205. exitCode: z.number().int().nullable().optional(),
  1206. signal: z.string().nullable().optional(),
  1207. error: z.string().optional(),
  1208. recoverable: z.boolean().optional(),
  1209. recoveryAttempt: z.number().int().positive().optional(),
  1210. recoveryLimit: z.number().int().positive().optional(),
  1211. recoveryBudgetExhausted: z.boolean().optional(),
  1212. reasonCode: nonEmptyStringSchema.optional(),
  1213. retryable: z.boolean().optional(),
  1214. })
  1215. .strict();
  1216. export const hostLogResponseSchema = z.object({
  1217. type: z.literal("log"),
  1218. level: z.enum(["info", "warn", "error"]),
  1219. source: z.string(),
  1220. message: z.string(),
  1221. });
  1222. export { zcodeProviderSchema };
  1223. export const zcodeTaskMigrationSourceSchema = z.enum(["claudeCode"]);
  1224. export const hostAgentProcessSpawnedResponseSchema = z.object({
  1225. type: z.literal("agent-process-spawned"),
  1226. /** 进程泳道(mcp-status 等),旧 Host 不带该字段。 */
  1227. lane: nonEmptyStringSchema.optional(),
  1228. pid: z.number().int().positive(),
  1229. provider: zcodeProviderSchema,
  1230. workspacePath: nonEmptyStringSchema,
  1231. command: z.string(),
  1232. args: z.array(z.string()),
  1233. startedAt: z.number().int().nonnegative(),
  1234. runtimeGeneration: z.number().int().positive().optional(),
  1235. runtimeInstanceId: nonEmptyStringSchema.optional(),
  1236. });
  1237. export type HostAgentProcessSpawnedResponse = z.infer<typeof hostAgentProcessSpawnedResponseSchema>;
  1238. export const hostAgentProcessReadyResponseSchema = z.object({
  1239. type: z.literal("agent-process-ready"),
  1240. /** 进程泳道(mcp-status 等),旧 Host 不带该字段。 */
  1241. lane: nonEmptyStringSchema.optional(),
  1242. pid: z.number().int().positive(),
  1243. provider: zcodeProviderSchema,
  1244. workspacePath: nonEmptyStringSchema,
  1245. readyAt: z.number().int().nonnegative(),
  1246. startupDurationMs: z.number().int().nonnegative(),
  1247. runtimeGeneration: z.number().int().positive(),
  1248. runtimeInstanceId: nonEmptyStringSchema,
  1249. });
  1250. export type HostAgentProcessReadyResponse = z.infer<typeof hostAgentProcessReadyResponseSchema>;
  1251. export const hostAgentProcessExitedResponseSchema = z.object({
  1252. type: z.literal("agent-process-exited"),
  1253. /** 进程泳道(mcp-status 等),旧 Host 不带该字段。 */
  1254. lane: nonEmptyStringSchema.optional(),
  1255. pid: z.number().int().positive(),
  1256. provider: zcodeProviderSchema,
  1257. workspacePath: nonEmptyStringSchema,
  1258. exitCode: z.number().int().nullable(),
  1259. signal: z.string().nullable(),
  1260. endedAt: z.number().int().nonnegative(),
  1261. terminationKind: z.enum(["expected", "unexpected", "watchdog_recycle"]),
  1262. terminationReason: z.string().optional(),
  1263. /** rolling-upgrade 兼容:旧 Host 缺字段时 desktop 映射 crash_phase=unknown。 */
  1264. runtimeReady: z.boolean().optional(),
  1265. runtimeGeneration: z.number().int().positive(),
  1266. runtimeInstanceId: nonEmptyStringSchema.optional(),
  1267. uptimeMs: z.number().int().nonnegative(),
  1268. stderrLineCount: z.number().int().nonnegative(),
  1269. stderrTail: z.array(z.string().max(1_100)).max(20).optional(),
  1270. });
  1271. export type HostAgentProcessExitedResponse = z.infer<typeof hostAgentProcessExitedResponseSchema>;
  1272. export const hostAgentProcessErrorResponseSchema = z.object({
  1273. type: z.literal("agent-process-error"),
  1274. /** 进程泳道(mcp-status 等),旧 Host 不带该字段。 */
  1275. lane: nonEmptyStringSchema.optional(),
  1276. pid: z.number().int().positive().nullable(),
  1277. provider: zcodeProviderSchema,
  1278. workspacePath: nonEmptyStringSchema,
  1279. command: z.string(),
  1280. args: z.array(z.string()),
  1281. errorName: nonEmptyStringSchema,
  1282. errorCode: z.string().optional(),
  1283. errorMessage: z.string(),
  1284. errorStack: z.string().optional(),
  1285. runtimeGeneration: z.number().int().positive(),
  1286. runtimeInstanceId: nonEmptyStringSchema.optional(),
  1287. occurredAt: z.number().int().nonnegative(),
  1288. });
  1289. export type HostAgentProcessErrorResponse = z.infer<typeof hostAgentProcessErrorResponseSchema>;
  1290. export const hostAgentProcessExceptionResponseSchema = z
  1291. .object({
  1292. type: z.literal("agent-process-exception"),
  1293. lane: nonEmptyStringSchema.optional(),
  1294. pid: z.number().int().positive(),
  1295. provider: zcodeProviderSchema,
  1296. workspacePath: nonEmptyStringSchema,
  1297. runtimeGeneration: z.number().int().positive(),
  1298. runtimeInstanceId: nonEmptyStringSchema,
  1299. diagnostic: zcodeProcessDiagnosticSchema,
  1300. })
  1301. .strict();
  1302. export type HostAgentProcessExceptionResponse = z.infer<
  1303. typeof hostAgentProcessExceptionResponseSchema
  1304. >;
  1305. /**
  1306. * services 打标后的 CLI 资源样本。
  1307. *
  1308. * `lane` 不是 CLI 协议字段:CLI 进程不知道自己被哪个进程管理器拉起,由 services 层在解析
  1309. * 协议样本时按所属进程管理器补上。样本自身仍按 CLI 协议 schema 严格校验,因此 CLI 自报 lane
  1310. * 会被协议层直接拒绝。`lane` 可选是为了兼容版本落后、还没打标的远端 server。
  1311. */
  1312. export const processResourceCliLaneSchema = z.enum(PROCESS_RESOURCE_CLI_LANES);
  1313. export const agentLaneResourceSampleSchema = zcodeProcessResourceSampleSchema
  1314. .extend({ lane: processResourceCliLaneSchema.optional() })
  1315. .strict();
  1316. export type AgentLaneResourceSample = z.infer<typeof agentLaneResourceSampleSchema>;
  1317. /** Host 仅传运行环境的 SHA-256 哈希,避免原始主机、用户或 URL 进入消息与日志。 */
  1318. const resourceTelemetryEnvironmentKeySchema = z.string().regex(/^[a-f0-9]{64}$/);
  1319. export const hostAgentResourceSampleResponseSchema = z
  1320. .object({
  1321. type: z.literal("agent-resource-sample"),
  1322. runtimeSurface: z.enum(["local", "remote"]),
  1323. environmentKey: resourceTelemetryEnvironmentKeySchema.optional(),
  1324. sample: agentLaneResourceSampleSchema,
  1325. })
  1326. .strict();
  1327. export type HostAgentResourceSampleResponse = z.infer<typeof hostAgentResourceSampleResponseSchema>;
  1328. /**
  1329. * Node 进程(host / scheduler)每 60 秒自采的瞬时事实
  1330. *
  1331. * 只带这三项:CPU 与 RSS 由 main 的 `getAppMetrics()` 负责,heap 只有进程自己读得到。
  1332. */
  1333. export const nodeSelfResourceSampleSchema = z
  1334. .object({
  1335. /**
  1336. * 整机归一化 CPU 百分比,100 表示所有逻辑核占满。
  1337. * 上限刻意放宽(与 CLI 的 `zcodeProcessResourceSampleSchema` 同口径):读数异常时宁可让
  1338. * 样本带着离谱数值上去、由平台侧数值异常规则暴露,也不在客户端静默丢样本。
  1339. */
  1340. cpuPercent: z.number().finite().nonnegative().max(100_000),
  1341. rssKb: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
  1342. heapUsedKb: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
  1343. })
  1344. .strict();
  1345. export type NodeSelfResourceSample = z.infer<typeof nodeSelfResourceSampleSchema>;
  1346. /**
  1347. * 主窗口 renderer 每 60 秒经 preload 桥送 main 的 heap 读数
  1348. *
  1349. * 只带 heap:renderer 的 CPU 与 RSS 由 main 的 `getAppMetrics()` 负责,
  1350. * renderer 自己也读不到。`strict` 保证 UI 侧不会顺手夹带路径、session 等隐私字段。
  1351. */
  1352. export const rendererHeapSampleSchema = z
  1353. .object({
  1354. heapUsedKb: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER),
  1355. })
  1356. .strict();
  1357. export type RendererHeapSample = z.infer<typeof rendererHeapSampleSchema>;
  1358. export const hostResourceSampleResponseSchema = z
  1359. .object({
  1360. type: z.literal("host-resource-sample"),
  1361. sample: nodeSelfResourceSampleSchema,
  1362. })
  1363. .strict();
  1364. export type HostResourceSampleResponse = z.infer<typeof hostResourceSampleResponseSchema>;
  1365. export const hostMcpResourceSamplesResponseSchema = z
  1366. .object({
  1367. type: z.literal("mcp-resource-samples"),
  1368. runtimeSurface: z.enum(["local", "remote"]),
  1369. environmentKey: resourceTelemetryEnvironmentKeySchema.optional(),
  1370. samples: zcodeMcpResourceSamplesSchema,
  1371. })
  1372. .strict();
  1373. export type HostMcpResourceSamplesResponse = z.infer<typeof hostMcpResourceSamplesResponseSchema>;
  1374. export const hostToolExecResourceResponseSchema = z
  1375. .object({
  1376. type: z.literal("tool-exec-resource"),
  1377. runtimeSurface: z.enum(["local", "remote"]),
  1378. sample: zcodeToolExecResourceSchema,
  1379. })
  1380. .strict();
  1381. export type HostToolExecResourceResponse = z.infer<typeof hostToolExecResourceResponseSchema>;
  1382. export const hostMcpTelemetryResponseSchema = z
  1383. .object({
  1384. type: z.literal("mcp-telemetry"),
  1385. runtimeSurface: z.enum(["local", "remote"]),
  1386. event: zcodeMcpTelemetryEventSchema,
  1387. })
  1388. .strict();
  1389. export type HostMcpTelemetryResponse = z.infer<typeof hostMcpTelemetryResponseSchema>;
  1390. export const hostPluginTelemetryResponseSchema = z
  1391. .object({
  1392. type: z.literal("plugin-telemetry"),
  1393. event: rendererTelemetryEventPayloadSchema.refine((event) =>
  1394. ["plugin_lifecycle", "plugin_discovery", "plugin_usage", "plugin_runtime_error"].includes(
  1395. event.elementName,
  1396. ),
  1397. ),
  1398. })
  1399. .strict();
  1400. export type HostPluginTelemetryResponse = z.infer<typeof hostPluginTelemetryResponseSchema>;
  1401. export const hostRemoteConversationTelemetryResponseSchema = z
  1402. .object({
  1403. type: z.literal("remote-conversation-telemetry"),
  1404. event: remoteConversationTelemetryEventSchema,
  1405. })
  1406. .strict();
  1407. export type HostRemoteConversationTelemetryResponse = z.infer<
  1408. typeof hostRemoteConversationTelemetryResponseSchema
  1409. >;
  1410. export const hostSessionCreateTelemetryResponseSchema = z
  1411. .object({
  1412. type: z.literal("session-create-telemetry"),
  1413. event: automationSessionCreateTelemetrySchema,
  1414. })
  1415. .strict();
  1416. export type HostSessionCreateTelemetryResponse = z.infer<
  1417. typeof hostSessionCreateTelemetryResponseSchema
  1418. >;
  1419. export const hostAgentRunningTaskCountChangedResponseSchema = z.object({
  1420. type: z.literal("agent-running-task-count-changed"),
  1421. runningTaskCount: z.number().int().nonnegative(),
  1422. });
  1423. /**
  1424. * 关闭窗口或退出应用会中断、且无法恢复的 Host 事项(docs/git/worktree.md §6.4)。
  1425. * 第一版只有"正在新 worktree 中启动的任务";以后可加入其他会被关闭中断的 Host 任务。
  1426. */
  1427. export const hostQuitBlockerSchema = z.object({
  1428. kind: z.enum(["worktree-creating"]),
  1429. count: z.number().int().positive(),
  1430. });
  1431. export type HostQuitBlocker = z.infer<typeof hostQuitBlockerSchema>;
  1432. export const hostQuitBlockersChangedResponseSchema = z.object({
  1433. type: z.literal("quit-blockers-changed"),
  1434. /** 当前完整集合;空数组表示没有阻止退出的事项。 */
  1435. blockers: z.array(hostQuitBlockerSchema),
  1436. });
  1437. export const hostWorkspaceRunningTaskCountChangedResponseSchema = z.object({
  1438. type: z.literal("workspace-running-task-count-changed"),
  1439. workspacePath: nonEmptyStringSchema,
  1440. workspaceIdentity: nonEmptyStringSchema.optional(),
  1441. runningTaskCount: z.number().int().nonnegative(),
  1442. });
  1443. export const hostCuaOperationStateResponseSchema = z
  1444. .object({
  1445. type: z.literal("cua-operation-state"),
  1446. active: z.boolean(),
  1447. sessionId: nonEmptyStringSchema,
  1448. turnId: nonEmptyStringSchema,
  1449. workspacePath: nonEmptyStringSchema,
  1450. workspaceIdentity: nonEmptyStringSchema.optional(),
  1451. })
  1452. .strict();
  1453. export type HostCuaOperationStateResponse = z.infer<typeof hostCuaOperationStateResponseSchema>;
  1454. export const hostBroadcastClaimRequestResponseSchema = z.object({
  1455. type: z.literal("broadcast-claim-request"),
  1456. requestId: nonEmptyStringSchema,
  1457. key: nonEmptyStringSchema.max(1_024),
  1458. });
  1459. export const hostBroadcastClaimCommitResponseSchema = z.object({
  1460. type: z.literal("broadcast-claim-commit"),
  1461. key: nonEmptyStringSchema.max(1_024),
  1462. claimToken: nonEmptyStringSchema,
  1463. });
  1464. export const hostBroadcastClaimReleaseResponseSchema = z.object({
  1465. type: z.literal("broadcast-claim-release"),
  1466. key: nonEmptyStringSchema.max(1_024),
  1467. claimToken: nonEmptyStringSchema,
  1468. });
  1469. export const hostTaskRealtimePublishResponseSchema = z.object({
  1470. type: z.literal("task-realtime-publish"),
  1471. event: taskRealtimeEventSchema,
  1472. });
  1473. export const hostTaskStreamOpPublishResponseSchema = z.object({
  1474. type: z.literal("task-stream-op-publish"),
  1475. target: taskStreamMirrorTargetSchema,
  1476. op: taskStreamMirrorPublishOpSchema,
  1477. });
  1478. export const hostTaskRunLeaseAcquireResponseSchema = z.object({
  1479. type: z.literal("task-run-lease-acquire"),
  1480. request: taskRunLeaseAcquireRequestSchema,
  1481. });
  1482. export const hostTaskRunLeaseReleaseResponseSchema = z.object({
  1483. type: z.literal("task-run-lease-release"),
  1484. target: taskRunLeaseTargetSchema,
  1485. });
  1486. export const hostTaskOwnerCommandRequestResponseSchema = z.object({
  1487. type: z.literal("task-owner-command-request"),
  1488. command: taskOwnerCommandRequestSchema,
  1489. });
  1490. export const hostTaskOwnerCommandResultResponseSchema = z.object({
  1491. type: z.literal("task-owner-command-result"),
  1492. result: taskOwnerCommandResultSchema,
  1493. });
  1494. export const hostSessionMessageSendRequestedResponseSchema = z.object({
  1495. type: z.literal("session-message-send-requested"),
  1496. request: sessionMessageRequestSchema,
  1497. });
  1498. export const hostSessionRouteAnnounceResponseSchema = z.object({
  1499. type: z.literal("session-route-announce"),
  1500. route: sessionRouteSchema,
  1501. });
  1502. export const hostSessionMessageDeliverResultResponseSchema = z.object({
  1503. type: z.literal("session-message-deliver-result"),
  1504. result: sessionMessageDeliveryResultSchema,
  1505. });
  1506. export const hostFeedbackLogArchiveRequestResponseSchema = z.object({
  1507. type: z.literal("feedback-log-archive-request"),
  1508. requestId: nonEmptyStringSchema,
  1509. sourceDir: nonEmptyStringSchema,
  1510. });
  1511. // host → main:定时任务派发结果。ok=已成功创建 session 且 prompt 已发出。
  1512. export const hostCronRunResultResponseSchema = z.object({
  1513. type: z.literal("cron-run-result"),
  1514. runId: nonEmptyStringSchema,
  1515. ok: z.boolean(),
  1516. taskId: z.string().optional(),
  1517. sessionId: z.string().optional(),
  1518. error: z.string().optional(),
  1519. failureKind: z.enum(["transient", "permanent"]).optional(),
  1520. });
  1521. // host → main:闲时任务派发结果。ok=session 已确保存在且 prompt 已发出;迟到结果用 offPeakTaskId 兜底结算。
  1522. export const hostOffPeakRunResultResponseSchema = z.object({
  1523. type: z.literal("off-peak-run-result"),
  1524. offPeakTaskId: nonEmptyStringSchema,
  1525. ok: z.boolean(),
  1526. /** Host 已在开放 CLI 生命周期事件前完成接纳落库;调度器只清理退避。 */
  1527. lifecycleManaged: z.literal(true).optional(),
  1528. conversationId: z.string().optional(),
  1529. sessionId: z.string().optional(),
  1530. error: z.string().optional(),
  1531. failureKind: z.enum(["transient", "permanent"]).optional(),
  1532. });
  1533. // host → main:manual run 落库后的 scheduler 唤醒请求;业务数据仍由 scheduler 从 sqlite 读取。
  1534. export const hostCronSchedulerWakeRequestResponseSchema = z.object({
  1535. type: z.literal("cron-scheduler-wake-request"),
  1536. automationId: nonEmptyStringSchema,
  1537. });
  1538. // host → main:闲时任务 schedulable 翻转后的 scheduler 唤醒;业务数据仍由 scheduler 从 sqlite 读取。
  1539. export const hostOffPeakSchedulerWakeRequestResponseSchema = z.object({
  1540. type: z.literal("off-peak-scheduler-wake-request"),
  1541. offPeakTaskId: z.string().optional(),
  1542. });
  1543. // host → main:执行一条 browser-use 命令(main 用 WebContentsView+CDP 执行)。
  1544. export const hostBrowserExecuteRequestResponseSchema = z.object({
  1545. controlScopeId: nonEmptyStringSchema.optional(),
  1546. type: z.literal("browser-execute-request"),
  1547. requestId: nonEmptyStringSchema,
  1548. // 迁移兼容:旧 host bundle 没有 browserId/context;新 browser-client 链路始终携带。
  1549. browserId: nonEmptyStringSchema.optional(),
  1550. browserGeneration: z.number().int().nonnegative().optional(),
  1551. sessionId: nonEmptyStringSchema,
  1552. turnId: nonEmptyStringSchema.optional(),
  1553. workspaceKey: nonEmptyStringSchema.optional(),
  1554. workspacePath: nonEmptyStringSchema.optional(),
  1555. workspaceIdentity: nonEmptyStringSchema.optional(),
  1556. remoteSessionId: nonEmptyStringSchema.optional(),
  1557. clientMode: z.enum(["desktop-continuous", "web-remote-replayable"]).optional(),
  1558. sessionContext: z.enum(["live", "cached"]).optional(),
  1559. command: browserCommandSchema,
  1560. });
  1561. export const hostLocalMediaPreviewPathAuthorizeRequestResponseSchema = z
  1562. .object({
  1563. type: z.literal("local-media-preview-path-authorize-request"),
  1564. requestId: nonEmptyStringSchema,
  1565. path: nonEmptyStringSchema,
  1566. })
  1567. .strict();
  1568. /** host → main:登记已校验的插件 UI HTML。 */
  1569. export const hostPluginSandboxRegisterRequestResponseSchema = z
  1570. .object({
  1571. type: z.literal("plugin-sandbox-register-request"),
  1572. instance: mcpAppInstanceSchema,
  1573. requestId: nonEmptyStringSchema,
  1574. workspacePath: z.string().optional(),
  1575. workspaceIdentity: z.string().optional(),
  1576. ownerWebContentsId: z.number().int().nonnegative(),
  1577. // 只有扩展视图不属于会话(docs/plugins/extension-host.md §8),见下方 refine。
  1578. sessionId: nonEmptyStringSchema.optional(),
  1579. contentKind: z.enum(["gen-ui", "extension"]).optional(),
  1580. pluginId: nonEmptyStringSchema.optional(),
  1581. // 资源所属 MCP server 运行时名:沙箱 partition 按它派生。
  1582. serverName: nonEmptyStringSchema.optional(),
  1583. // 沙箱作用域 id(`tool:<toolCallId>` / `surface:<surfaceId>`),main 只当不透明字符串。
  1584. scopeId: nonEmptyStringSchema,
  1585. html: z.string(),
  1586. // MCP Apps 资源级 CSP 的四类域;与 mcp-apps 的 mcpToolUiCspSchema 同步。
  1587. csp: z
  1588. .object({
  1589. connectDomains: z.array(z.string()).optional(),
  1590. resourceDomains: z.array(z.string()).optional(),
  1591. frameDomains: z.array(z.string()).optional(),
  1592. baseUriDomains: z.array(z.string()).optional(),
  1593. })
  1594. .strict()
  1595. .optional(),
  1596. // 资源级 `_meta["zcode/csp"]` 放宽项;与 mcp-apps 的 mcpAppCspRelaxationsSchema 同步。
  1597. cspRelaxations: z
  1598. .object({ unsafeEval: z.boolean().optional(), wasmUnsafeEval: z.boolean().optional() })
  1599. .strict()
  1600. .optional(),
  1601. // 资源级 `_meta.ui.permissions`(规范四键);与 mcp-apps 的 MCP_APPS_RESOURCE_PERMISSIONS 同步。
  1602. permissions: z
  1603. .array(z.enum(["camera", "microphone", "geolocation", "clipboardWrite"]))
  1604. .optional(),
  1605. prefersBorder: z.boolean().optional(),
  1606. // 资源级尺寸提示,main 原样放进句柄的 resourceMeta。strict schema:改 PluginSandboxRegisterRequestPayload 必须同步这里。
  1607. heightHint: z.number().int().positive().optional(),
  1608. minFrameHeight: z.number().int().positive().optional(),
  1609. showInline: z.boolean().optional(),
  1610. backgroundRetention: z.boolean().optional(),
  1611. })
  1612. .strict()
  1613. .refine(
  1614. (value) =>
  1615. value.contentKind === "extension"
  1616. ? // 扩展视图:按插件归属,没有会话与 MCP server 名,也不能带原生权限。
  1617. Boolean(value.pluginId) &&
  1618. !value.sessionId &&
  1619. !value.serverName &&
  1620. !value.permissions?.length
  1621. : Boolean(value.sessionId) &&
  1622. (value.contentKind === "gen-ui"
  1623. ? !value.pluginId && !value.serverName && !value.permissions?.length
  1624. : Boolean(value.pluginId && value.serverName)),
  1625. "Invalid sandbox provenance",
  1626. );
  1627. export const networkObservationSchema = z.object({
  1628. transport: z.enum(["http", "websocket", "rpc"]),
  1629. interface: z.string(),
  1630. durationMs: z.number(),
  1631. ok: z.boolean(),
  1632. statusCode: z.number().optional(),
  1633. errorKind: z.string().optional(),
  1634. attempt: z.number().int().positive().optional(),
  1635. dnsMs: z.number().optional(),
  1636. tcpMs: z.number().optional(),
  1637. tlsMs: z.number().optional(),
  1638. ttfbMs: z.number().optional(),
  1639. downloadMs: z.number().optional(),
  1640. });
  1641. export const hostNetworkTelemetryBatchResponseSchema = z.object({
  1642. type: z.literal("network-telemetry-batch"),
  1643. observations: z.array(networkObservationSchema).max(500),
  1644. });
  1645. export const hostProviderProvisioningSourceChangedResponseSchema = z
  1646. .object({
  1647. type: z.literal("provider-provisioning-source-changed"),
  1648. trigger: providerProvisioningTriggerSchema.exclude(["environment-online", "user-retry"]),
  1649. })
  1650. .strict();
  1651. /**
  1652. * host → main:数据同步页按设备读取(read)、等当前执行结束后读取(wait)或重试(retry)
  1653. * Provisioning lane。Main 总是回 provider-provisioning-lane-result。
  1654. */
  1655. export const hostProviderProvisioningLaneRequestResponseSchema = z
  1656. .object({
  1657. type: z.literal("provider-provisioning-lane-request"),
  1658. requestId: nonEmptyStringSchema,
  1659. sourceServerId: nonEmptyStringSchema,
  1660. action: z.enum(["read", "wait", "retry"]),
  1661. })
  1662. .strict();
  1663. export const hostProviderProvisioningExecutionResultResponseSchema = z
  1664. .object({
  1665. type: z.literal("provider-provisioning-execution-result"),
  1666. requestId: nonEmptyStringSchema,
  1667. environmentKey: nonEmptyStringSchema,
  1668. status: z.enum(["applied", "already-applied", "unsupported", "failed", "rollback_failed"]),
  1669. error: z.string().optional(),
  1670. errorCode: providerProvisioningErrorCodeSchema.optional(),
  1671. })
  1672. .strict();
  1673. export const hostResourceUsageProcessSchema = z
  1674. .object({
  1675. pid: z.number().int().positive(),
  1676. name: nonEmptyStringSchema,
  1677. category: z.enum(["base", "task", "builtin-plugin", "community-plugin"]),
  1678. groupKey: nonEmptyStringSchema,
  1679. groupLabel: nonEmptyStringSchema,
  1680. cpuPercent: z.number().finite().nonnegative(),
  1681. memoryBytes: z.number().finite().nonnegative(),
  1682. })
  1683. .strict();
  1684. export const hostResourceUsageSnapshotResultResponseSchema = z
  1685. .object({
  1686. type: z.literal("resource-usage-snapshot-result"),
  1687. requestId: nonEmptyStringSchema,
  1688. sampledAt: z.number().int().nonnegative(),
  1689. processes: z.array(hostResourceUsageProcessSchema).max(10_000),
  1690. })
  1691. .strict();
  1692. export type HostResourceUsageSnapshotResultResponse = z.infer<
  1693. typeof hostResourceUsageSnapshotResultResponseSchema
  1694. >;
  1695. export const hostResponseMessageSchema = z.discriminatedUnion("type", [
  1696. hostProjectWorkspacePreparedResponseSchema,
  1697. z.object({ type: z.literal("network-capture-batch"), batch: networkCaptureBatchSchema }).strict(),
  1698. z
  1699. .object({ type: z.literal("database-startup-state"), state: databaseStartupStateSchema })
  1700. .strict(),
  1701. hostResourceUsageSnapshotResultResponseSchema,
  1702. hostRemoteWorkspaceConnectionLogResponseSchema,
  1703. hostRemoteWorkspaceConnectedResponseSchema,
  1704. hostRemoteWorkspaceContextBoundResponseSchema,
  1705. hostRemoteWorkspaceContextBindFailedResponseSchema,
  1706. hostRemoteWorkspaceReconnectedResponseSchema,
  1707. hostRemoteWorkspaceConnectFailedResponseSchema,
  1708. hostRemoteWorkspaceClosedResponseSchema,
  1709. hostLogResponseSchema,
  1710. hostAgentProcessSpawnedResponseSchema,
  1711. hostAgentProcessReadyResponseSchema,
  1712. hostAgentProcessExitedResponseSchema,
  1713. hostAgentProcessErrorResponseSchema,
  1714. hostAgentProcessExceptionResponseSchema,
  1715. hostAgentResourceSampleResponseSchema,
  1716. hostResourceSampleResponseSchema,
  1717. hostMcpTelemetryResponseSchema,
  1718. hostMcpResourceSamplesResponseSchema,
  1719. hostToolExecResourceResponseSchema,
  1720. hostSessionCreateTelemetryResponseSchema,
  1721. hostRemoteConversationTelemetryResponseSchema,
  1722. hostPluginTelemetryResponseSchema,
  1723. hostAgentRunningTaskCountChangedResponseSchema,
  1724. hostQuitBlockersChangedResponseSchema,
  1725. hostWorkspaceRunningTaskCountChangedResponseSchema,
  1726. hostCuaOperationStateResponseSchema,
  1727. hostBroadcastEnvelopeSchema,
  1728. hostBroadcastClaimRequestResponseSchema,
  1729. hostBroadcastClaimCommitResponseSchema,
  1730. hostBroadcastClaimReleaseResponseSchema,
  1731. hostTaskRealtimePublishResponseSchema,
  1732. hostTaskStreamOpPublishResponseSchema,
  1733. hostTaskRunLeaseAcquireResponseSchema,
  1734. hostTaskRunLeaseReleaseResponseSchema,
  1735. hostTaskOwnerCommandRequestResponseSchema,
  1736. hostTaskOwnerCommandResultResponseSchema,
  1737. hostSessionMessageSendRequestedResponseSchema,
  1738. hostSessionRouteAnnounceResponseSchema,
  1739. hostSessionMessageDeliverResultResponseSchema,
  1740. hostFeedbackLogArchiveRequestResponseSchema,
  1741. hostBrowserExecuteRequestResponseSchema,
  1742. hostLocalMediaPreviewPathAuthorizeRequestResponseSchema,
  1743. hostCredentialCipherRequestResponseSchema,
  1744. hostCredentialKeyShareRequestResponseSchema,
  1745. hostPluginSandboxRegisterRequestResponseSchema,
  1746. hostNetworkTelemetryBatchResponseSchema,
  1747. hostProviderProvisioningSourceChangedResponseSchema,
  1748. hostProviderProvisioningExecutionResultResponseSchema,
  1749. hostProviderProvisioningLaneRequestResponseSchema,
  1750. hostCronRunResultResponseSchema,
  1751. hostOffPeakRunResultResponseSchema,
  1752. hostCronSchedulerWakeRequestResponseSchema,
  1753. hostOffPeakSchedulerWakeRequestResponseSchema,
  1754. ]);
  1755. export const zcodeTaskPersistStatusSchema = z.enum(["running", "completed", "error"]);
  1756. export const zcodePromptImageAttachmentSchema = z.object({
  1757. kind: z.literal("image"),
  1758. filename: z.string(),
  1759. mimeType: z.string(),
  1760. sizeBytes: z.number().int().nonnegative().optional(),
  1761. dataBase64: z.string().optional(),
  1762. localPath: z.string().optional(),
  1763. });
  1764. // 附件 TypeScript 联合类型新增 video 后,手写的持久化运行时 schema 未同步,
  1765. // session 恢复解析会拒绝含视频的用户消息。字段与 image 的 inline/local 引用语义保持一致。
  1766. export const zcodePromptVideoAttachmentSchema = z.object({
  1767. kind: z.literal("video"),
  1768. filename: z.string(),
  1769. mimeType: z.string(),
  1770. sizeBytes: z.number().int().nonnegative().optional(),
  1771. dataBase64: z.string().optional(),
  1772. localPath: z.string().optional(),
  1773. });
  1774. export const zcodePromptPdfAttachmentSchema = z.object({
  1775. kind: z.literal("pdf"),
  1776. filename: z.string(),
  1777. mimeType: z.string(),
  1778. sizeBytes: z.number().int().nonnegative().optional(),
  1779. dataBase64: z.string().optional(),
  1780. localPath: z.string().optional(),
  1781. });
  1782. export const zcodePromptFileAttachmentSchema = z.object({
  1783. kind: z.literal("file"),
  1784. filename: z.string(),
  1785. mimeType: z.string(),
  1786. sizeBytes: z.number().int().nonnegative(),
  1787. dataBase64: z.string().optional(),
  1788. textContent: z.string().optional(),
  1789. localPath: z.string().optional(),
  1790. });
  1791. export const zcodePromptAttachmentSchema = z.discriminatedUnion("kind", [
  1792. zcodePromptImageAttachmentSchema,
  1793. zcodePromptVideoAttachmentSchema,
  1794. zcodePromptPdfAttachmentSchema,
  1795. zcodePromptFileAttachmentSchema,
  1796. ]);
  1797. export const zcodePersistedToolCallSchema = z.object({
  1798. toolName: z.string().optional(),
  1799. title: z.string().optional(),
  1800. kind: z.string().optional(),
  1801. status: z.enum(["completed", "failed", "denied", "stopped"]).optional(),
  1802. input: z.unknown(),
  1803. output: z.unknown().optional(),
  1804. error: z.string().optional(),
  1805. raw: z.unknown().optional(),
  1806. snapshotRefs: z
  1807. .array(
  1808. z.object({
  1809. field: z.enum(["input", "output", "raw"]),
  1810. refId: z.string(),
  1811. hash: z.string(),
  1812. fullBytes: z.number().int().nonnegative(),
  1813. previewBytes: z.number().int().nonnegative(),
  1814. }),
  1815. )
  1816. .optional(),
  1817. });
  1818. const zcodePersistedMessagePartSchema = z.discriminatedUnion("type", [
  1819. z.object({ type: z.literal("content"), content: z.string() }),
  1820. z.object({ type: z.literal("thought"), content: z.string() }),
  1821. z.object({
  1822. type: z.literal("tool-call"),
  1823. toolIndex: z.number().int().nonnegative(),
  1824. }),
  1825. ]);
  1826. export const zcodePersistedMessageSchema = z.object({
  1827. id: z.string().optional(),
  1828. role: z.enum(["user", "assistant"]),
  1829. content: z.string(),
  1830. timestamp: z.number().int().nonnegative(),
  1831. model: z.string().optional(),
  1832. characterCount: z.number().int().nonnegative().optional(),
  1833. // assistant 历史耗时已经在服务层落盘为 durationMs,
  1834. // 但校验 schema 没同步,saveTask/getTaskSnapshot 解析时会把它静默剥掉,
  1835. // 导致新消息结束后 UI 仍然只能看到“Worked”。这里补上字段以保留持久化值。
  1836. durationMs: z.number().int().nonnegative().optional(),
  1837. interrupted: z.boolean().optional(),
  1838. feedback: z.enum(["like", "dislike"]).optional(),
  1839. attachments: z.array(zcodePromptAttachmentSchema).optional(),
  1840. tools: z.array(zcodePersistedToolCallSchema).optional(),
  1841. thought: z.string().optional(),
  1842. parts: z.array(zcodePersistedMessagePartSchema).optional(),
  1843. checkpointState: z.enum(["partial"]).optional(),
  1844. checkpointReason: z.enum(["tool_completed", "part_boundary", "periodic"]).optional(),
  1845. checkpointUpdatedAt: z.number().int().nonnegative().optional(),
  1846. turnIndex: z.number().int().nonnegative().optional(),
  1847. // snapshot 按需加载依赖 bodyRefs(content/thought -> refId)定位完整内容;
  1848. // 若 schema 缺字段,Zod 会在解析 session 文件时静默剥离,导致“加载完整内容”功能失效。
  1849. bodyRefs: z
  1850. .array(
  1851. z.object({
  1852. field: z.enum(["content", "thought"]),
  1853. refId: z.string(),
  1854. hash: z.string(),
  1855. fullBytes: z.number().int().nonnegative(),
  1856. previewBytes: z.number().int().nonnegative(),
  1857. }),
  1858. )
  1859. .optional(),
  1860. toolSlice: z
  1861. .object({
  1862. persistedMessageIndex: z.number().int().nonnegative(),
  1863. totalTools: z.number().int().nonnegative(),
  1864. startToolIndex: z.number().int().nonnegative(),
  1865. endToolIndexExclusive: z.number().int().nonnegative(),
  1866. })
  1867. .optional(),
  1868. });
  1869. export const zcodeTaskGoalStatusSchema = z.enum(["active", "paused", "budget_limited", "complete"]);
  1870. export const zcodeTaskTargetChangedActionSchema = z.enum([
  1871. "set",
  1872. "status_updated",
  1873. "cleared",
  1874. "usage_accounted",
  1875. "run_started",
  1876. "run_finished",
  1877. "summary_updated",
  1878. ]);
  1879. export const zcodeTaskTargetChangedSourceSchema = z.enum(["command", "tool", "runtime"]);
  1880. export const zcodeTaskGoalSchema = z.object({
  1881. sessionID: nonEmptyStringSchema,
  1882. targetID: nonEmptyStringSchema,
  1883. objective: nonEmptyStringSchema,
  1884. // 2.15.0 之前的 /goal 历史任务没有写 summaryTitle。
  1885. // 读取 task index 老数据时要补成 null,否则整个任务列表会被运行时 schema 拒绝。
  1886. summaryTitle: z.string().min(1).nullable().default(null),
  1887. status: zcodeTaskGoalStatusSchema,
  1888. tokenBudget: z.number().int().positive().nullable(),
  1889. tokensUsed: z.number().int().nonnegative(),
  1890. timeUsedSeconds: z.number().int().nonnegative(),
  1891. activeInputId: nonEmptyStringSchema.nullable().optional(),
  1892. activeRunStartedAtMs: z.number().int().nonnegative().nullable().optional(),
  1893. activeRunLastSeenAtMs: z.number().int().nonnegative().nullable().optional(),
  1894. time: z.object({
  1895. created: z.number().int().nonnegative(),
  1896. updated: z.number().int().nonnegative(),
  1897. }),
  1898. });
  1899. export const zcodeTaskGoalChangedPatchSchema = z.object({
  1900. action: zcodeTaskTargetChangedActionSchema,
  1901. source: zcodeTaskTargetChangedSourceSchema,
  1902. target: zcodeTaskGoalSchema.nullable(),
  1903. previousTarget: zcodeTaskGoalSchema.nullable().optional(),
  1904. });
  1905. export const zcodeTaskTargetStatusSchema = zcodeTaskGoalStatusSchema;
  1906. export const zcodeTaskTargetSchema = zcodeTaskGoalSchema;
  1907. export const zcodeTaskTargetChangedPatchSchema = zcodeTaskGoalChangedPatchSchema;
  1908. export const zcodeTaskMetaSchema = z.object({
  1909. taskId: nonEmptyStringSchema,
  1910. traceId: nonEmptyStringSchema,
  1911. title: z.string(),
  1912. titleOverridden: z.boolean().optional(),
  1913. workspacePath: nonEmptyStringSchema,
  1914. workspaceIdentity: nonEmptyStringSchema.optional(),
  1915. workspacePurpose: z.enum(["project", "conversation"]).optional(),
  1916. createdAt: z.number().int().nonnegative(),
  1917. updatedAt: z.number().int().nonnegative(),
  1918. mode: zcodeTaskModeSchema,
  1919. model: z.string().optional(),
  1920. thoughtLevel: nonEmptyStringSchema.optional(),
  1921. runtimeEpoch: z.number().int().nonnegative().optional(),
  1922. // meta 直接解析自 tasks-index/旧 session 文件;历史 provider 值在此归一为 glm。
  1923. provider: legacyZCodeProviderSchema.optional(),
  1924. migrationSource: zcodeTaskMigrationSourceSchema.optional(),
  1925. forkedFromTaskId: nonEmptyStringSchema.optional(),
  1926. // cron automation 身份:随 meta_json 一起持久化(单一来源),同时在写入时投影到 tasks 表
  1927. // cron_automation_id 索引列,供按 automation 反查 session。runId 属于 automation_runs /
  1928. // 投递 metadata,不属于 task 表。
  1929. cronAutomationId: nonEmptyStringSchema.optional(),
  1930. // off-peak 身份:与 cron 同款持久化策略——meta_json 单一来源 + tasks 表
  1931. // off_peak_task_id 索引投影列(兜底/反查)。
  1932. offPeakTaskId: nonEmptyStringSchema.optional(),
  1933. unreadAt: z.number().int().nonnegative().optional(),
  1934. status: zcodeTaskPersistStatusSchema.optional(),
  1935. lastError: z
  1936. .object({
  1937. code: z.string().optional(),
  1938. detail: z.string().optional(),
  1939. message: z.string().min(1),
  1940. traceId: nonEmptyStringSchema.optional(),
  1941. taskId: nonEmptyStringSchema.optional(),
  1942. attribution: errorAttributionSchema.optional(),
  1943. })
  1944. .optional(),
  1945. repairState: z
  1946. .object({
  1947. claudeNativeSnapshotAssistantContentVersion: z.number().int().nonnegative().optional(),
  1948. codexNativeSnapshotSubagentToolsVersion: z.number().int().nonnegative().optional(),
  1949. })
  1950. .optional(),
  1951. changeSummary: z
  1952. .object({
  1953. fileCount: z.number().int().nonnegative(),
  1954. added: z.number().int().nonnegative(),
  1955. removed: z.number().int().nonnegative(),
  1956. files: z.array(
  1957. z.object({
  1958. path: z.string(),
  1959. added: z.number().int().nonnegative(),
  1960. removed: z.number().int().nonnegative(),
  1961. writeCount: z.number().int().positive(),
  1962. lastTurnIndex: z.number().int().nonnegative(),
  1963. }),
  1964. ),
  1965. })
  1966. .optional(),
  1967. target: zcodeTaskGoalSchema.nullable().optional(),
  1968. });
  1969. export const zcodeTaskSessionBindingStateSchema = z.enum([
  1970. "idle",
  1971. "syncing",
  1972. "ready",
  1973. "stale",
  1974. "failed",
  1975. ]);
  1976. export const zcodeTaskSessionBindingSchema = z.object({
  1977. // 绑定状态由 services 从持久化数据投影;旧绑定残留的历史 provider 值在此归一为 glm。
  1978. provider: legacyZCodeProviderSchema,
  1979. sessionId: nonEmptyStringSchema,
  1980. // 绑定锚点需要支持空 task 的 -1,所以这里不能套 nonnegative。
  1981. lastSyncedTurnIndex: z.number().int(),
  1982. state: zcodeTaskSessionBindingStateSchema,
  1983. });
  1984. export const zcodeTaskIndexEntrySchema = z.object({
  1985. workspaceHash: nonEmptyStringSchema,
  1986. taskId: nonEmptyStringSchema,
  1987. });
  1988. export const zcodePinnedTasksFileSchema = z.object({
  1989. version: z.literal("1"),
  1990. tasks: z.array(zcodeTaskIndexEntrySchema),
  1991. });
  1992. const zcodePersistedFileSnapshotSchema = z.object({
  1993. path: z.string(),
  1994. beforeContent: z.string().nullable(),
  1995. afterContent: z.string(),
  1996. writeCount: z.number().int().positive(),
  1997. contentRefs: z
  1998. .array(
  1999. z.object({
  2000. field: z.enum(["beforeContent", "afterContent"]),
  2001. refId: z.string(),
  2002. hash: z.string(),
  2003. fullBytes: z.number().int().nonnegative(),
  2004. previewBytes: z.number().int().nonnegative(),
  2005. }),
  2006. )
  2007. .optional(),
  2008. });
  2009. const zcodePersistedFileChangeSchema = z.object({
  2010. turnIndex: z.number().int().nonnegative(),
  2011. snapshots: z.array(zcodePersistedFileSnapshotSchema),
  2012. fileState: z.enum(["applied", "reverted"]).optional(),
  2013. });
  2014. const zcodePersistedTurnCheckpointSchema = z.object({
  2015. turnIndex: z.number().int().nonnegative(),
  2016. baseFileCheckpointId: nonEmptyStringSchema,
  2017. resultFileCheckpointId: nonEmptyStringSchema.optional(),
  2018. });
  2019. export const zcodeSessionFileSchema = z.object({
  2020. meta: zcodeTaskMetaSchema,
  2021. messages: z.array(zcodePersistedMessageSchema),
  2022. fileChanges: z.array(zcodePersistedFileChangeSchema).optional(),
  2023. turnCheckpoints: z.array(zcodePersistedTurnCheckpointSchema).optional(),
  2024. });