zcodeV4HostCommand.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // host(services 层)侧的 v4 命令信封构造与 ACK 收口共用件(send/交互回执收敛)。
  2. //
  3. // 与 renderer 的 packages/ui/src/v4/commandFactory.ts 平行:renderer 走浏览器
  4. // localStorage 持久化 clientId;host 进程用进程内稳定 clientId(host 重启 = 新提交端,
  5. // 幂等表以 commandId 为键不受影响)。不合并成一个实现的原因:ui 包不能被 services 反向依赖。
  6. import { randomBytes } from "node:crypto";
  7. import {
  8. COMMANDS_REQUIRING_BASE_REVISION,
  9. ROW_TARGETING_COMMANDS,
  10. type CommandAck,
  11. type CommandEnvelope,
  12. type CommandPayloadMap,
  13. type CommandType,
  14. } from "@zcode/shared/zcode-protocol-v4";
  15. const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
  16. /** uuid v7(RFC 9562):48-bit Unix ms 时间戳 + 74-bit 随机;与 renderer 工厂同构。 */
  17. export function uuidv7(now: number = Date.now()): string {
  18. const bytes = randomBytes(16);
  19. const ts = BigInt(now);
  20. bytes[0] = Number((ts >> 40n) & 0xffn);
  21. bytes[1] = Number((ts >> 32n) & 0xffn);
  22. bytes[2] = Number((ts >> 24n) & 0xffn);
  23. bytes[3] = Number((ts >> 16n) & 0xffn);
  24. bytes[4] = Number((ts >> 8n) & 0xffn);
  25. bytes[5] = Number(ts & 0xffn);
  26. bytes[6] = 0x70 | (bytes[6]! & 0x0f);
  27. bytes[8] = 0x80 | (bytes[8]! & 0x3f);
  28. let hex = "";
  29. for (const byte of bytes) hex += HEX[byte];
  30. return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
  31. }
  32. /** host services 进程稳定 clientId;pendingCommands 展示与幂等表以它区分提交端。 */
  33. const hostV4ClientId = `host-services-${uuidv7()}`;
  34. export function getHostV4ClientId(): string {
  35. return hostV4ClientId;
  36. }
  37. export interface CreateHostCommandEnvelopeInput<T extends CommandType> {
  38. type: T;
  39. payload: CommandPayloadMap[T];
  40. /** createSession 时为 null。 */
  41. sessionId: string | null;
  42. /**
  43. * 幂等键。手机 replayable 的 send_prompt 用 inputId(=traceId)作 commandId:
  44. * CLI 侧 sendText 以 commandId 为 inputId 起 turn,终态事件的 inputId 才能与
  45. * host command queue 的 traceId 对账收口(inputId→commandId 对齐)。
  46. * 缺省生成 uuid v7(stop/resolveInteraction 等一次性命令)。
  47. */
  48. commandId?: string;
  49. /** 手机 replayable 保留原提交端 clientId;缺省用 host 进程稳定 id。 */
  50. clientId?: string;
  51. baseRevision?: number;
  52. baseLogEpoch?: string;
  53. }
  54. /** 构造 host 侧命令信封;CAS 命令缺 baseRevision 就地抛出。 */
  55. export function createHostCommandEnvelope<T extends CommandType>(
  56. input: CreateHostCommandEnvelopeInput<T>,
  57. ): CommandEnvelope {
  58. if (COMMANDS_REQUIRING_BASE_REVISION.has(input.type) && input.baseRevision === undefined) {
  59. throw new Error(
  60. `command ${input.type} 是 CAS 命令,必须携带 baseRevision(10-protocol-spec §6.4)`,
  61. );
  62. }
  63. if (ROW_TARGETING_COMMANDS.has(input.type) && !input.baseLogEpoch) {
  64. throw new Error(
  65. `command ${input.type} 是 row target 命令,必须携带 baseLogEpoch`,
  66. );
  67. }
  68. return {
  69. commandId: input.commandId ?? uuidv7(),
  70. clientId: input.clientId ?? hostV4ClientId,
  71. sessionId: input.sessionId,
  72. ...(input.baseRevision !== undefined
  73. ? { baseRevision: input.baseRevision }
  74. : {}),
  75. ...(input.baseLogEpoch ? { baseLogEpoch: input.baseLogEpoch } : {}),
  76. type: input.type,
  77. payload: input.payload,
  78. issuedAt: Date.now(),
  79. };
  80. }
  81. /** v4 命令被服务端否决(rejected/stale/failed)。code 供调用方结构化分流,不匹配错误文案。 */
  82. export class ZCodeV4CommandRejectedError extends Error {
  83. readonly code = "ZCODE_V4_COMMAND_REJECTED";
  84. constructor(
  85. readonly commandType: CommandType,
  86. readonly ack: CommandAck,
  87. contextMessage: string,
  88. ) {
  89. super(
  90. `v4 command ${commandType} ${ack.status}` +
  91. `${ack.reasonCode ? ` (${ack.reasonCode})` : ""}` +
  92. `${ack.message ? `: ${ack.message}` : ""} — ${contextMessage}`,
  93. );
  94. this.name = "ZCodeV4CommandRejectedError";
  95. }
  96. }
  97. /**
  98. * ACK 错误映射(旧 op 抛错语义 → v4 六态):
  99. * - accepted:正常收口;duplicate:同 commandId 重试回放,幂等成功;
  100. * - noop:晚到应答/已收口,幂等成功(resolveInteraction 先到先得语义);
  101. * - rejected/stale/failed:抛结构化错误,reasonCode 原样携带给调用方。
  102. */
  103. export function assertV4CommandAckOk(
  104. commandType: CommandType,
  105. ack: CommandAck,
  106. contextMessage: string,
  107. ): CommandAck {
  108. if (ack.status === "accepted" || ack.status === "duplicate" || ack.status === "noop") {
  109. return ack;
  110. }
  111. throw new ZCodeV4CommandRejectedError(commandType, ack, contextMessage);
  112. }
  113. /**
  114. * CAS 命令的 host 侧提交(配置写下沉):host services 没有本地 v4 投影,
  115. * 拿不到当前 conversation revision——「stale ACK 必带 revisionAtDecision」
  116. * 用服务端回报的最新 revision 收敛重试,与 renderer 的 dispatchConfigCas 同构
  117. * (packages/ui/src/v4/SessionPane.tsx)。首发 baseRevision=0 作探测,典型路径一次
  118. * stale 即命中;每次尝试新 commandId(stale 裁决不进幂等表,语义等价且避免歧义)。
  119. * 旧 facade 从不带 expectedRevision(无 CAS),这里 stale 仅意味着并发推进而非冲突,
  120. * 重试即为「无 CAS 提交」语义的保真;连续用尽仅在病态并发下出现,按拒绝抛出。
  121. */
  122. export async function sendHostCasCommandV4<T extends CommandType>(input: {
  123. send: (envelope: CommandEnvelope) => Promise<CommandAck>;
  124. type: T;
  125. payload: CommandPayloadMap[T];
  126. sessionId: string;
  127. contextMessage: string;
  128. maxAttempts?: number;
  129. }): Promise<CommandAck> {
  130. const maxAttempts = input.maxAttempts ?? 4;
  131. let baseRevision = 0;
  132. let lastAck: CommandAck | null = null;
  133. for (let attempt = 0; attempt < maxAttempts; attempt++) {
  134. const ack = await input.send(
  135. createHostCommandEnvelope({
  136. type: input.type,
  137. payload: input.payload,
  138. sessionId: input.sessionId,
  139. baseRevision,
  140. }),
  141. );
  142. if (ack.status === "stale") {
  143. lastAck = ack;
  144. baseRevision = ack.revisionAtDecision;
  145. continue;
  146. }
  147. return assertV4CommandAckOk(input.type, ack, input.contextMessage);
  148. }
  149. throw new ZCodeV4CommandRejectedError(
  150. input.type,
  151. lastAck ?? {
  152. commandId: "",
  153. status: "stale",
  154. revisionAtDecision: baseRevision,
  155. },
  156. `${input.contextMessage}(连续 stale,放弃重试)`,
  157. );
  158. }