bash-model-result-wire-fixture.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { createServer } from "node:http";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, beforeEach, expect, vi } from "vitest";
  6. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  7. import {
  8. createSessionId,
  9. type HookMatcherConfig,
  10. type HooksRuntimeConfigPatch,
  11. } from "@zcode/contracts";
  12. import {
  13. ApiKeyAccessConfig,
  14. ModelConfig,
  15. ModelOptionSpecsConfig,
  16. ModelPropertiesConfig,
  17. ProviderApiConfig,
  18. ProviderConfig,
  19. ProviderRegistry,
  20. } from "@zcode/provider";
  21. import { createZCodeApp } from "../src/app/create-app.js";
  22. import { createRuntimeAiSdkModelExecutionConfig } from "../src/model-config.js";
  23. import { createModelAdapter } from "../src/model-factory.js";
  24. const PROVIDER_ID = "bash-wire";
  25. export const SLEEP_ADVICE =
  26. "To wait for a condition, run an until-loop with run_in_background: true (e.g. `until <check>; do sleep 2; done`); you are notified when it exits. To wait for a command you started, use run_in_background: true. Do not chain shorter sleeps to work around this block.";
  27. const MODEL_ID = "bash-wire-model";
  28. export type Block = Record<string, unknown> & { type?: string };
  29. type WireMessage = { role: string; content: string | Block[] };
  30. export type WireBody = {
  31. system?: Block[];
  32. messages: WireMessage[];
  33. tools?: Array<{ name: string; description?: string }>;
  34. };
  35. type Reply = { content: Block[]; stop: "tool_use" | "end_turn" };
  36. interface Fixture {
  37. root: string;
  38. workspace: string;
  39. bodies: WireBody[];
  40. /** 按收到的请求序号(从 1 开始)给出回复;没有时回复一段文字。 */
  41. script: Map<number, Reply>;
  42. /** 按请求内容给出回复,优先于 script;返回 undefined 时再查 script。 */
  43. respond?: (body: WireBody) => Reply | undefined;
  44. /** 每次回复前把伪造的 Date 往后拨这么多毫秒(模拟模型响应耗时);需要先 vi.useFakeTimers。 */
  45. responseMs?: number;
  46. /** until:关闭 app 之前等到满足条件的请求(例如后台任务的通知轮)。 */
  47. run(
  48. prompt: string,
  49. options?: { resume?: boolean; until?: (body: WireBody) => boolean },
  50. ): Promise<void>;
  51. close(): Promise<void>;
  52. /** recordHooks 时 Hook 收到的 stdin,按运行顺序。 */
  53. hookInputs(): Promise<Array<Record<string, unknown>>>;
  54. }
  55. let fixture: Fixture | undefined;
  56. let previousStorageDir: string | undefined;
  57. export async function createFixture(options: { recordHooks?: boolean } = {}): Promise<Fixture> {
  58. const root = await mkdtemp(join(tmpdir(), "zcode-bash-wire-"));
  59. const workspace = join(root, "workspace");
  60. const storageDir = join(root, "storage");
  61. await mkdir(workspace, { recursive: true });
  62. process.env.ZCODE_STORAGE_DIR = storageDir;
  63. const hookLog = join(root, "hook-inputs.jsonl");
  64. const hooks = options.recordHooks ? await recordingHooks(root, hookLog) : undefined;
  65. const bodies: WireBody[] = [];
  66. const script = new Map<number, Reply>();
  67. const waiters: Array<() => void> = [];
  68. const server = createServer(async (req, res) => {
  69. let raw = "";
  70. for await (const chunk of req) raw += chunk;
  71. if (!req.url?.includes("/messages")) {
  72. res.writeHead(404).end("{}");
  73. return;
  74. }
  75. const body = JSON.parse(raw) as WireBody & { model: string };
  76. bodies.push(body);
  77. if (fixture?.responseMs) vi.setSystemTime(Date.now() + fixture.responseMs);
  78. for (const wake of waiters.splice(0)) wake();
  79. const reply = fixture?.respond?.(body) ??
  80. script.get(bodies.length) ?? {
  81. content: [{ type: "text", text: "done" }],
  82. stop: "end_turn",
  83. };
  84. res.writeHead(200, { "content-type": "application/json" });
  85. res.end(
  86. JSON.stringify({
  87. id: `msg_${bodies.length}`,
  88. type: "message",
  89. role: "assistant",
  90. model: body.model,
  91. content: reply.content,
  92. stop_reason: reply.stop,
  93. stop_sequence: null,
  94. usage: { input_tokens: 100, output_tokens: 5 },
  95. }),
  96. );
  97. });
  98. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  99. const address = server.address();
  100. if (!address || typeof address === "string") throw new Error("mock server has no port");
  101. const registry = providerRegistry(`http://127.0.0.1:${address.port}/v1`);
  102. const sessionId = createSessionId("bash-wire");
  103. // shell 用隔离的 HOME,不读本机 shell 配置;PATH 等其余环境沿用测试进程。
  104. const home = join(root, "home");
  105. await mkdir(home, { recursive: true });
  106. const env = { ...process.env, HOME: home, ZCODE_STORAGE_DIR: storageDir };
  107. const waitForRequest = (predicate: (body: WireBody) => boolean) =>
  108. waitFor(() => bodies.some(predicate), waiters);
  109. const run = async (
  110. prompt: string,
  111. options: { resume?: boolean; until?: (body: WireBody) => boolean } = {},
  112. ) => {
  113. const sessionStore = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  114. const app = await createZCodeApp({
  115. env,
  116. modelAdapter: createModelAdapter({
  117. env,
  118. executionConfig: createRuntimeAiSdkModelExecutionConfig(env),
  119. }),
  120. providerRegistry: registry,
  121. pluginStorageRoot: join(root, "plugins"),
  122. readSubagentRuntimeConfig: async () => ({ kind: "built-in-fallback" }),
  123. runtimeConfig: {
  124. mcp: { enabled: false },
  125. memory: { enabled: false },
  126. mode: "yolo",
  127. modelSelection: {
  128. providerId: PROVIDER_ID,
  129. modelId: MODEL_ID,
  130. options: { reasoningLevel: "disabled" },
  131. },
  132. modelStreaming: "off",
  133. storage: { dir: storageDir },
  134. subagents: { enabled: true },
  135. titleGeneration: { enabled: false },
  136. workingDirectory: workspace,
  137. ...(hooks ? { hooks } : {}),
  138. },
  139. ...(options.resume ? { resume: true } : {}),
  140. sessionId,
  141. sessionStore,
  142. skipUserConfig: true,
  143. });
  144. try {
  145. await app.submitPrompt(prompt);
  146. if (options.until) {
  147. await waitForRequest(options.until);
  148. // 等这个请求所在的轮次结束再关闭;轮次中途关闭会留下中断标记,改变下一次请求。
  149. await waitFor(() => app.runtime.getActiveTurnInfo() === undefined);
  150. }
  151. } finally {
  152. await app.close?.();
  153. sessionStore.close();
  154. }
  155. };
  156. const close = async () => {
  157. server.closeAllConnections();
  158. await new Promise<void>((resolve) => server.close(() => resolve()));
  159. };
  160. const hookInputs = async () =>
  161. (await readFile(hookLog, "utf8"))
  162. .split("\n")
  163. .filter(Boolean)
  164. .map((line) => JSON.parse(line) as Record<string, unknown>);
  165. fixture = { root, workspace, bodies, script, run, close, hookInputs };
  166. return fixture;
  167. }
  168. /**
  169. * PostToolUse 与 PostToolUseFailure 各挂一个 process Hook:把 stdin 追加到 log,
  170. * 返回 `AUDIT_<事件名>` 作为 additionalContext。
  171. */
  172. async function recordingHooks(root: string, log: string): Promise<HooksRuntimeConfigPatch> {
  173. const script = join(root, "record-hook.mjs");
  174. await writeFile(
  175. script,
  176. [
  177. 'import { appendFileSync } from "node:fs";',
  178. 'let raw = "";',
  179. "for await (const chunk of process.stdin) raw += chunk;",
  180. "const input = JSON.parse(raw);",
  181. "appendFileSync(process.argv[2], JSON.stringify(input) + '\\n');",
  182. "const event = input.hook_event_name;",
  183. "process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: `AUDIT_${event}` } }));",
  184. ].join("\n"),
  185. );
  186. const matcher = (): HookMatcherConfig[] => [
  187. {
  188. matcher: "Bash",
  189. hooks: [
  190. { type: "process", command: process.execPath, args: [script, log], timeoutMs: 20_000 },
  191. ],
  192. },
  193. ];
  194. // runtimeConfig 直接传给 createZCodeApp,不经过默认配置层:输出上限与超时要写全,否则 stdout 读不到。
  195. return {
  196. enabled: true,
  197. events: { PostToolUse: matcher(), PostToolUseFailure: matcher() },
  198. maxOutputBytes: 32_768,
  199. timeoutMs: 60_000,
  200. };
  201. }
  202. /** 轮询条件;收到新请求时立即再查一次。 */
  203. async function waitFor(check: () => boolean, waiters: Array<() => void> = []): Promise<void> {
  204. const deadline = Date.now() + 15_000;
  205. while (!check()) {
  206. if (Date.now() > deadline) throw new Error("condition was not reached");
  207. await new Promise<void>((resolve) => {
  208. waiters.push(resolve);
  209. setTimeout(resolve, 50);
  210. });
  211. }
  212. }
  213. function providerRegistry(baseUrl: string): ProviderRegistry {
  214. return new ProviderRegistry([
  215. {
  216. providerId: PROVIDER_ID,
  217. config: new ProviderConfig({
  218. access: new ApiKeyAccessConfig({ apiKey: "wire-local-fake" }),
  219. api: new ProviderApiConfig({ type: "anthropic-messages", baseUrl }),
  220. models: [MODEL_ID],
  221. enabled: true,
  222. }),
  223. models: [
  224. {
  225. modelId: MODEL_ID,
  226. config: new ModelConfig({
  227. properties: new ModelPropertiesConfig({
  228. contextWindow: 1_000_000,
  229. inputFormat: { supportsText: true },
  230. outputFormat: { supportsText: true },
  231. supportsToolCall: true,
  232. supportsJsonSchemaOutput: true,
  233. supportsNativeWebSearch: false,
  234. supportsMidConversationSystem: true,
  235. }),
  236. optionSpecs: new ModelOptionSpecsConfig({
  237. reasoningLevel: { values: ["disabled"], map: "{}" },
  238. maxOutputTokens: { max: 10_000, map: '{"max_tokens": maxOutputTokens}' },
  239. }),
  240. }),
  241. },
  242. ],
  243. },
  244. ]);
  245. }
  246. export function bashCall(id: string, input: Record<string, unknown>): Reply {
  247. return {
  248. content: [{ type: "tool_use", id, name: "Bash", input: { description: id, ...input } }],
  249. stop: "tool_use",
  250. };
  251. }
  252. export function toolResult(body: WireBody, toolUseId: string): { is_error: boolean; text: string } {
  253. for (const message of body.messages) {
  254. if (!Array.isArray(message.content)) continue;
  255. for (const block of message.content) {
  256. if (block.type !== "tool_result" || block.tool_use_id !== toolUseId) continue;
  257. const content = block.content;
  258. const text = Array.isArray(content)
  259. ? (content as Block[]).map((item) => String(item.text ?? "")).join("")
  260. : String(content ?? "");
  261. return { is_error: block.is_error === true, text };
  262. }
  263. }
  264. throw new Error(`${toolUseId} has no tool_result`);
  265. }
  266. export function systemTexts(body: WireBody): string[] {
  267. return body.messages
  268. .filter((message) => message.role === "system")
  269. .map((message) =>
  270. typeof message.content === "string"
  271. ? message.content
  272. : message.content.map((block) => String(block.text ?? "")).join(""),
  273. );
  274. }
  275. /**
  276. * 冷恢复后的首个请求:重启前最后一个请求的 system 与 messages 原样在前,只在后面追加。
  277. * 缓存断点会移到最新的消息上,不算内容。is_error 也要相同:错误结果的标记随 completed part 持久化。
  278. */
  279. export function expectColdReplay(live: WireBody, resumed: WireBody) {
  280. expect(withoutVolatile(resumed.system)).toEqual(withoutVolatile(live.system));
  281. expect(withoutVolatile(resumed.messages.slice(0, live.messages.length))).toEqual(
  282. withoutVolatile(live.messages),
  283. );
  284. }
  285. function withoutVolatile(value: unknown): unknown {
  286. if (Array.isArray(value)) return value.map(withoutVolatile);
  287. if (!value || typeof value !== "object") return value;
  288. return Object.fromEntries(
  289. Object.entries(value)
  290. .filter(([key]) => key !== "cache_control")
  291. .map(([key, item]) => [key, withoutVolatile(item)]),
  292. );
  293. }
  294. export function expectNoTotalTokens(bodies: WireBody[]) {
  295. for (const body of bodies) expect(JSON.stringify(body)).not.toContain("<total_tokens>");
  296. }
  297. export function escapeRegExp(value: string): string {
  298. return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  299. }
  300. export function setupBashWireTest() {
  301. beforeEach(() => {
  302. previousStorageDir = process.env.ZCODE_STORAGE_DIR;
  303. });
  304. afterEach(async () => {
  305. if (previousStorageDir === undefined) delete process.env.ZCODE_STORAGE_DIR;
  306. else process.env.ZCODE_STORAGE_DIR = previousStorageDir;
  307. if (fixture) {
  308. await fixture.close();
  309. await rm(fixture.root, { recursive: true, force: true });
  310. }
  311. fixture = undefined;
  312. });
  313. }
  314. export async function assertSubagentBashText(runInBackground: boolean, expected: string) {
  315. const f = await createFixture();
  316. const isChild = (body: WireBody) => !(body.tools ?? []).some((tool) => tool.name === "Agent");
  317. let parentCalls = 0;
  318. let childCalls = 0;
  319. f.respond = (body) => {
  320. if (isChild(body)) {
  321. childCalls += 1;
  322. return childCalls === 1
  323. ? bashCall("toolu_child_bg", { command: "sleep 0.2", run_in_background: true })
  324. : undefined;
  325. }
  326. parentCalls += 1;
  327. if (parentCalls !== 1) return undefined;
  328. return {
  329. content: [
  330. {
  331. type: "tool_use",
  332. id: "toolu_agent",
  333. name: "Agent",
  334. input: {
  335. description: "child task",
  336. prompt: "Start the command in the background.",
  337. subagent_type: "general-purpose",
  338. run_in_background: runInBackground,
  339. },
  340. },
  341. ],
  342. stop: "tool_use",
  343. };
  344. };
  345. await f.run("launch the child", {
  346. until: () => f.bodies.filter(isChild).length >= 2,
  347. });
  348. const childResult = toolResult(f.bodies.filter(isChild)[1]!, "toolu_child_bg");
  349. expect(childResult.is_error).toBe(false);
  350. expect(childResult.text).toMatch(
  351. new RegExp(
  352. `^Command running in background with ID: \\S+\\. Output is being written to: \\S+\\. ${escapeRegExp(expected)} To check interim output, use Read on that file path\\.$`,
  353. ),
  354. );
  355. }