transport.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. import { localTtftFactsSchema } from "../localTtft.js";
  2. /* eslint-disable max-lines -- 三个 topic 的 logical/physical/candidate schema 必须共享同一通用传输声明,避免跨文件分叉。 */
  3. // 传输外壳:连接握手 / 订阅 / 帧信封。
  4. // 阶段为类型占位(后半接通道层时启用),数据形状已按规范定稿。
  5. import { z } from "zod";
  6. import { APP_USAGE_RANGES, appUsageSnapshotSchema } from "../usage-stats.js";
  7. import { zcodeWorkspaceRefSchema } from "../zcode-protocol-legacy-types.js";
  8. import {
  9. PROTOCOL_V4_LIMITS,
  10. V4_WIRE_PROTOCOL_VERSION,
  11. conversationRowTargetSchema,
  12. timestampSchema,
  13. } from "./core.js";
  14. import { conversationDeltaSchema } from "./delta.js";
  15. import { conversationRowSchema, toolCallRowSchema } from "./rows.js";
  16. import { sessionsIndexDeltaSchema, sessionsIndexSnapshotSchema } from "./sessions-index.js";
  17. import { WORKFLOW_RUN_STOP_REASONS } from "./workflow-observation-display.js";
  18. import { conversationSnapshotSchema } from "./snapshot.js";
  19. import { workspaceConfigDeltaSchema, workspaceConfigSnapshotSchema } from "./workspace-config.js";
  20. import { createTopicWireFrameSchema, topicWireFrameCandidateSchema } from "./wire.js";
  21. // ── 连接与握手 ──
  22. export const hostCapabilitiesSchema = z.object({
  23. nativeDialogs: z.boolean(),
  24. localTerminal: z.boolean(),
  25. // ws binary(relay 链路探测用)。
  26. binaryFrames: z.boolean(),
  27. compression: z.enum(["none", "permessage-deflate"]),
  28. // Wire-compatible:旧 Host 缺失等价于 false;调用方必须用 === true 判断。
  29. workspaceHookReview: z.boolean().optional(),
  30. independentPlanState: z.boolean().optional(),
  31. /**
  32. * 本 Host 会发 `workflowRun.*` 键级增量(delta.ts 的两条 op),因而 `workflowRuns` 的
  33. * actors / nodes 可以到 1024 而不是旧界的 256。没有这个位的消费者收到的仍是整键
  34. * `state.updated`,并且先经 `clampWorkflowRunsForLegacy` 裁到旧界。
  35. */
  36. workflowRunDeltas: z.boolean().optional(),
  37. });
  38. export type HostCapabilities = z.infer<typeof hostCapabilitiesSchema>;
  39. export const helloMessageSchema = z
  40. .object({
  41. kind: z.literal("hello"),
  42. protocolVersion: z.literal(V4_WIRE_PROTOCOL_VERSION),
  43. connectionId: z.string(),
  44. clientMode: z.enum(["desktop-continuous", "web-remote-replayable"]),
  45. deliveryProfile: z.enum(["continuous", "replayable"]),
  46. // 首次时钟校准。
  47. serverTime: timestampSchema,
  48. capabilities: hostCapabilitiesSchema,
  49. // 此处只留位。
  50. auth: z.object({ userId: z.string().optional() }),
  51. })
  52. .strict()
  53. .superRefine((hello, context) => {
  54. const expectedProfile = hello.clientMode === "desktop-continuous" ? "continuous" : "replayable";
  55. if (hello.deliveryProfile !== expectedProfile) {
  56. context.addIssue({
  57. code: "custom",
  58. message: "trusted clientMode and deliveryProfile must match",
  59. path: ["deliveryProfile"],
  60. });
  61. }
  62. });
  63. export type HelloMessage = z.infer<typeof helloMessageSchema>;
  64. // clientMode 连接级注册一次,不进 command 信封。
  65. export const clientHelloSchema = z
  66. .object({
  67. kind: z.literal("clientHello"),
  68. protocolVersion: z.literal(V4_WIRE_PROTOCOL_VERSION),
  69. clientId: z.string(),
  70. clientKind: z.enum(["desktop", "web", "mobileRemote", "mobileApp"]).optional(),
  71. appVersion: z.string(),
  72. // 缺失代表旧客户端,不具备 Settings-centered review UI。
  73. capabilities: z
  74. .object({
  75. workspaceHookReviewUi: z.boolean().optional(),
  76. /**
  77. * 本客户端认得 `workflowRun.*` 增量。⚠ 声明规则是**单向**的:客户端只有在 Host 的
  78. * hello 里见到 `workflowRunDeltas === true` 时才能带上这个键——这个 capabilities 对象
  79. * 是 `.strict()` 的,老 Host 见到不认识的键会整条 clientHello 解析失败、连接握不上手。
  80. */
  81. workflowRunDeltas: z.boolean().optional(),
  82. })
  83. .strict()
  84. .optional(),
  85. })
  86. .strict();
  87. export type ClientHello = z.infer<typeof clientHelloSchema>;
  88. export function hostSupportsWorkspaceHookReview(capabilities: HostCapabilities): boolean {
  89. return capabilities.workspaceHookReview === true;
  90. }
  91. export function clientSupportsWorkspaceHookReview(clientHello: ClientHello): boolean {
  92. return clientHello.capabilities?.workspaceHookReviewUi === true;
  93. }
  94. export function hostSupportsWorkflowRunDeltas(capabilities: HostCapabilities): boolean {
  95. return capabilities.workflowRunDeltas === true;
  96. }
  97. export function clientSupportsWorkflowRunDeltas(clientHello: ClientHello): boolean {
  98. return clientHello.capabilities?.workflowRunDeltas === true;
  99. }
  100. // ── §3.1 订阅 ──
  101. export const subscribeParamsSchema = z
  102. .object({
  103. // "conversation/<sessionId>" | "sessions-index/<workspaceId>" | ...
  104. topic: z.string(),
  105. // 水位不变量:仅当客户端真持有该时刻一致状态才允许带。
  106. base: z.object({ logEpoch: z.string(), seq: z.number() }).optional(),
  107. // QoS hint,只影响调度,不影响语义。
  108. visibility: z.enum(["foreground", "background"]).optional(),
  109. })
  110. .strict();
  111. export type SubscribeParams = z.infer<typeof subscribeParamsSchema>;
  112. export const subscribeAckSchema = z.object({
  113. subscriptionId: z.string(),
  114. // resume = base 有效,从 base.seq 续传增量;否则 snapshot。
  115. mode: z.enum(["snapshot", "resume"]),
  116. logEpoch: z.string(),
  117. });
  118. export type SubscribeAck = z.infer<typeof subscribeAckSchema>;
  119. const openTimingMsSchema = z.number().int().nonnegative().optional();
  120. const openTimingCountSchema = z.number().int().nonnegative().optional();
  121. /**
  122. * Desktop session 首次打开的低频诊断 timing;只挂在 conversation subscribe ACK,
  123. * 不进入 snapshot、delta、sessions-index 或 workspace-config。
  124. */
  125. export const conversationOpenTimingSchema = z
  126. .object({
  127. version: z.literal(1),
  128. hostPrepareMs: openTimingMsSchema,
  129. providerRegistrySyncMs: openTimingMsSchema,
  130. taskMetaReadMs: openTimingMsSchema,
  131. cliRequestMs: openTimingMsSchema,
  132. cliBootstrapMs: openTimingMsSchema,
  133. cliSessionRestoreMs: openTimingMsSchema,
  134. initialFrameEncodeMs: openTimingMsSchema,
  135. cliProcessState: z.enum(["spawned", "reused"]).optional(),
  136. sessionRuntimeState: z.enum(["cold", "warm"]).optional(),
  137. snapshotRowCount: openTimingCountSchema,
  138. })
  139. .strict();
  140. export type ConversationOpenTiming = z.infer<typeof conversationOpenTimingSchema>;
  141. const conversationSubscribeAckSchema = subscribeAckSchema.extend({
  142. openTiming: conversationOpenTimingSchema.optional(),
  143. });
  144. export type ConversationSubscribeAck = z.infer<typeof conversationSubscribeAckSchema>;
  145. // ── 帧信封(泛型帧用工厂构造具体 topic 的 schema)──
  146. export function createTopicFrameSchema<S extends z.ZodTypeAny, D extends z.ZodTypeAny>(
  147. snapshotSchema: S,
  148. deltaSchema: D,
  149. ) {
  150. return z.object({
  151. topic: z.string(),
  152. // 代际标识,防旧流交错。
  153. subscriptionId: z.string(),
  154. // 区间记账 (fromSeq, toSeq];snapshot 帧 fromSeq 固定为 0。
  155. fromSeq: z.number(),
  156. toSeq: z.number(),
  157. // CLI 时钟,供 clockOffset 估计。
  158. sentAt: timestampSchema,
  159. payload: z.discriminatedUnion("kind", [
  160. z.object({ kind: z.literal("snapshot"), snapshot: snapshotSchema }),
  161. z.object({ kind: z.literal("deltas"), deltas: z.array(deltaSchema) }),
  162. ]),
  163. });
  164. }
  165. export interface TopicFrame<S, D> {
  166. topic: string;
  167. subscriptionId: string;
  168. fromSeq: number;
  169. toSeq: number;
  170. sentAt: Timestamp;
  171. payload: { kind: "snapshot"; snapshot: S } | { kind: "deltas"; deltas: D[] };
  172. }
  173. type Timestamp = z.infer<typeof timestampSchema>;
  174. // conversation topic 的具体帧 schema(五件套实例化)。
  175. // 传输外壳/黄金测试用它做帧合法性校验;host 通道层 复用。
  176. export const conversationTopicFrameSchema = createTopicFrameSchema(
  177. conversationSnapshotSchema,
  178. conversationDeltaSchema,
  179. )
  180. .extend({
  181. ttft: localTtftFactsSchema.optional(),
  182. ttftRelated: z.array(localTtftFactsSchema).max(16).optional(),
  183. })
  184. .superRefine((frame, context) => {
  185. if (!frame.topic.startsWith("conversation/") || frame.topic.length === "conversation/".length) {
  186. context.addIssue({ code: "custom", message: "invalid conversation topic", path: ["topic"] });
  187. }
  188. });
  189. export type ConversationTopicFrame = z.infer<typeof conversationTopicFrameSchema>;
  190. export const conversationTopicWireFrameSchema = createTopicWireFrameSchema(
  191. conversationTopicFrameSchema,
  192. ).superRefine((wire, context) => {
  193. if (!wire.topic.startsWith("conversation/") || wire.topic.length === "conversation/".length) {
  194. context.addIssue({ code: "custom", message: "invalid conversation topic", path: ["topic"] });
  195. }
  196. });
  197. export type ConversationTopicWireFrame = z.infer<typeof conversationTopicWireFrameSchema>;
  198. export const conversationTopicWireCandidateSchema = topicWireFrameCandidateSchema.superRefine(
  199. (wire, context) => {
  200. if (!wire.topic.startsWith("conversation/") || wire.topic.length === "conversation/".length) {
  201. context.addIssue({ code: "custom", message: "invalid conversation topic", path: ["topic"] });
  202. }
  203. },
  204. );
  205. export type ConversationTopicWireCandidate = z.infer<typeof conversationTopicWireCandidateSchema>;
  206. // sessions-index topic 的具体帧 schema(五件套实例化;侧栏列表活性数据源)。
  207. export const sessionsIndexTopicFrameSchema = createTopicFrameSchema(
  208. sessionsIndexSnapshotSchema,
  209. sessionsIndexDeltaSchema,
  210. ).superRefine((frame, context) => {
  211. if (
  212. !frame.topic.startsWith("sessions-index/") ||
  213. frame.topic.length === "sessions-index/".length
  214. ) {
  215. context.addIssue({ code: "custom", message: "invalid sessions-index topic", path: ["topic"] });
  216. }
  217. });
  218. export type SessionsIndexTopicFrame = z.infer<typeof sessionsIndexTopicFrameSchema>;
  219. export const sessionsIndexTopicWireFrameSchema = createTopicWireFrameSchema(
  220. sessionsIndexTopicFrameSchema,
  221. ).superRefine((wire, context) => {
  222. if (!wire.topic.startsWith("sessions-index/") || wire.topic.length === "sessions-index/".length) {
  223. context.addIssue({ code: "custom", message: "invalid sessions-index topic", path: ["topic"] });
  224. }
  225. });
  226. export type SessionsIndexTopicWireFrame = z.infer<typeof sessionsIndexTopicWireFrameSchema>;
  227. export const sessionsIndexTopicWireCandidateSchema = topicWireFrameCandidateSchema.superRefine(
  228. (wire, context) => {
  229. if (
  230. !wire.topic.startsWith("sessions-index/") ||
  231. wire.topic.length === "sessions-index/".length
  232. ) {
  233. context.addIssue({
  234. code: "custom",
  235. message: "invalid sessions-index topic",
  236. path: ["topic"],
  237. });
  238. }
  239. },
  240. );
  241. export type SessionsIndexTopicWireCandidate = z.infer<typeof sessionsIndexTopicWireCandidateSchema>;
  242. // workspace-config topic 的具体帧 schema(additive 变更;配置目录活性数据源)。
  243. export const workspaceConfigTopicFrameSchema = createTopicFrameSchema(
  244. workspaceConfigSnapshotSchema,
  245. workspaceConfigDeltaSchema,
  246. ).superRefine((frame, context) => {
  247. if (
  248. !frame.topic.startsWith("workspace-config/") ||
  249. frame.topic.length === "workspace-config/".length
  250. ) {
  251. context.addIssue({
  252. code: "custom",
  253. message: "invalid workspace-config topic",
  254. path: ["topic"],
  255. });
  256. }
  257. });
  258. export type WorkspaceConfigTopicFrame = z.infer<typeof workspaceConfigTopicFrameSchema>;
  259. export const workspaceConfigTopicWireFrameSchema = createTopicWireFrameSchema(
  260. workspaceConfigTopicFrameSchema,
  261. ).superRefine((wire, context) => {
  262. if (
  263. !wire.topic.startsWith("workspace-config/") ||
  264. wire.topic.length === "workspace-config/".length
  265. ) {
  266. context.addIssue({
  267. code: "custom",
  268. message: "invalid workspace-config topic",
  269. path: ["topic"],
  270. });
  271. }
  272. });
  273. export type WorkspaceConfigTopicWireFrame = z.infer<typeof workspaceConfigTopicWireFrameSchema>;
  274. export const workspaceConfigTopicWireCandidateSchema = topicWireFrameCandidateSchema.superRefine(
  275. (wire, context) => {
  276. if (
  277. !wire.topic.startsWith("workspace-config/") ||
  278. wire.topic.length === "workspace-config/".length
  279. ) {
  280. context.addIssue({
  281. code: "custom",
  282. message: "invalid workspace-config topic",
  283. path: ["topic"],
  284. });
  285. }
  286. },
  287. );
  288. export type WorkspaceConfigTopicWireCandidate = z.infer<
  289. typeof workspaceConfigTopicWireCandidateSchema
  290. >;
  291. /** 三个生产 topic 的公共 logical / physical 路由面。 */
  292. export const routedTopicFrameSchema = z.union([
  293. conversationTopicFrameSchema,
  294. sessionsIndexTopicFrameSchema,
  295. workspaceConfigTopicFrameSchema,
  296. ]);
  297. export type RoutedTopicFrame = z.infer<typeof routedTopicFrameSchema>;
  298. export const routedTopicWireFrameSchema = z.union([
  299. conversationTopicWireFrameSchema,
  300. sessionsIndexTopicWireFrameSchema,
  301. workspaceConfigTopicWireFrameSchema,
  302. ]);
  303. export type RoutedTopicWireFrame = z.infer<typeof routedTopicWireFrameSchema>;
  304. export const routedTopicWireCandidateSchema = z.union([
  305. conversationTopicWireCandidateSchema,
  306. sessionsIndexTopicWireCandidateSchema,
  307. workspaceConfigTopicWireCandidateSchema,
  308. ]);
  309. export type RoutedTopicWireCandidate = z.infer<typeof routedTopicWireCandidateSchema>;
  310. // ── v4 RPC 出入口(host 通道层)──
  311. // 载体复用现有 JSON-RPC(stdio NDJSON / socket),方法名带 v4/ 前缀与旧协议并存;
  312. // 旧 session/* 方法删除后,这里就是唯一协议面。
  313. export const V4_METHODS = {
  314. connectionFlow: "v4/connection/flow",
  315. controllerSubscribe: "v4/controller/subscribe",
  316. controllerResync: "v4/controller/resync",
  317. controllerUnsubscribe: "v4/controller/unsubscribe",
  318. conversationSubscribe: "v4/conversation/subscribe",
  319. conversationResync: "v4/conversation/resync",
  320. conversationUnsubscribe: "v4/conversation/unsubscribe",
  321. // 行分页 query(rows/range):只读、无状态、超时重发安全。
  322. conversationRowsRange: "v4/conversation/rowsRange",
  323. // 当前有效分支的终态 ExitPlanMode 目录;只读、无状态、超时重发安全。
  324. conversationPlans: "v4/conversation/plans",
  325. conversationFileChanges: "v4/conversation/fileChanges",
  326. backgroundBashOutput: "v4/conversation/backgroundBashOutput",
  327. conversationFileRewindPreview: "v4/conversation/fileRewindPreview",
  328. // workflow run 的事件日志分页(详情页审计面):只读、无状态、超时重发安全。
  329. // 新方法天然偏斜安全——旧桌面根本不会调用它。
  330. conversationWorkflowRunEvents: "v4/conversation/workflowRunEvents",
  331. conversationWorkflowRuns: "v4/conversation/workflowRuns",
  332. // workflow run 的用户面产物。三条同族:
  333. // 只读、无状态、超时重发安全;schema 在 workflow-artifacts.ts(那边还有术语消歧)。
  334. // Artifacts 产物清单(冷恢复与中枢详情的 durable 读法)
  335. // ArtifactData 预置看板的条目分页(cursor = journal sequence)
  336. // ArtifactRead 内容产物的字节,≤ 512 KiB 一块,形状逐字照 attachmentRead
  337. conversationWorkflowRunArtifacts: "v4/conversation/workflowRunArtifacts",
  338. conversationWorkflowRunArtifactData: "v4/conversation/workflowRunArtifactData",
  339. conversationWorkflowRunArtifactRead: "v4/conversation/workflowRunArtifactRead",
  340. // workflow run 的工作区 transcript。两条同族,
  341. // 照产物的 ①/③ 拆法:Workspace 是轻行清单(不带正文),NodeResult 是一个节点的有界正文。
  342. conversationWorkflowRunWorkspace: "v4/conversation/workflowRunWorkspace",
  343. conversationWorkflowRunNodeResult: "v4/conversation/workflowRunNodeResult",
  344. // usage query(模式同 rows/range:只读、无状态、超时重发安全)。
  345. // usage 事实源在 CLI 的 session 库(model_usage/turn_usage 聚合),host 侧无副本,
  346. // 故收敛为 v4 query 而非 host 直连;旧词 usage/stats、session/usage 就此消费清零。
  347. usageStats: "v4/usage/stats",
  348. conversationUsage: "v4/conversation/usage",
  349. // 附件事务:禁止 full-data RPC。每个 chunk 的 decoded bytes <=512KiB,
  350. // renderer->host Channel 与 host->CLI NDJSON 都必须逐 request 证明 <=1MiB。
  351. attachmentBegin: "v4/attachment/begin",
  352. attachmentChunk: "v4/attachment/chunk",
  353. attachmentCommit: "v4/attachment/commit",
  354. attachmentAbort: "v4/attachment/abort",
  355. // 已发送图片预览:只读、按 session row 授权,响应仍按 512KiB 分块。
  356. attachmentRead: "v4/attachment/read",
  357. // Share 读取 userInput 附件:允许 text/plain 等非媒体类型,仍按 row/index 授权并分块返回。
  358. conversationAttachmentRead: "v4/conversation/attachmentRead",
  359. // Share 预检 userInput 附件元数据:只做 row/index 授权和 stat,不读取完整文件。
  360. conversationAttachmentStat: "v4/conversation/attachmentStat",
  361. // Desktop local 已发送视频:只返回经过同一 row/index 授权的本地播放源。
  362. attachmentPreviewSource: "v4/attachment/previewSource",
  363. commandsQuery: "v4/commands/query",
  364. command: "v4/command",
  365. } as const;
  366. export type V4Method = (typeof V4_METHODS)[keyof typeof V4_METHODS];
  367. /** 按任务授权的有界输出查询,不接受任意路径或调用方扩大的读取预算。 */
  368. export const v4BackgroundBashOutputParamsSchema = z.strictObject({
  369. sessionId: z.string().min(1),
  370. workId: z.string().min(1),
  371. });
  372. export type V4BackgroundBashOutputParams = z.infer<typeof v4BackgroundBashOutputParamsSchema>;
  373. export const v4ConnectionFlowStateSchema = z.enum(["saturated", "drained", "closed"]);
  374. export type V4ConnectionFlowState = z.infer<typeof v4ConnectionFlowStateSchema>;
  375. export const v4ConnectionFlowParamsSchema = z
  376. .object({
  377. connectionId: z.string().min(1),
  378. state: v4ConnectionFlowStateSchema,
  379. })
  380. .strict();
  381. export type V4ConnectionFlowParams = z.infer<typeof v4ConnectionFlowParamsSchema>;
  382. export const v4ConnectionFlowResultSchema = z.object({}).strict();
  383. export const V4_NOTIFICATIONS = {
  384. // 下行帧(snapshot / deltas),params = ConversationTopicFrame。
  385. conversationFrame: "v4/conversation/frame",
  386. // 仅 live ingest 的无正文事实;不进入 topic snapshot/recovery。
  387. conversationTelemetryFact: "v4/telemetry/event",
  388. localTtftFacts: "v4/telemetry/local-ttft",
  389. // 仅当前进程 live ToolCallResult 产生;历史与 replayable 链路不得补造。
  390. cuaPermissionObservation: "v4/cua/permission-observation",
  391. } as const;
  392. /** 3.3.6 SSH 历史任务归属证明与 sessions-index 冷种子共享同一有界窗口。 */
  393. export const MAX_LEGACY_TASK_IDS_PER_SUBSCRIBE = 200;
  394. // subscribe 请求 = 通用 SubscribeParams + connectionId(重订阅替换按
  395. // (connectionId, topic) 判定;stdio 单管道场景由 host 为每个下游客户端分配)。
  396. export const v4ConversationSubscribeParamsSchema = subscribeParamsSchema.extend({
  397. connectionId: z.string(),
  398. clientMode: z.enum(["desktop-continuous", "web-remote-replayable"]),
  399. // 当前可信 attachment 的 workspace;cold resume 优先使用它恢复身份,live 不消费。
  400. workspace: zcodeWorkspaceRefSchema.optional(),
  401. /** host 从当前 remote workspace 的 tasks-index 精确读取的旧任务归属 allowlist。 */
  402. legacyTaskIds: z.array(z.string().min(1)).max(MAX_LEGACY_TASK_IDS_PER_SUBSCRIBE).optional(),
  403. // 仅供 host→CLI cold resume 使用;live conversation 不消费该 hint。
  404. resumeThoughtLevel: z.string().trim().min(1).optional(),
  405. /**
  406. * 这条订阅收不收 `workflowRun.*` 键级增量。与 `clientMode` 同族:由**可信 host** 从该连接的
  407. * clientHello 注入,面向 UI 的 subscribe 选不了它——一个客户端能不能认得增量是连接的事实,
  408. * 不是某一次订阅可以自选的口味。缺席 = 按旧消费者处理(整键 patch + 旧界裁剪)。
  409. */
  410. workflowRunDeltas: z.boolean().optional(),
  411. });
  412. export type V4ConversationSubscribeParams = z.infer<typeof v4ConversationSubscribeParamsSchema>;
  413. // 公共 subscribe response 严格只含 ACK。initial snapshot/resume 由 server 的
  414. // request-scoped post-response outbox 在 response line 之后作为 owned notification 发出。
  415. export const v4ConversationSubscribeResultSchema = z
  416. .object({
  417. ack: conversationSubscribeAckSchema,
  418. })
  419. .strict();
  420. export type V4ConversationSubscribeResult = z.infer<typeof v4ConversationSubscribeResultSchema>;
  421. // sessions-index 与 conversation 共用同一 subscribe RPC;公共 response 同样 ACK-only。
  422. export const v4SessionsIndexSubscribeResultSchema = z
  423. .object({
  424. ack: subscribeAckSchema,
  425. })
  426. .strict();
  427. export type V4SessionsIndexSubscribeResult = z.infer<typeof v4SessionsIndexSubscribeResultSchema>;
  428. // workspace-config 也只回 ACK;initial frame 走同一 post-response notification 时序。
  429. export const v4WorkspaceConfigSubscribeResultSchema = z
  430. .object({
  431. ack: subscribeAckSchema,
  432. })
  433. .strict();
  434. export type V4WorkspaceConfigSubscribeResult = z.infer<
  435. typeof v4WorkspaceConfigSubscribeResultSchema
  436. >;
  437. // 活跃订阅的 same-sub 恢复。topic/connection/profile 必须由 host owned registry
  438. // 反查,客户端只能声明自己已确认的水位与是否强制 snapshot。
  439. export const conversationResyncParamsSchema = z
  440. .object({
  441. subscriptionId: z.string().trim().min(1).max(1024),
  442. base: z
  443. .object({
  444. logEpoch: z.string().trim().min(1).max(1024),
  445. seq: z.number().int().nonnegative(),
  446. })
  447. .strict()
  448. .nullable(),
  449. forceSnapshot: z.boolean().optional(),
  450. })
  451. .strict();
  452. export type ConversationResyncParams = z.infer<typeof conversationResyncParamsSchema>;
  453. // CLI-facing 形状:topic/connectionId 只能由 connection facade 从 owned registry 注入。
  454. export const v4ConversationResyncParamsSchema = conversationResyncParamsSchema
  455. .extend({
  456. topic: z.string().trim().min(1).max(2048),
  457. connectionId: z.string().trim().min(1).max(1024),
  458. })
  459. .strict();
  460. export type V4ConversationResyncParams = z.infer<typeof v4ConversationResyncParamsSchema>;
  461. export const v4ConversationResyncResultSchema = z
  462. .object({
  463. ack: subscribeAckSchema,
  464. })
  465. .strict();
  466. export type V4ConversationResyncResult = z.infer<typeof v4ConversationResyncResultSchema>;
  467. export const v4ConversationUnsubscribeParamsSchema = z
  468. .object({
  469. topic: z.string().trim().min(1).max(2048),
  470. subscriptionId: z.string().trim().min(1).max(1024),
  471. connectionId: z.string().trim().min(1).max(1024),
  472. })
  473. .strict();
  474. export type V4ConversationUnsubscribeParams = z.infer<typeof v4ConversationUnsubscribeParamsSchema>;
  475. // ── rows/range(游标制行分页,loadOlder)──
  476. // 无 index 语义:全序 = rowId 升序;客户端按 rowId 键控合并。
  477. export const v4ConversationRowsRangeParamsSchema = z.object({
  478. sessionId: z.string(),
  479. /** Host attachment injects this trusted value; renderer callers omit it. */
  480. clientMode: z.enum(["desktop-continuous", "web-remote-replayable"]).optional(),
  481. // 取 rowId < beforeRowId 的行;缺省 = 从当前尾部向前。
  482. beforeRowId: z.number().optional(),
  483. limit: z.number().min(1).max(PROTOCOL_V4_LIMITS.rowsRangeMaxLimit),
  484. });
  485. export type V4ConversationRowsRangeParams = z.infer<typeof v4ConversationRowsRangeParamsSchema>;
  486. export const v4ConversationRowsRangeResultSchema = z.object({
  487. // rowId 升序。
  488. rows: z.array(conversationRowSchema),
  489. // 服务端取值时的水位/纪元;与 fileChanges 等只读查询共用,避免跨 revision 拼接发布数据。
  490. atSeq: z.number(),
  491. atRevision: z.number().int().nonnegative(),
  492. atLogEpoch: z.string(),
  493. // beforeRowId 方向是否还有更早的行。
  494. hasMore: z.boolean(),
  495. });
  496. export type V4ConversationRowsRangeResult = z.infer<typeof v4ConversationRowsRangeResultSchema>;
  497. // ── conversation plans directory ──
  498. // 目录来自 CLI 完整有效 projection,不能用 renderer 的有界 tail window 推导。
  499. export const v4ConversationPlansParamsSchema = z
  500. .object({
  501. sessionId: z.string().min(1),
  502. })
  503. .strict();
  504. export type V4ConversationPlansParams = z.infer<typeof v4ConversationPlansParamsSchema>;
  505. export const v4ConversationPlansResultSchema = z
  506. .object({
  507. // 当前有效分支的终态 ExitPlanMode,rowId 降序(最新优先)。
  508. plans: z.array(toolCallRowSchema),
  509. atSeq: z.number().int().nonnegative(),
  510. atLogEpoch: z.string().min(1),
  511. })
  512. .strict();
  513. export type V4ConversationPlansResult = z.infer<typeof v4ConversationPlansResultSchema>;
  514. const readonlyDiffHunkSchema = z
  515. .object({
  516. oldStart: z.number(),
  517. oldLines: z.number(),
  518. newStart: z.number(),
  519. newLines: z.number(),
  520. lines: z.array(z.string()),
  521. })
  522. .strict();
  523. export const v4ConversationFileChangesParamsSchema = z
  524. .object({
  525. sessionId: z.string().min(1),
  526. target: conversationRowTargetSchema,
  527. baseRevision: z.number().int().nonnegative(),
  528. baseLogEpoch: z.string().trim().min(1),
  529. })
  530. .strict();
  531. export type V4ConversationFileChangesParams = z.infer<typeof v4ConversationFileChangesParamsSchema>;
  532. export const v4ConversationFileChangesResultSchema = z
  533. .object({
  534. files: z.number().int().nonnegative(),
  535. additions: z.number().int().nonnegative(),
  536. deletions: z.number().int().nonnegative(),
  537. state: z.enum(["active", "reverted"]).optional(),
  538. items: z.array(
  539. z
  540. .object({
  541. path: z.string().min(1),
  542. additions: z.number().int().nonnegative(),
  543. deletions: z.number().int().nonnegative(),
  544. writeCount: z.number().int().nonnegative(),
  545. toolNames: z.array(z.string()),
  546. patches: z.array(readonlyDiffHunkSchema),
  547. })
  548. .strict(),
  549. ),
  550. })
  551. .strict();
  552. export type V4ConversationFileChangesResult = z.infer<typeof v4ConversationFileChangesResultSchema>;
  553. // ── workflow run 事件日志──
  554. // 形态与 rows/range、plans 同族:只读、无状态、超时重发安全。cursor = journal sequence
  555. // (`appendEvent` 单调分配),在 workflowRuns[].lastEventSequence 抬升时重取。
  556. // 刻意**不是** v4 command:command 的 ACK 结果是 commandResultSchema 那个封闭的「变更结果」
  557. // 判别联合,把一页只读事件塞进去等于把读放进写的词汇表,还要白背 baseRevision/幂等那套机制。
  558. /**
  559. * 事件日志一页的两道界,网关按它们取数(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md
  560. * 「Reading the journal」)。字节按存储里的序列化字节计、取协议单帧上限的四分之一:条数单独
  561. * 管不住字节,500 条带着大 report item 的事件足以顶到单帧上限。
  562. */
  563. export const WORKFLOW_RUN_EVENTS_PAGE_LIMITS = {
  564. maxEvents: 500,
  565. maxBytes: PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes / 4,
  566. } as const;
  567. export const v4ConversationWorkflowRunEventsParamsSchema = z
  568. .object({
  569. sessionId: z.string().min(1),
  570. runId: z.string().min(1),
  571. /** 只取 sequence 严格大于该值的事件;缺省从头取。 */
  572. afterSequence: z.number().int().nonnegative().optional(),
  573. limit: z.number().int().positive().max(WORKFLOW_RUN_EVENTS_PAGE_LIMITS.maxEvents).optional(),
  574. })
  575. .strict();
  576. export type V4ConversationWorkflowRunEventsParams = z.infer<
  577. typeof v4ConversationWorkflowRunEventsParamsSchema
  578. >;
  579. export const v4ConversationWorkflowRunEventsResultSchema = z
  580. .object({
  581. events: z.array(
  582. z
  583. .object({
  584. sequence: z.number().int().nonnegative(),
  585. type: z.string().min(1).max(64),
  586. // 载荷已在 CLI 侧经 boundDynamicWorkflowRunEventPayload 有界化(同一次序列化
  587. // 也喂给 workflowRuns 投影)。这里不再复述引擎的事件形状:读端按种类解释。
  588. payload: z.record(z.string(), z.unknown()),
  589. truncated: z.boolean().optional(),
  590. })
  591. .strict(),
  592. ),
  593. /** 本页之后仍有事件(页可能因条数或字节上界提前收尾)。 */
  594. hasMore: z.boolean(),
  595. })
  596. .strict();
  597. // **刻意不带 `atSeq` / `atLogEpoch`**,尽管同族的 rows/range 与 plans 都带。
  598. //
  599. // 那两个字段在同族里是**陈旧读防护**:它们读的是 conversation projection,而 projection 的
  600. // `rowId` 只在一个 log epoch 内有意义(重建 / fork / rewind 会重新编号),所以读端的契约是
  601. // "atLogEpoch ≠ store 当前 epoch → 整个结果丢弃"。
  602. //
  603. // 本 query 读的是 **journal**(`dwf_event`),它与 conversation log 无关,且 cursor 永不失效:
  604. // journal 的 JournalStorePort 契约要求 sequence 只追加、
  605. // 跨 resume 从既有最大值继续、既不重置也不复用,既有条目的编号不变。也就是说一个
  606. // `(runId, sequence)` cursor 永远有效——没有任何"陈旧"可供防护。
  607. //
  608. // 更要紧的是:带上 `atLogEpoch` 不是无害的对称。按同族的读端契约,一次与 run 完全无关的
  609. // 会话 rewind(epoch 变化)会让详情页把**合法的** journal 页整页丢掉。宁可少一个字段,
  610. // 也不要携带一个在这里定义不出正确语义的字段。
  611. export type V4ConversationWorkflowRunEventsResult = z.infer<
  612. typeof v4ConversationWorkflowRunEventsResultSchema
  613. >;
  614. // ── dwf run 枚举 ──
  615. // journal-backed 的重启后发现面:`workflowRuns` 投影是 memory-only(冷合并归类),
  616. // 重启后为空——工具卡 join 与 Resume 按钮的可用性只能从 dwf_run 行还原。与
  617. // workflowRunEvents 同族(只读、无状态、超时重发安全),同样刻意不是 v4 command,
  618. // 同样不带 atSeq/atLogEpoch(读 journal,与 conversation log 无关,见上一个 query 的论证)。
  619. // 新方法天然偏斜安全:旧桌面永远不会调用它。
  620. export const v4ConversationWorkflowRunsParamsSchema = z
  621. .object({
  622. sessionId: z.string().min(1),
  623. /** 返回条数上限;缺省与钳制在 CLI 侧(枚举面有界,绝不无界扫库)。 */
  624. limit: z.number().int().positive().max(64).optional(),
  625. })
  626. .strict();
  627. export type V4ConversationWorkflowRunsParams = z.infer<
  628. typeof v4ConversationWorkflowRunsParamsSchema
  629. >;
  630. export const v4ConversationWorkflowRunSummarySchema = z
  631. .object({
  632. runId: z.string().min(1),
  633. /** 发起 run 的 CreateWorkflow 工具调用 id(工具卡 → 详情页/Resume 的关联键);老 run 缺席。 */
  634. toolCallId: z.string().min(1).optional(),
  635. /**
  636. * 展示标签,服务端读时派生(`name` → 脚本首行 → runId)。optional 是偏斜安全:
  637. * 老 CLI 不发这个键,读侧回落 runId——少一个标签是退化,不是错误。
  638. * 上限与派生侧的 80 字符对齐后留一倍余量(用户起的 `name` 不受派生上限约束)。
  639. */
  640. label: z.string().min(1).max(160).optional(),
  641. /** 最后更新时间(epoch 毫秒,journal 的 `dwf_run.time_updated`)。缺席即不显示时间。 */
  642. updatedAt: z.number().int().nonnegative().optional(),
  643. // 与 workflowRuns 投影同一套五值词汇;
  644. // 此查询使用独立的 schema,新增查询状态不改变投影侧的状态键。
  645. status: z.enum(["completed", "errored", "pending", "running", "stopped"]),
  646. /** `status === "stopped"` 才在场。词表与观察面共用一份——这里曾各抄一遍,于是引擎多出
  647. * `superseded` 时这份 strict schema 把整页 run 目录拒掉(桌面端表现为
  648. * 「读取 run 摘要失败」,任务列表计数与目录页一起空白)。 */
  649. stopReason: z.enum(WORKFLOW_RUN_STOP_REASONS).optional(),
  650. // lineage:修订出来的 run 带前驱,
  651. // 被替代的 run 带后继(只随 `stopReason: "superseded"`)。两者 optional:老 CLI 不发。
  652. resumedFrom: z.string().min(1).optional(),
  653. supersededBy: z.string().min(1).optional(),
  654. /** errored / stopped(provider|interrupted) 的结构化失败编码(`ProviderStop` / `Interrupted` …)。 */
  655. failureCode: z.string().min(1).max(64).optional(),
  656. failureMessage: z.string().max(2048).optional(),
  657. /** 是否可恢复。CLI 按 resume 门的同一个谓词算好——UI 绝不自行推导(两处谓词会漂移)。 */
  658. resumable: z.boolean(),
  659. })
  660. .strict();
  661. export type V4ConversationWorkflowRunSummary = z.infer<
  662. typeof v4ConversationWorkflowRunSummarySchema
  663. >;
  664. export const v4ConversationWorkflowRunsResultSchema = z
  665. .object({
  666. /** 最近更新在前(排序在存储层)。 */
  667. runs: z.array(v4ConversationWorkflowRunSummarySchema),
  668. })
  669. .strict();
  670. export type V4ConversationWorkflowRunsResult = z.infer<
  671. typeof v4ConversationWorkflowRunsResultSchema
  672. >;
  673. export const v4ConversationFileRewindPreviewParamsSchema = z
  674. .object({
  675. sessionId: z.string().min(1),
  676. target: conversationRowTargetSchema,
  677. baseRevision: z.number().int().nonnegative(),
  678. baseLogEpoch: z.string().trim().min(1),
  679. })
  680. .strict();
  681. export type V4ConversationFileRewindPreviewParams = z.infer<
  682. typeof v4ConversationFileRewindPreviewParamsSchema
  683. >;
  684. const v4WorkspaceFileRewindSafeFileSchema = z
  685. .object({
  686. action: z.enum(["restore", "delete"]),
  687. operationCount: z.number().int().nonnegative(),
  688. path: z.string().min(1),
  689. toolNames: z.array(z.string()),
  690. })
  691. .strict();
  692. const v4WorkspaceFileRewindUnsafeFileSchema = z
  693. .object({
  694. currentHash: z.string().optional(),
  695. expectedHash: z.string().optional(),
  696. message: z.string().optional(),
  697. operationCount: z.number().int().nonnegative(),
  698. path: z.string().min(1),
  699. reason: z.enum([
  700. "checkpoint_missing",
  701. "checkpoint_unreadable",
  702. "external_modified",
  703. "file_read_failed",
  704. "unsupported_checkpoint",
  705. ]),
  706. toolNames: z.array(z.string()),
  707. })
  708. .strict();
  709. const v4WorkspaceFileRewindIgnoredFileSchema = z
  710. .object({
  711. operationCount: z.number().int().nonnegative(),
  712. path: z.string().min(1),
  713. reason: z.literal("bash_ignored"),
  714. toolNames: z.array(z.string()),
  715. })
  716. .strict();
  717. export const v4ConversationFileRewindPreviewResultSchema = z
  718. .object({
  719. canApply: z.boolean(),
  720. ignoredFiles: z.array(v4WorkspaceFileRewindIgnoredFileSchema),
  721. safeFiles: z.array(v4WorkspaceFileRewindSafeFileSchema),
  722. unsafeFiles: z.array(v4WorkspaceFileRewindUnsafeFileSchema),
  723. })
  724. .strict();
  725. export type V4ConversationFileRewindPreviewResult = z.infer<
  726. typeof v4ConversationFileRewindPreviewResultSchema
  727. >;
  728. // ── usage query──
  729. // app 级用量聚合:range/timeZone 入参与旧 usage/stats 同形(消费者语义不变),
  730. // 结果 = AppUsageSnapshot(形状归属中性模块 usage-stats.ts,不与旧词表文件耦合)。
  731. export const v4UsageStatsParamsSchema = z
  732. .object({
  733. range: z.enum(APP_USAGE_RANGES),
  734. timeZone: z.string().optional(),
  735. })
  736. .strict();
  737. export type V4UsageStatsParams = z.infer<typeof v4UsageStatsParamsSchema>;
  738. export const v4UsageStatsResultSchema = appUsageSnapshotSchema;
  739. export type V4UsageStatsResult = z.infer<typeof v4UsageStatsResultSchema>;
  740. // 会话级 token 用量(旧 session/usage 的 v4 名字空间落位:会话是协议一等概念,
  741. // task 是 UI 投影概念不进协议词表)。字段与旧 result 同形,旧 schema 随词一起死。
  742. export const v4ConversationUsageParamsSchema = z
  743. .object({
  744. sessionId: z.string().min(1),
  745. })
  746. .strict();
  747. export type V4ConversationUsageParams = z.infer<typeof v4ConversationUsageParamsSchema>;
  748. export const v4ConversationUsageResultSchema = z
  749. .object({
  750. sessionId: z.string().min(1),
  751. totalTokens: z.number().int().nonnegative(),
  752. inputTokens: z.number().int().nonnegative(),
  753. outputTokens: z.number().int().nonnegative(),
  754. reasoningTokens: z.number().int().nonnegative(),
  755. cacheCreationTokens: z.number().int().nonnegative(),
  756. cacheReadTokens: z.number().int().nonnegative(),
  757. modelRequestCount: z.number().int().nonnegative(),
  758. modelErrorCount: z.number().int().nonnegative(),
  759. inputBaselineBySource: z.record(z.string(), z.number().int().nonnegative()),
  760. })
  761. .strict();
  762. export type V4ConversationUsageResult = z.infer<typeof v4ConversationUsageResultSchema>;
  763. // ── 附件上行事务 ──
  764. // UI 高层仍用 put(input)->ref;这份 full-data schema 只描述 renderer 内部调用,绝不作为
  765. // production RPC method。wire 只能用 begin/chunk/commit/abort。
  766. export const v4AttachmentPutParamsSchema = z
  767. .object({
  768. sessionId: z.string().min(1),
  769. fileName: z.string().min(1),
  770. mime: z.string().min(1),
  771. // base64(不带 data: 前缀);解码后字节数 ≤ PROTOCOL_V4_LIMITS.attachmentMaxBytes。
  772. dataBase64: z.string().min(1),
  773. })
  774. .strict();
  775. export type V4AttachmentPutParams = z.infer<typeof v4AttachmentPutParamsSchema>;
  776. export const v4AttachmentPutResultSchema = z.object({
  777. ref: z.string().min(1),
  778. });
  779. export type V4AttachmentPutResult = z.infer<typeof v4AttachmentPutResultSchema>;
  780. const v4AttachmentUploadIdSchema = z
  781. .string()
  782. .min(1)
  783. .max(128)
  784. .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/);
  785. const v4AttachmentChecksumSchema = z.string().regex(/^sha256:[0-9a-f]{64}$/);
  786. export const v4AttachmentBeginParamsSchema = z
  787. .object({
  788. connectionId: z.string().min(1),
  789. uploadId: v4AttachmentUploadIdSchema,
  790. sessionId: z.string().min(1),
  791. fileName: z
  792. .string()
  793. .min(1)
  794. .max(255)
  795. .regex(/^[^\0\r\n]+$/),
  796. mime: z
  797. .string()
  798. .min(3)
  799. .max(255)
  800. .regex(/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/),
  801. totalBytes: z.number().int().min(0).max(PROTOCOL_V4_LIMITS.attachmentMaxBytes),
  802. totalChunks: z.number().int().min(0).max(PROTOCOL_V4_LIMITS.attachmentUploadMaxChunks),
  803. checksum: v4AttachmentChecksumSchema,
  804. })
  805. .strict()
  806. .superRefine((value, context) => {
  807. if ((value.totalBytes === 0) !== (value.totalChunks === 0)) {
  808. context.addIssue({
  809. code: "custom",
  810. message: "zero-byte upload must declare zero chunks",
  811. path: ["totalChunks"],
  812. });
  813. }
  814. });
  815. export type V4AttachmentBeginParams = z.infer<typeof v4AttachmentBeginParamsSchema>;
  816. export const v4AttachmentBeginResultSchema = z.discriminatedUnion("state", [
  817. z
  818. .object({
  819. uploadId: v4AttachmentUploadIdSchema,
  820. state: z.literal("staging"),
  821. nextChunkIndex: z.number().int().nonnegative(),
  822. })
  823. .strict(),
  824. z
  825. .object({
  826. uploadId: v4AttachmentUploadIdSchema,
  827. state: z.literal("committed"),
  828. nextChunkIndex: z.number().int().nonnegative(),
  829. ref: z.string().min(1),
  830. })
  831. .strict(),
  832. ]);
  833. export type V4AttachmentBeginResult = z.infer<typeof v4AttachmentBeginResultSchema>;
  834. function decodedBase64ByteLength(value: string): number | null {
  835. if (value.length === 0) return 0;
  836. if (value.length % 4 !== 0) return null;
  837. const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
  838. const contentLength = value.length - padding;
  839. for (let index = 0; index < contentLength; index += 1) {
  840. const code = value.charCodeAt(index);
  841. const valid =
  842. (code >= 65 && code <= 90) ||
  843. (code >= 97 && code <= 122) ||
  844. (code >= 48 && code <= 57) ||
  845. code === 43 ||
  846. code === 47;
  847. if (!valid) return null;
  848. }
  849. for (let index = contentLength; index < value.length; index += 1) {
  850. if (value.charCodeAt(index) !== 61) return null;
  851. }
  852. return (value.length / 4) * 3 - padding;
  853. }
  854. export const v4AttachmentChunkParamsSchema = z
  855. .object({
  856. connectionId: z.string().min(1),
  857. uploadId: v4AttachmentUploadIdSchema,
  858. sessionId: z.string().min(1),
  859. chunkIndex: z.number().int().nonnegative(),
  860. dataBase64: z.string(),
  861. })
  862. .strict()
  863. .superRefine((value, context) => {
  864. const decodedBytes = decodedBase64ByteLength(value.dataBase64);
  865. if (decodedBytes === null) {
  866. context.addIssue({ code: "custom", message: "invalid base64", path: ["dataBase64"] });
  867. return;
  868. }
  869. if (decodedBytes > PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes) {
  870. context.addIssue({
  871. code: "too_big",
  872. maximum: PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  873. origin: "string",
  874. inclusive: true,
  875. message: "attachment chunk exceeds decoded byte limit",
  876. path: ["dataBase64"],
  877. });
  878. }
  879. });
  880. export type V4AttachmentChunkParams = z.infer<typeof v4AttachmentChunkParamsSchema>;
  881. export const v4AttachmentChunkResultSchema = z
  882. .object({
  883. uploadId: v4AttachmentUploadIdSchema,
  884. nextChunkIndex: z.number().int().nonnegative(),
  885. })
  886. .strict();
  887. export type V4AttachmentChunkResult = z.infer<typeof v4AttachmentChunkResultSchema>;
  888. const v4AttachmentTerminalParamsSchema = z
  889. .object({
  890. connectionId: z.string().min(1),
  891. uploadId: v4AttachmentUploadIdSchema,
  892. sessionId: z.string().min(1),
  893. })
  894. .strict();
  895. export const v4AttachmentCommitParamsSchema = v4AttachmentTerminalParamsSchema;
  896. export type V4AttachmentCommitParams = z.infer<typeof v4AttachmentCommitParamsSchema>;
  897. export const v4AttachmentCommitResultSchema = v4AttachmentPutResultSchema.strict();
  898. export type V4AttachmentCommitResult = z.infer<typeof v4AttachmentCommitResultSchema>;
  899. export const v4AttachmentAbortParamsSchema = v4AttachmentTerminalParamsSchema;
  900. export type V4AttachmentAbortParams = z.infer<typeof v4AttachmentAbortParamsSchema>;
  901. export const v4AttachmentAbortResultSchema = z.object({}).strict();
  902. /** 已发送 image/video/PDF 预览 query;ref 必须由 CLI 对当前 session projection 再授权。 */
  903. export const v4AttachmentReadParamsSchema = z
  904. .object({
  905. sessionId: z.string().min(1),
  906. ref: z.string().min(1),
  907. // 新 renderer 用稳定 row 身份 + 附件序号消除同一路径跨轮歧义;两者必须成对出现。
  908. target: conversationRowTargetSchema.optional(),
  909. attachmentIndex: z.number().int().nonnegative().optional(),
  910. offset: z.number().int().nonnegative(),
  911. limit: z.number().int().positive().max(PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes),
  912. })
  913. .strict()
  914. .superRefine((value, context) => {
  915. if ((value.target === undefined) === (value.attachmentIndex === undefined)) return;
  916. context.addIssue({
  917. code: "custom",
  918. message: "target and attachmentIndex must be provided together",
  919. path: value.target === undefined ? ["target"] : ["attachmentIndex"],
  920. });
  921. });
  922. export type V4AttachmentReadParams = z.infer<typeof v4AttachmentReadParamsSchema>;
  923. /** Desktop local 已发送视频 source query;远端与 Web 必须返回 chunked。PDF 始终走 chunked。 */
  924. export const v4AttachmentPreviewSourceParamsSchema = z
  925. .object({
  926. sessionId: z.string().min(1),
  927. ref: z.string().min(1),
  928. target: conversationRowTargetSchema.optional(),
  929. attachmentIndex: z.number().int().nonnegative().optional(),
  930. clientMode: z.enum(["desktop-continuous", "web-remote-replayable"]),
  931. })
  932. .strict()
  933. .superRefine((value, context) => {
  934. if ((value.target === undefined) === (value.attachmentIndex === undefined)) return;
  935. context.addIssue({
  936. code: "custom",
  937. message: "target and attachmentIndex must be provided together",
  938. path: value.target === undefined ? ["target"] : ["attachmentIndex"],
  939. });
  940. });
  941. export type V4AttachmentPreviewSourceParams = z.infer<typeof v4AttachmentPreviewSourceParamsSchema>;
  942. export const v4AttachmentPreviewSourceResultSchema = z.union([
  943. z
  944. .object({
  945. kind: z.literal("local_path"),
  946. path: z.string().min(1),
  947. mediaType: z.string().refine((value) => value.startsWith("video/"), {
  948. message: "local attachment preview only supports video media types",
  949. }),
  950. })
  951. .strict(),
  952. z.object({ kind: z.literal("chunked") }).strict(),
  953. ]);
  954. export type V4AttachmentPreviewSourceResult = z.infer<typeof v4AttachmentPreviewSourceResultSchema>;
  955. export const v4AttachmentReadResultSchema = z
  956. .object({
  957. dataBase64: z.string(),
  958. mediaType: z
  959. .string()
  960. .refine(
  961. (value) =>
  962. value.startsWith("image/") ||
  963. value.startsWith("video/") ||
  964. value.split(";", 1)[0]?.trim().toLowerCase() === "application/pdf" ||
  965. value.split(";", 1)[0]?.trim().toLowerCase() === "text/plain",
  966. "attachment preview only supports image/video/pdf/plain text types",
  967. ),
  968. totalBytes: z.number().int().nonnegative().max(PROTOCOL_V4_LIMITS.attachmentPreviewMaxBytes),
  969. nextOffset: z.number().int().positive().nullable(),
  970. })
  971. .strict()
  972. .superRefine((value, context) => {
  973. if (
  974. // 根因:运行时已支持材料文本,响应 schema 仍只接受媒体,导致跨进程预览失败。
  975. (value.mediaType.startsWith("image/") ||
  976. value.mediaType.split(";", 1)[0]?.trim().toLowerCase() === "text/plain") &&
  977. value.totalBytes > PROTOCOL_V4_LIMITS.attachmentMaxBytes
  978. ) {
  979. context.addIssue({
  980. code: "too_big",
  981. maximum: PROTOCOL_V4_LIMITS.attachmentMaxBytes,
  982. origin: "number",
  983. inclusive: true,
  984. message: "image/text preview exceeds total byte limit",
  985. path: ["totalBytes"],
  986. });
  987. }
  988. const decodedBytes = decodedBase64ByteLength(value.dataBase64);
  989. if (decodedBytes === null) {
  990. context.addIssue({ code: "custom", message: "invalid base64", path: ["dataBase64"] });
  991. return;
  992. }
  993. if (decodedBytes > PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes) {
  994. context.addIssue({
  995. code: "too_big",
  996. maximum: PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  997. origin: "string",
  998. inclusive: true,
  999. message: "attachment read chunk exceeds decoded byte limit",
  1000. path: ["dataBase64"],
  1001. });
  1002. }
  1003. if (value.nextOffset !== null && value.nextOffset > value.totalBytes) {
  1004. context.addIssue({
  1005. code: "custom",
  1006. message: "nextOffset exceeds totalBytes",
  1007. path: ["nextOffset"],
  1008. });
  1009. }
  1010. });
  1011. export type V4AttachmentReadResult = z.infer<typeof v4AttachmentReadResultSchema>;
  1012. /** Share 读取用户输入附件,允许任意已授权 MIME,不改变媒体预览 read 的语义。 */
  1013. export const v4ConversationAttachmentReadParamsSchema = z
  1014. .object({
  1015. sessionId: z.string().min(1),
  1016. ref: z.string().min(1),
  1017. target: conversationRowTargetSchema,
  1018. attachmentIndex: z.number().int().nonnegative(),
  1019. offset: z.number().int().nonnegative(),
  1020. limit: z.number().int().positive().max(PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes),
  1021. })
  1022. .strict();
  1023. export type V4ConversationAttachmentReadParams = z.infer<
  1024. typeof v4ConversationAttachmentReadParamsSchema
  1025. >;
  1026. export const v4ConversationAttachmentReadResultSchema = z
  1027. .object({
  1028. dataBase64: z.string(),
  1029. mediaType: z.string().min(1),
  1030. totalBytes: z.number().int().nonnegative().max(PROTOCOL_V4_LIMITS.attachmentPreviewMaxBytes),
  1031. nextOffset: z.number().int().positive().nullable(),
  1032. })
  1033. .strict()
  1034. .superRefine((value, context) => {
  1035. const decodedBytes = decodedBase64ByteLength(value.dataBase64);
  1036. if (decodedBytes === null) {
  1037. context.addIssue({ code: "custom", message: "invalid base64", path: ["dataBase64"] });
  1038. return;
  1039. }
  1040. if (decodedBytes > PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes) {
  1041. context.addIssue({
  1042. code: "too_big",
  1043. maximum: PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  1044. origin: "string",
  1045. inclusive: true,
  1046. message: "attachment read chunk exceeds decoded byte limit",
  1047. path: ["dataBase64"],
  1048. });
  1049. }
  1050. if (value.nextOffset !== null && value.nextOffset > value.totalBytes) {
  1051. context.addIssue({
  1052. code: "custom",
  1053. message: "nextOffset exceeds totalBytes",
  1054. path: ["nextOffset"],
  1055. });
  1056. }
  1057. });
  1058. export type V4ConversationAttachmentReadResult = z.infer<
  1059. typeof v4ConversationAttachmentReadResultSchema
  1060. >;
  1061. /** Share 选择阶段的 metadata-only 附件检查。 */
  1062. export const v4ConversationAttachmentStatParamsSchema = z
  1063. .object({
  1064. sessionId: z.string().min(1),
  1065. ref: z.string().min(1),
  1066. target: conversationRowTargetSchema,
  1067. attachmentIndex: z.number().int().nonnegative(),
  1068. })
  1069. .strict();
  1070. export type V4ConversationAttachmentStatParams = z.infer<
  1071. typeof v4ConversationAttachmentStatParamsSchema
  1072. >;
  1073. export const v4ConversationAttachmentStatResultSchema = z
  1074. .object({
  1075. mediaType: z.string().min(1),
  1076. // stat 是 metadata-only 探测,必须能表达超过传输上限的真实大小,否则
  1077. // 「已知容量超限」无法在选择阶段作为阻断项呈现(见 attachmentStatMaxBytes 注释)。
  1078. totalBytes: z.number().int().nonnegative().max(PROTOCOL_V4_LIMITS.attachmentStatMaxBytes),
  1079. mtimeMs: z.number().finite().optional(),
  1080. })
  1081. .strict();
  1082. export type V4ConversationAttachmentStatResult = z.infer<
  1083. typeof v4ConversationAttachmentStatResultSchema
  1084. >;
  1085. /** conversation topic key 构造(与 parseConversationTopic 对偶)。 */
  1086. export function conversationTopic(sessionId: string): string {
  1087. return `conversation/${sessionId}`;
  1088. }
  1089. /** conversation topic key 解析("conversation/<sessionId>")。 */
  1090. export function parseConversationTopic(topic: string): string | null {
  1091. if (!topic.startsWith("conversation/")) return null;
  1092. const sessionId = topic.slice("conversation/".length);
  1093. return sessionId.length > 0 ? sessionId : null;
  1094. }