fake-provider-wire.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /**
  2. * 假 provider 服务器的 wire 帧(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Verification」):Anthropic
  3. * Messages 与 OpenAI chat completions 两套成功帧 / 流内错误帧 / 业务错误体。故障层与格式无关,
  4. * 只有这里分两套;写法参考 adapters/tests/model-execution.test.ts 的 `sseFrame`(家规不跨包引用
  5. * 测试树,所以重写一遍)。
  6. */
  7. import { SUBMIT_RESULT_TOOL_NAME } from "@zcode/contracts";
  8. export type WireFormat = "anthropic-messages" | "openai-chat-completions";
  9. export interface CannedModelOptions {
  10. /** K:每个子代理的空转轮数,缺省 3。 */
  11. turns?: number;
  12. /** submit_result 的 payload,缺省 `{ note: "done" }`。 */
  13. submitPayload?: unknown;
  14. /** 「可见输出」帧里的文本,缺省 "Working."。 */
  15. visibleText?: string;
  16. }
  17. const DEFAULT_CANNED_TURNS = 3;
  18. const DEFAULT_SUBMIT_PAYLOAD: { note: string } = { note: "done" };
  19. const CANNED_GLOB_INPUT: { pattern: string } = { pattern: "**/*.md" };
  20. export const DEFAULT_VISIBLE_TEXT = "Working.";
  21. const MODEL_NAME = "alpha";
  22. const USAGE_IN = 12;
  23. const USAGE_OUT = 8;
  24. export const SSE_HEADERS = {
  25. "cache-control": "no-cache",
  26. "content-type": "text/event-stream; charset=utf-8",
  27. } as const;
  28. interface CannedTurn {
  29. toolName: string;
  30. toolInput: unknown;
  31. toolCallId: string;
  32. }
  33. /** 罐头模型:对话进度 → 这一轮该发哪个工具调用。纯函数。 */
  34. export function cannedTurn(toolResultCount: number, options: CannedModelOptions): CannedTurn {
  35. const turns = options.turns ?? DEFAULT_CANNED_TURNS;
  36. if (toolResultCount < turns) {
  37. return {
  38. toolName: "Glob",
  39. toolInput: CANNED_GLOB_INPUT,
  40. toolCallId: `call-glob-${toolResultCount + 1}`,
  41. };
  42. }
  43. return {
  44. toolName: SUBMIT_RESULT_TOOL_NAME,
  45. toolInput: { result: options.submitPayload ?? DEFAULT_SUBMIT_PAYLOAD },
  46. toolCallId: `call-submit-${toolResultCount + 1}`,
  47. };
  48. }
  49. function sseFrame(event: string | undefined, data: unknown): string {
  50. const payload = typeof data === "string" ? data : JSON.stringify(data);
  51. return event === undefined ? `data: ${payload}\n\n` : `event: ${event}\ndata: ${payload}\n\n`;
  52. }
  53. // ————————————————————————————————————————————————————————————————
  54. // Anthropic Messages
  55. // ————————————————————————————————————————————————————————————————
  56. /** Anthropic 流的首帧(message_start):没有任何可见输出。 */
  57. function anthropicMessageStart(ordinal: number): string {
  58. return sseFrame("message_start", {
  59. type: "message_start",
  60. message: {
  61. id: `msg_${ordinal}`,
  62. type: "message",
  63. role: "assistant",
  64. model: MODEL_NAME,
  65. content: [],
  66. stop_reason: null,
  67. stop_sequence: null,
  68. usage: { input_tokens: USAGE_IN, output_tokens: 0 },
  69. },
  70. });
  71. }
  72. /** Anthropic 流的可见文本块(三帧)。 */
  73. function anthropicVisibleText(index: number, text: string): string {
  74. return [
  75. sseFrame("content_block_start", {
  76. type: "content_block_start",
  77. index,
  78. content_block: { type: "text", text: "" },
  79. }),
  80. sseFrame("content_block_delta", {
  81. type: "content_block_delta",
  82. index,
  83. delta: { type: "text_delta", text },
  84. }),
  85. sseFrame("content_block_stop", { type: "content_block_stop", index }),
  86. ].join("");
  87. }
  88. /** Anthropic 流的工具调用块 + 收尾(input 拆成两个 delta,逼真一点)。 */
  89. function anthropicToolUseFrames(index: number, turn: CannedTurn): string {
  90. const json = JSON.stringify(turn.toolInput);
  91. const half = Math.ceil(json.length / 2);
  92. return [
  93. sseFrame("content_block_start", {
  94. type: "content_block_start",
  95. index,
  96. content_block: { type: "tool_use", id: turn.toolCallId, name: turn.toolName, input: {} },
  97. }),
  98. sseFrame("content_block_delta", {
  99. type: "content_block_delta",
  100. index,
  101. delta: { type: "input_json_delta", partial_json: json.slice(0, half) },
  102. }),
  103. sseFrame("content_block_delta", {
  104. type: "content_block_delta",
  105. index,
  106. delta: { type: "input_json_delta", partial_json: json.slice(half) },
  107. }),
  108. sseFrame("content_block_stop", { type: "content_block_stop", index }),
  109. sseFrame("message_delta", {
  110. type: "message_delta",
  111. delta: { stop_reason: "tool_use", stop_sequence: null },
  112. usage: { output_tokens: USAGE_OUT },
  113. }),
  114. sseFrame("message_stop", { type: "message_stop" }),
  115. ].join("");
  116. }
  117. function anthropicNonStreamBody(ordinal: number, turn: CannedTurn): unknown {
  118. return {
  119. id: `msg_${ordinal}`,
  120. type: "message",
  121. role: "assistant",
  122. model: MODEL_NAME,
  123. content: [{ type: "tool_use", id: turn.toolCallId, name: turn.toolName, input: turn.toolInput }],
  124. stop_reason: "tool_use",
  125. stop_sequence: null,
  126. usage: { input_tokens: USAGE_IN, output_tokens: USAGE_OUT },
  127. };
  128. }
  129. // ————————————————————————————————————————————————————————————————
  130. // OpenAI chat completions
  131. // ————————————————————————————————————————————————————————————————
  132. function openaiChunk(
  133. ordinal: number,
  134. choice: Record<string, unknown> | undefined,
  135. extra?: Record<string, unknown>,
  136. ): string {
  137. return sseFrame(undefined, {
  138. id: `chatcmpl-${ordinal}`,
  139. object: "chat.completion.chunk",
  140. created: 1,
  141. model: MODEL_NAME,
  142. choices: choice === undefined ? [] : [{ index: 0, finish_reason: null, ...choice }],
  143. ...extra,
  144. });
  145. }
  146. /** OpenAI 流的首帧(只带 role,没有任何可见内容)。 */
  147. function openaiRoleChunk(ordinal: number): string {
  148. return openaiChunk(ordinal, { delta: { role: "assistant", content: "" } });
  149. }
  150. function openaiVisibleChunk(ordinal: number, text: string): string {
  151. return openaiChunk(ordinal, { delta: { content: text } });
  152. }
  153. /** OpenAI 流的工具调用块 + finish + usage + [DONE]。 */
  154. function openaiToolCallFrames(ordinal: number, turn: CannedTurn): string {
  155. const json = JSON.stringify(turn.toolInput);
  156. const half = Math.ceil(json.length / 2);
  157. return [
  158. openaiChunk(ordinal, {
  159. delta: {
  160. tool_calls: [
  161. {
  162. index: 0,
  163. id: turn.toolCallId,
  164. type: "function",
  165. function: { name: turn.toolName, arguments: json.slice(0, half) },
  166. },
  167. ],
  168. },
  169. }),
  170. openaiChunk(ordinal, {
  171. delta: { tool_calls: [{ index: 0, function: { arguments: json.slice(half) } }] },
  172. }),
  173. openaiChunk(ordinal, { delta: {}, finish_reason: "tool_calls" }),
  174. openaiChunk(ordinal, undefined, {
  175. usage: { prompt_tokens: USAGE_IN, completion_tokens: USAGE_OUT, total_tokens: USAGE_IN + USAGE_OUT },
  176. }),
  177. "data: [DONE]\n\n",
  178. ].join("");
  179. }
  180. function openaiNonStreamBody(ordinal: number, turn: CannedTurn): unknown {
  181. return {
  182. id: `chatcmpl-${ordinal}`,
  183. object: "chat.completion",
  184. created: 1,
  185. model: MODEL_NAME,
  186. choices: [
  187. {
  188. index: 0,
  189. message: {
  190. role: "assistant",
  191. content: null,
  192. tool_calls: [
  193. {
  194. id: turn.toolCallId,
  195. type: "function",
  196. function: { name: turn.toolName, arguments: JSON.stringify(turn.toolInput) },
  197. },
  198. ],
  199. },
  200. finish_reason: "tool_calls",
  201. },
  202. ],
  203. usage: { prompt_tokens: USAGE_IN, completion_tokens: USAGE_OUT, total_tokens: USAGE_IN + USAGE_OUT },
  204. };
  205. }
  206. // ————————————————————————————————————————————————————————————————
  207. // 与格式相关的错误体
  208. // ————————————————————————————————————————————————————————————————
  209. /** 两种 wire 共用的首帧:有 message_start / role 帧但还没有任何可见输出。 */
  210. export function firstFrame(route: WireFormat, ordinal: number): string {
  211. return route === "anthropic-messages" ? anthropicMessageStart(ordinal) : openaiRoleChunk(ordinal);
  212. }
  213. export function visibleFrame(route: WireFormat, ordinal: number, text: string): string {
  214. return route === "anthropic-messages" ? anthropicVisibleText(0, text) : openaiVisibleChunk(ordinal, text);
  215. }
  216. export function successStream(route: WireFormat, ordinal: number, turn: CannedTurn): string {
  217. return route === "anthropic-messages"
  218. ? anthropicMessageStart(ordinal) + anthropicToolUseFrames(0, turn)
  219. : openaiRoleChunk(ordinal) + openaiToolCallFrames(ordinal, turn);
  220. }
  221. export function successBody(route: WireFormat, ordinal: number, turn: CannedTurn): string {
  222. return JSON.stringify(
  223. route === "anthropic-messages" ? anthropicNonStreamBody(ordinal, turn) : openaiNonStreamBody(ordinal, turn),
  224. );
  225. }
  226. /**
  227. * 流内错误帧:两种 wire 都把 code 放在 `error.code`——这是 `readProviderBusinessFailureFromBody`
  228. * 的 error.code 分支(model-execution.ts),SSE 帧解析器复用同一函数,所以 providerCode 一定落到。
  229. */
  230. export function streamErrorFrame(route: WireFormat, code: string, message: string): string {
  231. if (route === "anthropic-messages") {
  232. return sseFrame("error", {
  233. type: "error",
  234. error: { type: "rate_limit_error", code, message },
  235. });
  236. }
  237. return sseFrame(undefined, { error: { code, message } });
  238. }
  239. /** 非 2xx 的业务错误体:`error-object`(BigModel 两种端点共同的形状)或 Start Plan 网关的 `top-level`。 */
  240. export function businessErrorBody(verdict: {
  241. status: number;
  242. code?: string;
  243. message?: string;
  244. bodyShape?: "error-object" | "top-level";
  245. }): string {
  246. const message = verdict.message ?? `fake provider status ${verdict.status}`;
  247. if (verdict.bodyShape === "top-level") {
  248. return JSON.stringify({
  249. ...(verdict.code === undefined ? {} : { code: Number(verdict.code) }),
  250. msg: message,
  251. });
  252. }
  253. return JSON.stringify({
  254. error: {
  255. ...(verdict.code === undefined ? {} : { code: verdict.code }),
  256. message,
  257. type: "error",
  258. },
  259. });
  260. }