validation.ts 75 KB

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