upstream-replay-server.ts 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. /* eslint-disable max-lines -- Upstream E2E 回放服务需要集中维护 fixture 匹配、capture artifact、chunk timeline 和 SSE 时间轴回放,拆开会让录制/回放协议更难追踪。 */
  2. import { randomUUID } from "node:crypto";
  3. import { readFileSync } from "node:fs";
  4. import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
  5. import type { AddressInfo } from "node:net";
  6. import { resolve } from "node:path";
  7. import type {
  8. E2ENetworkCaptureArtifact,
  9. E2ENetworkCaptureRecord,
  10. E2ENetworkCaptureResponseEvent,
  11. E2ENetworkResponseChunk,
  12. } from "./network-capture-proxy.js";
  13. import { writeE2EJsonFileAtomically } from "./e2e-atomic-json-file.js";
  14. import {
  15. redactE2ENetworkCaptureJson,
  16. redactE2ENetworkCaptureJsonText,
  17. sanitizeE2ENetworkCaptureHeaders,
  18. } from "./e2e-network-capture-redaction.js";
  19. import { resolveUpstreamModels } from "./upstream-recorded-models.js";
  20. // 夹具未写模型时,回放响应使用与 E2E 供应商相同的模型(环境变量或录制模型)。
  21. const DEFAULT_REPLAY_MODEL = resolveUpstreamModels().model;
  22. const LATEST_AGENT_ID_REPLAY_TOKEN = "{{latestAgentId}}";
  23. const LATEST_BASH_TASK_ID_REPLAY_TOKEN = "{{latestBashTaskId}}";
  24. const MEMORY_ROOT_REPLAY_TOKEN = "{{memoryRoot}}";
  25. const LATEST_AUTOMATION_ID_REPLAY_TOKEN = "{{latestAutomationId}}";
  26. const LATEST_WORKFLOW_RUN_ID_REPLAY_TOKEN = "{{latestWorkflowRunId}}";
  27. const BROWSER_FIXTURE_URL_REPLAY_TOKEN = "{{browserFixtureUrl}}";
  28. const LATEST_BROWSER_TAB_ID_REPLAY_TOKEN = "{{latestBrowserTabId}}";
  29. const LATEST_BROWSER_TAB_A_ID_REPLAY_TOKEN = "{{latestBrowserTabAId}}";
  30. const LATEST_BROWSER_TAB_B_ID_REPLAY_TOKEN = "{{latestBrowserTabBId}}";
  31. export interface UpstreamReplayServer {
  32. artifactPath: string;
  33. baseUrl: string;
  34. host: string;
  35. port: number;
  36. stop(): Promise<void>;
  37. }
  38. interface StartUpstreamReplayServerOptions {
  39. artifactPath: string;
  40. artifactWriter?: typeof writeE2EJsonFileAtomically;
  41. fixtureVariables?: Readonly<Record<string, string>>;
  42. fixturePaths: string[];
  43. host?: string;
  44. port?: number;
  45. }
  46. interface UpstreamReplayFixtureFile {
  47. fixtures: UpstreamReplayFixture[];
  48. version: 1;
  49. }
  50. type UpstreamReplayCloseMode = "end" | "destroy";
  51. interface UpstreamReplayFixture {
  52. metadata?: { timingPolicy?: string };
  53. captured?: {
  54. capturedAt?: string;
  55. model?: string;
  56. requestBodyBytes?: number;
  57. responseBodyBytes?: number;
  58. statusCode?: number;
  59. url?: string;
  60. };
  61. description?: string;
  62. id: string;
  63. maxMatches?: number;
  64. match: {
  65. bodyExcludes?: string[];
  66. bodyIncludes?: string[];
  67. lastUserMessageExcludes?: string[];
  68. lastUserMessageIncludes?: string[];
  69. method?: string;
  70. pathIncludes?: string;
  71. };
  72. replay?: {
  73. consumeOnce?: boolean;
  74. };
  75. response: {
  76. body?: string;
  77. chunks?: UpstreamReplayResponseChunk[];
  78. closeMode?: UpstreamReplayCloseMode;
  79. delayMs?: number;
  80. /** 仅 controlled-stream:每个边界均等待测试完成对应操作再释放。 */
  81. releaseAfterChunks?: number | number[];
  82. events?: E2ENetworkCaptureResponseEvent[];
  83. headers?: Record<string, string>;
  84. statusCode: number;
  85. statusMessage?: string;
  86. text?: UpstreamReplayTextResponse | string;
  87. toolUse?: UpstreamReplayToolUseResponse;
  88. toolUses?: UpstreamReplayToolUseResponse[];
  89. };
  90. }
  91. interface ReplayVariables {
  92. browserFixtureUrl?: string;
  93. latestBrowserTabAId?: string;
  94. latestBrowserTabBId?: string;
  95. latestBrowserTabId?: string;
  96. latestAgentId?: string;
  97. latestBashTaskId?: string;
  98. memoryRoot?: string;
  99. latestAutomationId?: string;
  100. latestWorkflowRunId?: string;
  101. }
  102. interface UpstreamReplayResponseChunk {
  103. base64?: string;
  104. byteLength?: number;
  105. offsetMs: number;
  106. text?: string;
  107. }
  108. interface UpstreamReplayTextResponse {
  109. id?: string;
  110. inputTokens?: number;
  111. model?: string;
  112. outputTokens?: number;
  113. text: string;
  114. }
  115. interface UpstreamReplayToolUseResponse {
  116. id?: string;
  117. input: Record<string, unknown>;
  118. inputTokens?: number;
  119. messageId?: string;
  120. model?: string;
  121. name: string;
  122. outputTokens?: number;
  123. }
  124. type MutableCaptureRecord = E2ENetworkCaptureRecord;
  125. export async function startUpstreamReplayServer(
  126. options: StartUpstreamReplayServerOptions,
  127. ): Promise<UpstreamReplayServer> {
  128. const host = options.host ?? "127.0.0.1";
  129. const requestedPort = options.port ?? 0;
  130. const artifactPath = resolve(options.artifactPath);
  131. const artifactWriter = options.artifactWriter ?? writeE2EJsonFileAtomically;
  132. // Bug 根因:provider fixture 里的绝对路径过去只能写死为 POSIX 临时目录,
  133. // Windows Node 与 Git Bash 因而会访问不同文件。静态变量必须在 matcher 之前展开,
  134. // 否则 response 虽能拿到正确路径,请求仍会先因 matcher 含 token 而 miss。
  135. const fixtures = options.fixturePaths.flatMap((path) =>
  136. loadFixtureFile(path, options.fixtureVariables),
  137. );
  138. for (const fixture of fixtures) {
  139. const boundary = fixture.response.releaseAfterChunks;
  140. if (boundary === undefined) continue;
  141. const counts = Array.isArray(boundary) ? boundary : [boundary];
  142. if (
  143. fixture.metadata?.timingPolicy !== "controlled-stream" ||
  144. counts.length === 0 ||
  145. counts.some(
  146. (count, index) =>
  147. !Number.isInteger(count) ||
  148. count < 1 ||
  149. count >= (fixture.response.chunks?.length ?? 0) ||
  150. (index > 0 && count <= counts[index - 1]!),
  151. ) ||
  152. fixture.response.events?.length
  153. ) {
  154. throw new Error(`无效受控流 fixture: ${fixture.id};不得改变 recorded/fault stream 的时间轴`);
  155. }
  156. }
  157. const fixtureMatchCounts = new Map<string, number>();
  158. const records: MutableCaptureRecord[] = [];
  159. const gates = new Map<string, { release(): void; cancel(): void }>();
  160. const holdStream = (id: string, response: ServerResponse) =>
  161. new Promise<void>((resolveGate, rejectGate) => {
  162. if (gates.has(id)) {
  163. rejectGate(new Error(`重复的受控请求: ${id}`));
  164. return;
  165. }
  166. const finish = (error?: Error) => {
  167. clearTimeout(timer);
  168. response.off("close", closed);
  169. gates.delete(id);
  170. if (error) rejectGate(error);
  171. else resolveGate();
  172. };
  173. const closed = () => finish(new Error(`受控流已断开: ${id}`));
  174. const timer = setTimeout(() => finish(new Error(`受控流未被测试释放: ${id}`)), 120_000);
  175. gates.set(id, { release: () => finish(), cancel: closed });
  176. response.once("close", closed);
  177. });
  178. let serverPort = requestedPort;
  179. let baseUrl = `http://${host}:${serverPort}`;
  180. let artifactWriteQueue = Promise.resolve();
  181. const writeArtifact = () => {
  182. const artifact = {
  183. generatedAt: new Date().toISOString(),
  184. proxy: {
  185. caCertPath: "",
  186. host,
  187. port: serverPort,
  188. proxyUrl: baseUrl,
  189. },
  190. records: records.map(serializeRecord),
  191. version: 1,
  192. } satisfies E2ENetworkCaptureArtifact;
  193. // 同一 replay server 内也必须串行替换 artifact;否则多个并发 child request
  194. // 会让各自的临时文件竞争目标路径,并可能把较旧快照写到较新快照之后。
  195. const nextWrite = artifactWriteQueue
  196. .catch(() => undefined)
  197. .then(() => artifactWriter(artifactPath, artifact));
  198. artifactWriteQueue = nextWrite;
  199. return nextWrite;
  200. };
  201. const server = createServer((request, response) => {
  202. // 控制端不进入模型请求台账;每个独立 replay server 只释放自己的正在等待的 fixture。
  203. if (request.method === "GET" && request.url === "/__e2e__/gates") {
  204. response.setHeader("content-type", "application/json");
  205. response.end(JSON.stringify([...gates.keys()]));
  206. return;
  207. }
  208. if (request.method === "POST" && request.url?.startsWith("/__e2e__/release/")) {
  209. const gate = gates.get(request.url.slice("/__e2e__/release/".length));
  210. response.statusCode = gate ? 204 : 409;
  211. gate?.release();
  212. response.end();
  213. return;
  214. }
  215. void handleReplayRequest(request, response, {
  216. baseUrl,
  217. fixtureMatchCounts,
  218. fixtures,
  219. records,
  220. writeArtifact,
  221. holdStream,
  222. }).catch((error: unknown) => {
  223. // Bug 根因:旧 handler 是裸 `void Promise`,capture 写入抛错后没有任何人
  224. // 收口 response,provider 只能一直等 socket。证据通道失败必须显式结束请求。
  225. closeReplayResponseAfterHandlerError(response, error);
  226. });
  227. });
  228. await new Promise<void>((resolveStart, rejectStart) => {
  229. server.listen(requestedPort, host, () => {
  230. const address = server.address() as AddressInfo | null;
  231. if (!address) {
  232. rejectStart(new Error("Upstream replay server did not expose an address"));
  233. return;
  234. }
  235. serverPort = address.port;
  236. baseUrl = `http://${host}:${serverPort}`;
  237. resolveStart();
  238. });
  239. server.once("error", rejectStart);
  240. });
  241. try {
  242. await writeArtifact();
  243. } catch (error) {
  244. // Bug 根因:listen 成功后首次 artifact 写入失败会直接退出启动流程,
  245. // 但旧实现没有关闭 HTTP server,导致端口和进程句柄跨测试泄漏。
  246. // 清理错误不能覆盖原始写入错误;同时显式等待队列收口再向调用方失败。
  247. await closeServerListener(server).catch(() => undefined);
  248. await artifactWriteQueue.catch(() => undefined);
  249. throw error;
  250. }
  251. return {
  252. artifactPath,
  253. baseUrl,
  254. host,
  255. port: serverPort,
  256. stop: () => {
  257. for (const gate of gates.values()) gate.cancel();
  258. return stopServer(server, writeArtifact);
  259. },
  260. };
  261. }
  262. async function handleReplayRequest(
  263. request: IncomingMessage,
  264. response: ServerResponse,
  265. context: {
  266. baseUrl: string;
  267. fixtureMatchCounts: Map<string, number>;
  268. fixtures: UpstreamReplayFixture[];
  269. records: MutableCaptureRecord[];
  270. writeArtifact(): Promise<void>;
  271. holdStream(id: string, response: ServerResponse): Promise<void>;
  272. },
  273. ) {
  274. const startedAt = new Date().toISOString();
  275. const requestBody = await readRequestBody(request);
  276. const requestText = requestBody.toString("utf-8");
  277. const requestJson = parseJson(requestText);
  278. const requestUrl = buildRequestUrl(request, context.baseUrl);
  279. const record: MutableCaptureRecord = {
  280. host: requestUrl.host,
  281. id: randomUUID(),
  282. method: request.method ?? "GET",
  283. path: requestUrl.pathname + requestUrl.search,
  284. protocol: requestUrl.protocol === "https:" ? "https" : "http",
  285. requestBodyBytes: requestBody.length,
  286. requestHeaders: sanitizeE2ENetworkCaptureHeaders(request.headers),
  287. requestJson: requestJson ? redactE2ENetworkCaptureJson(requestJson) : undefined,
  288. requestTextPreview: requestJson ? undefined : requestText,
  289. responseBodyBytes: 0,
  290. responseHeaders: {},
  291. startedAt,
  292. status: "pending",
  293. url: requestUrl.toString(),
  294. };
  295. context.records.push(record);
  296. await context.writeArtifact();
  297. const fixtureIndex = findFixtureIndex(
  298. context.fixtures,
  299. record,
  300. requestText,
  301. requestJson,
  302. context.fixtureMatchCounts,
  303. );
  304. const fixture = fixtureIndex >= 0 ? context.fixtures[fixtureIndex] : undefined;
  305. if (!fixture) {
  306. const body = JSON.stringify(
  307. {
  308. error: {
  309. message: `Missing Upstream e2e fixture for ${record.method} ${record.path}`,
  310. },
  311. },
  312. null,
  313. 2,
  314. );
  315. await writeResponse(response, record, {
  316. body,
  317. headers: { "content-type": "application/json; charset=utf-8" },
  318. statusCode: 500,
  319. statusMessage: "Missing Fixture",
  320. });
  321. await context.writeArtifact();
  322. return;
  323. }
  324. context.fixtureMatchCounts.set(fixture.id, (context.fixtureMatchCounts.get(fixture.id) ?? 0) + 1);
  325. record.replay = {
  326. closeMode: fixture.response.closeMode ?? "end",
  327. fixtureId: fixture.id,
  328. };
  329. await context.writeArtifact();
  330. if (fixture.response.delayMs && fixture.response.delayMs > 0) {
  331. await new Promise((resolveDelay) => setTimeout(resolveDelay, fixture.response.delayMs));
  332. }
  333. if (fixture.response.events?.length) {
  334. await writeEventStreamResponse(response, record, {
  335. events: fixture.response.events,
  336. closeMode: fixture.response.closeMode ?? "end",
  337. headers: fixture.response.headers ?? {},
  338. statusCode: fixture.response.statusCode,
  339. statusMessage: fixture.response.statusMessage ?? "OK",
  340. });
  341. } else {
  342. const resolvedBody = resolveFixtureResponseBody(
  343. fixture.response,
  344. extractReplayVariables(requestText, requestJson),
  345. isStreamingRequest(requestJson),
  346. );
  347. if (
  348. resolvedBody.body.includes(BROWSER_FIXTURE_URL_REPLAY_TOKEN) ||
  349. resolvedBody.body.includes(LATEST_WORKFLOW_RUN_ID_REPLAY_TOKEN)
  350. ) {
  351. // 修复原因:动态 URL marker 缺失或格式错误时保留模板会让 Browser tool
  352. // 导航到字面量 `{{browserFixtureUrl}}`,随后可能被 compact 摘要掩盖成成功。
  353. // replay 必须 fail closed,让 fixture/request 契约错误直接可见。
  354. await writeResponse(response, record, {
  355. body: JSON.stringify({
  356. error: {
  357. message: resolvedBody.body.includes(BROWSER_FIXTURE_URL_REPLAY_TOKEN)
  358. ? "Missing E2E_BROWSER_FIXTURE_URL replay variable"
  359. : "Missing workflow-hole run ID replay variable",
  360. },
  361. }),
  362. headers: { "content-type": "application/json; charset=utf-8" },
  363. statusCode: 500,
  364. statusMessage: "Missing Replay Variable",
  365. });
  366. // Bug 根因:artifact 写入改为异步后,这个 fail-closed 分支仍然 fire-and-forget;
  367. // Windows 原子替换最终失败时 rejection 会逃出统一 handler catch。返回前等待,
  368. // 让诊断落盘失败按请求生命周期收口,且不覆盖已经返回的 500 业务证据。
  369. await context.writeArtifact();
  370. return;
  371. }
  372. await writeResponse(response, record, {
  373. body: resolvedBody.body,
  374. chunks: fixture.response.chunks,
  375. closeMode: fixture.response.closeMode,
  376. ...(fixture.response.releaseAfterChunks === undefined
  377. ? {}
  378. : {
  379. releaseAfterChunks: fixture.response.releaseAfterChunks,
  380. release: () => {
  381. if (fixture.metadata?.timingPolicy !== "controlled-stream")
  382. throw new Error("仅 controlled-stream 允许显式释放");
  383. return context.holdStream(fixture.id, response);
  384. },
  385. }),
  386. headers: resolvedBody.headers,
  387. statusCode: fixture.response.statusCode,
  388. statusMessage: fixture.response.statusMessage ?? "OK",
  389. });
  390. }
  391. if (fixture.replay?.consumeOnce) {
  392. context.fixtures.splice(fixtureIndex, 1);
  393. }
  394. await context.writeArtifact();
  395. }
  396. function closeReplayResponseAfterHandlerError(response: ServerResponse, error: unknown): void {
  397. const message = error instanceof Error ? error.message : String(error);
  398. console.warn(`[upstream-replay] request handler failed: ${message}`);
  399. if (response.writableEnded || response.destroyed) {
  400. return;
  401. }
  402. if (response.headersSent) {
  403. response.destroy(error instanceof Error ? error : undefined);
  404. return;
  405. }
  406. const body = JSON.stringify({
  407. error: { message: `Upstream E2E replay handler failed: ${message}` },
  408. });
  409. response.writeHead(500, "Replay Handler Failed", {
  410. "content-length": String(Buffer.byteLength(body, "utf-8")),
  411. "content-type": "application/json; charset=utf-8",
  412. });
  413. response.end(body);
  414. }
  415. function resolveFixtureResponseBody(
  416. response: UpstreamReplayFixture["response"],
  417. variables: ReplayVariables,
  418. streaming: boolean,
  419. ): { body: string; headers: Record<string, string> } {
  420. if (response.body !== undefined) {
  421. return {
  422. body: applyReplayVariablesToString(response.body, variables),
  423. headers: response.headers ?? {},
  424. };
  425. }
  426. // 修复原因:fixture 的 text/toolUse 简写过去一律渲染为 SSE。标题等 sidecar 请求
  427. // 不带 stream:true,真实协议返回 application/json;继续回 SSE 会被回放审计记为
  428. // titleResponseFormatErrors。按请求的 stream 属性决定响应格式。
  429. // chunks 是录制/受控流的原始字节,存在时必须保持流式,不能被请求属性改写。
  430. const streamBody = streaming || (response.chunks?.length ?? 0) > 0;
  431. const responseHeaders = streamBody
  432. ? withEventStreamHeaders(response.headers)
  433. : withJsonHeaders(response.headers);
  434. if (response.toolUses?.length) {
  435. const toolUses = response.toolUses.map((toolUse) => resolveReplayToolUse(toolUse, variables));
  436. return {
  437. body: streamBody ? buildToolUsesSseBody(toolUses) : buildToolUsesMessageBody(toolUses),
  438. headers: responseHeaders,
  439. };
  440. }
  441. if (response.toolUse) {
  442. const toolUse = resolveReplayToolUse(response.toolUse, variables);
  443. return {
  444. body: streamBody ? buildToolUseSseBody(toolUse) : buildToolUsesMessageBody([toolUse]),
  445. headers: responseHeaders,
  446. };
  447. }
  448. if (response.text !== undefined) {
  449. const text = resolveReplayText(response.text, variables);
  450. return {
  451. body: streamBody ? buildTextSseBody(text) : buildTextMessageBody(text),
  452. headers: responseHeaders,
  453. };
  454. }
  455. return {
  456. body: "",
  457. headers: response.headers ?? {},
  458. };
  459. }
  460. function isStreamingRequest(requestJson: unknown): boolean {
  461. return (
  462. typeof requestJson === "object" &&
  463. requestJson !== null &&
  464. (requestJson as { stream?: unknown }).stream === true
  465. );
  466. }
  467. function extractReplayVariables(requestText: string, requestJson: unknown): ReplayVariables {
  468. const requestContent = `${requestText}\n${JSON.stringify(requestJson ?? {})}`;
  469. const browserTabIds = readLatestBrowserTabIds(requestJson);
  470. return {
  471. browserFixtureUrl: readBrowserFixtureUrl(requestContent),
  472. ...browserTabIds,
  473. latestAgentId: readLatestAgentId(requestContent),
  474. latestBashTaskId: readLatestBashTaskId(requestContent),
  475. memoryRoot: readMemoryRoot(requestContent),
  476. latestAutomationId: readLatestAutomationId(requestJson),
  477. // Workflow run ID 由真实工具生成;只取最新留白通知,不能把随机 ID 写死在夹具中。
  478. latestWorkflowRunId: [
  479. ...requestContent.matchAll(/<workflow-hole>[\s\S]*?<run-id>([^<]+)<\/run-id>/gu),
  480. ].at(-1)?.[1],
  481. };
  482. }
  483. function readLatestBrowserTabIds(
  484. value: unknown,
  485. ): Pick<ReplayVariables, "latestBrowserTabAId" | "latestBrowserTabBId" | "latestBrowserTabId"> {
  486. const ids = {
  487. e2eBrowserTabAId: [] as string[],
  488. e2eBrowserTabBId: [] as string[],
  489. e2eBrowserTabId: [] as string[],
  490. };
  491. const names = Object.keys(ids) as Array<keyof typeof ids>;
  492. const visit = (candidate: unknown): void => {
  493. if (typeof candidate === "string") {
  494. // Bug 根因:真实 Node REPL tool_result 是 `=> { ... }\nStructured content:`,
  495. // 不是可直接 JSON.parse 的纯 JSON;只解析带 E2E 命名空间的显式字段,避免
  496. // 从任意 tab 文本猜 id,让 replay 真正模拟模型读取上一条工具结果。
  497. for (const name of names) {
  498. const pattern = new RegExp(`["']${name}["']\\s*:\\s*["']([^"']+)["']`, "gu");
  499. for (const match of candidate.matchAll(pattern)) {
  500. if (match[1]?.trim()) ids[name].push(match[1].trim());
  501. }
  502. }
  503. return;
  504. }
  505. if (Array.isArray(candidate)) {
  506. for (const item of candidate) visit(item);
  507. return;
  508. }
  509. if (!candidate || typeof candidate !== "object") return;
  510. for (const [key, child] of Object.entries(candidate)) {
  511. if (names.includes(key as keyof typeof ids) && typeof child === "string" && child.trim()) {
  512. ids[key as keyof typeof ids].push(child.trim());
  513. }
  514. visit(child);
  515. }
  516. };
  517. visit(value);
  518. return {
  519. latestBrowserTabAId: ids.e2eBrowserTabAId.at(-1),
  520. latestBrowserTabBId: ids.e2eBrowserTabBId.at(-1),
  521. latestBrowserTabId: ids.e2eBrowserTabId.at(-1),
  522. };
  523. }
  524. function readBrowserFixtureUrl(value: string): string | undefined {
  525. // 修复原因:Browser Use E2E 的本地 HTTP server 使用随机端口,provider replay
  526. // 必须从用户 marker 回填真实 URL,不能依赖固定端口或公网页面制造并发/网络抖动。
  527. const match = value.match(
  528. /E2E_BROWSER_FIXTURE_URL:(https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?\/[^\s"'<>),]*)/u,
  529. );
  530. return match?.[1];
  531. }
  532. function readLatestAgentId(value: string): string | undefined {
  533. const matches = [...value.matchAll(/agentId:\s*(agent_[A-Za-z0-9_-]+)/gu)];
  534. return matches.at(-1)?.[1];
  535. }
  536. function readLatestBashTaskId(value: string): string | undefined {
  537. // Bash task ID 每次运行都不同;只从真实 launch result 回填,不能把 Agent ID 当作 Bash ID。
  538. const matches = [
  539. ...value.matchAll(/Command running in background with ID:\s*([A-Za-z0-9_-]+)\./gu),
  540. ];
  541. return matches.at(-1)?.[1];
  542. }
  543. function readMemoryRoot(value: string): string | undefined {
  544. // Memory root 由 Runtime 按 workspace 计算,fixture 不能硬编码本机绝对路径。
  545. // 只从已经进入 provider request 的既有 Memory prompt 提取路径并回填 tool input。
  546. const matches = [
  547. ...value.matchAll(/persistent(?:,\s*)? file-based memory(?: system)? at `([^`]+?)[/\\]`/giu),
  548. ];
  549. return matches.at(-1)?.[1];
  550. }
  551. function readLatestAutomationId(value: unknown): string | undefined {
  552. const ids: string[] = [];
  553. const visit = (candidate: unknown): void => {
  554. if (typeof candidate === "string") {
  555. const trimmed = candidate.trim();
  556. if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
  557. try {
  558. visit(JSON.parse(trimmed) as unknown);
  559. return;
  560. } catch {
  561. // tool_result 可能是带前后说明的文本,继续用正则提取其中的 JSON 字段。
  562. }
  563. }
  564. for (const match of candidate.matchAll(
  565. /["'](?:automationId|automation_id)["']\s*:\s*["']([^"']+)["']/gu,
  566. )) {
  567. if (match[1]?.trim()) ids.push(match[1].trim());
  568. }
  569. return;
  570. }
  571. if (Array.isArray(candidate)) {
  572. for (const item of candidate) visit(item);
  573. return;
  574. }
  575. if (!candidate || typeof candidate !== "object") return;
  576. for (const [key, child] of Object.entries(candidate)) {
  577. if (
  578. (key === "automationId" || key === "automation_id") &&
  579. typeof child === "string" &&
  580. child.trim()
  581. ) {
  582. ids.push(child.trim());
  583. }
  584. visit(child);
  585. }
  586. };
  587. visit(value);
  588. return ids.at(-1);
  589. }
  590. function resolveReplayToolUse(
  591. toolUse: UpstreamReplayToolUseResponse,
  592. variables: ReplayVariables,
  593. ): UpstreamReplayToolUseResponse {
  594. return {
  595. ...toolUse,
  596. id: toolUse.id === undefined ? undefined : applyReplayVariablesToString(toolUse.id, variables),
  597. input: applyReplayVariables(toolUse.input, variables) as Record<string, unknown>,
  598. messageId:
  599. toolUse.messageId === undefined
  600. ? undefined
  601. : applyReplayVariablesToString(toolUse.messageId, variables),
  602. };
  603. }
  604. function resolveReplayText(
  605. textResponse: UpstreamReplayTextResponse | string,
  606. variables: ReplayVariables,
  607. ): UpstreamReplayTextResponse | string {
  608. if (typeof textResponse === "string") {
  609. return applyReplayVariablesToString(textResponse, variables);
  610. }
  611. return {
  612. ...textResponse,
  613. id:
  614. textResponse.id === undefined
  615. ? undefined
  616. : applyReplayVariablesToString(textResponse.id, variables),
  617. text: applyReplayVariablesToString(textResponse.text, variables),
  618. };
  619. }
  620. function applyReplayVariables(value: unknown, variables: ReplayVariables): unknown {
  621. if (typeof value === "string") {
  622. return applyReplayVariablesToString(value, variables);
  623. }
  624. if (Array.isArray(value)) {
  625. return value.map((item) => applyReplayVariables(item, variables));
  626. }
  627. if (!value || typeof value !== "object") {
  628. return value;
  629. }
  630. return Object.fromEntries(
  631. Object.entries(value).map(([key, child]) => [key, applyReplayVariables(child, variables)]),
  632. );
  633. }
  634. function applyReplayVariablesToString(value: string, variables: ReplayVariables): string {
  635. let resolved = value;
  636. if (variables.latestBrowserTabId !== undefined) {
  637. resolved = resolved
  638. .split(LATEST_BROWSER_TAB_ID_REPLAY_TOKEN)
  639. .join(variables.latestBrowserTabId);
  640. }
  641. if (variables.latestBrowserTabAId !== undefined) {
  642. resolved = resolved
  643. .split(LATEST_BROWSER_TAB_A_ID_REPLAY_TOKEN)
  644. .join(variables.latestBrowserTabAId);
  645. }
  646. if (variables.latestBrowserTabBId !== undefined) {
  647. resolved = resolved
  648. .split(LATEST_BROWSER_TAB_B_ID_REPLAY_TOKEN)
  649. .join(variables.latestBrowserTabBId);
  650. }
  651. if (variables.latestAgentId !== undefined) {
  652. resolved = resolved.split(LATEST_AGENT_ID_REPLAY_TOKEN).join(variables.latestAgentId);
  653. }
  654. if (variables.latestBashTaskId !== undefined) {
  655. resolved = resolved.split(LATEST_BASH_TASK_ID_REPLAY_TOKEN).join(variables.latestBashTaskId);
  656. }
  657. if (variables.memoryRoot !== undefined) {
  658. resolved = resolved.split(MEMORY_ROOT_REPLAY_TOKEN).join(variables.memoryRoot);
  659. }
  660. if (variables.latestAutomationId !== undefined) {
  661. resolved = resolved.split(LATEST_AUTOMATION_ID_REPLAY_TOKEN).join(variables.latestAutomationId);
  662. }
  663. if (variables.latestWorkflowRunId !== undefined) {
  664. resolved = resolved
  665. .split(LATEST_WORKFLOW_RUN_ID_REPLAY_TOKEN)
  666. .join(variables.latestWorkflowRunId);
  667. }
  668. if (variables.browserFixtureUrl !== undefined) {
  669. resolved = resolved.split(BROWSER_FIXTURE_URL_REPLAY_TOKEN).join(variables.browserFixtureUrl);
  670. }
  671. return resolved;
  672. }
  673. function withEventStreamHeaders(
  674. headers: Record<string, string> | undefined,
  675. ): Record<string, string> {
  676. return {
  677. "cache-control": "no-cache",
  678. "content-type": "text/event-stream; charset=utf-8",
  679. ...headers,
  680. };
  681. }
  682. function withJsonHeaders(headers: Record<string, string> | undefined): Record<string, string> {
  683. // 非流式响应的 content-type 必须是权威值;fixture 的 SSE headers 不能带进 JSON 响应。
  684. return {
  685. ...headers,
  686. "content-type": "application/json; charset=utf-8",
  687. };
  688. }
  689. function buildToolUseSseBody(toolUse: UpstreamReplayToolUseResponse): string {
  690. return buildToolUsesSseBody([toolUse]);
  691. }
  692. function buildToolUsesSseBody(toolUses: UpstreamReplayToolUseResponse[]): string {
  693. const firstToolUse = toolUses[0];
  694. const messageId = firstToolUse?.messageId ?? `msg_${sanitizeSseId(firstToolUse?.name ?? "tool")}`;
  695. const inputTokens = firstToolUse?.inputTokens;
  696. const outputTokens = toolUses.reduce((sum, toolUse) => sum + (toolUse.outputTokens ?? 16), 0);
  697. return [
  698. sseEvent("message_start", {
  699. type: "message_start",
  700. message: {
  701. id: messageId,
  702. type: "message",
  703. role: "assistant",
  704. model: firstToolUse?.model ?? DEFAULT_REPLAY_MODEL,
  705. content: [],
  706. stop_reason: null,
  707. stop_sequence: null,
  708. usage: replayUsage(inputTokens, 0),
  709. },
  710. }),
  711. ...toolUses.flatMap((toolUse, index) => buildToolUseContentBlockEvents(toolUse, index)),
  712. sseEvent("message_delta", {
  713. type: "message_delta",
  714. delta: {
  715. stop_reason: "tool_use",
  716. stop_sequence: null,
  717. },
  718. usage: replayUsage(inputTokens, outputTokens),
  719. }),
  720. sseEvent("message_stop", { type: "message_stop" }),
  721. ].join("");
  722. }
  723. function buildToolUseContentBlockEvents(
  724. toolUse: UpstreamReplayToolUseResponse,
  725. index: number,
  726. ): string[] {
  727. const toolCallId = toolUse.id ?? `toolu_${sanitizeSseId(toolUse.name)}`;
  728. const inputJson = JSON.stringify(toolUse.input);
  729. return [
  730. sseEvent("content_block_start", {
  731. type: "content_block_start",
  732. index,
  733. content_block: {
  734. type: "tool_use",
  735. id: toolCallId,
  736. name: toolUse.name,
  737. input: {},
  738. },
  739. }),
  740. sseEvent("content_block_delta", {
  741. type: "content_block_delta",
  742. index,
  743. delta: {
  744. type: "input_json_delta",
  745. partial_json: inputJson,
  746. },
  747. }),
  748. sseEvent("content_block_stop", {
  749. type: "content_block_stop",
  750. index,
  751. }),
  752. ];
  753. }
  754. function buildTextSseBody(textResponse: UpstreamReplayTextResponse | string): string {
  755. const text = typeof textResponse === "string" ? textResponse : textResponse.text;
  756. const id =
  757. typeof textResponse === "string"
  758. ? "msg_upstream_e2e_text"
  759. : (textResponse.id ?? "msg_upstream_e2e_text");
  760. const model =
  761. typeof textResponse === "string"
  762. ? DEFAULT_REPLAY_MODEL
  763. : (textResponse.model ?? DEFAULT_REPLAY_MODEL);
  764. const inputTokens = typeof textResponse === "string" ? undefined : textResponse.inputTokens;
  765. const outputTokens = typeof textResponse === "string" ? undefined : textResponse.outputTokens;
  766. return [
  767. sseEvent("message_start", {
  768. type: "message_start",
  769. message: {
  770. id,
  771. type: "message",
  772. role: "assistant",
  773. model,
  774. content: [],
  775. stop_reason: null,
  776. stop_sequence: null,
  777. usage: replayUsage(inputTokens, 0),
  778. },
  779. }),
  780. sseEvent("content_block_start", {
  781. type: "content_block_start",
  782. index: 0,
  783. content_block: {
  784. type: "text",
  785. text: "",
  786. },
  787. }),
  788. sseEvent("content_block_delta", {
  789. type: "content_block_delta",
  790. index: 0,
  791. delta: {
  792. type: "text_delta",
  793. text,
  794. },
  795. }),
  796. sseEvent("content_block_stop", {
  797. type: "content_block_stop",
  798. index: 0,
  799. }),
  800. sseEvent("message_delta", {
  801. type: "message_delta",
  802. delta: {
  803. stop_reason: "end_turn",
  804. stop_sequence: null,
  805. },
  806. usage: replayUsage(inputTokens, outputTokens ?? 12),
  807. }),
  808. sseEvent("message_stop", { type: "message_stop" }),
  809. ].join("");
  810. }
  811. function buildToolUsesMessageBody(toolUses: UpstreamReplayToolUseResponse[]): string {
  812. const firstToolUse = toolUses[0];
  813. const messageId = firstToolUse?.messageId ?? `msg_${sanitizeSseId(firstToolUse?.name ?? "tool")}`;
  814. const inputTokens = firstToolUse?.inputTokens;
  815. const outputTokens = toolUses.reduce((sum, toolUse) => sum + (toolUse.outputTokens ?? 16), 0);
  816. return JSON.stringify({
  817. id: messageId,
  818. type: "message",
  819. role: "assistant",
  820. model: firstToolUse?.model ?? DEFAULT_REPLAY_MODEL,
  821. content: toolUses.map((toolUse) => ({
  822. type: "tool_use",
  823. id: toolUse.id ?? `toolu_${sanitizeSseId(toolUse.name)}`,
  824. name: toolUse.name,
  825. input: toolUse.input,
  826. })),
  827. stop_reason: "tool_use",
  828. stop_sequence: null,
  829. usage: replayUsage(inputTokens, outputTokens),
  830. });
  831. }
  832. function buildTextMessageBody(textResponse: UpstreamReplayTextResponse | string): string {
  833. const text = typeof textResponse === "string" ? textResponse : textResponse.text;
  834. const id =
  835. typeof textResponse === "string"
  836. ? "msg_upstream_e2e_text"
  837. : (textResponse.id ?? "msg_upstream_e2e_text");
  838. const model =
  839. typeof textResponse === "string"
  840. ? DEFAULT_REPLAY_MODEL
  841. : (textResponse.model ?? DEFAULT_REPLAY_MODEL);
  842. const inputTokens = typeof textResponse === "string" ? undefined : textResponse.inputTokens;
  843. const outputTokens = typeof textResponse === "string" ? undefined : textResponse.outputTokens;
  844. return JSON.stringify({
  845. id,
  846. type: "message",
  847. role: "assistant",
  848. model,
  849. content: [{ type: "text", text }],
  850. stop_reason: "end_turn",
  851. stop_sequence: null,
  852. usage: replayUsage(inputTokens, outputTokens ?? 12),
  853. });
  854. }
  855. function replayUsage(inputTokens = 128, outputTokens = 0) {
  856. return {
  857. input_tokens: inputTokens,
  858. cache_creation_input_tokens: 0,
  859. cache_read_input_tokens: 0,
  860. output_tokens: outputTokens,
  861. service_tier: "standard",
  862. };
  863. }
  864. function sseEvent(event: string, data: unknown): string {
  865. return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
  866. }
  867. function sanitizeSseId(value: string): string {
  868. return value
  869. .replace(/[^a-zA-Z0-9]+/g, "_")
  870. .replace(/^_+|_+$/g, "")
  871. .toLowerCase();
  872. }
  873. async function writeResponse(
  874. response: ServerResponse,
  875. record: MutableCaptureRecord,
  876. fixtureResponse: {
  877. body: string;
  878. chunks?: UpstreamReplayResponseChunk[];
  879. closeMode?: UpstreamReplayCloseMode;
  880. releaseAfterChunks?: number | number[];
  881. release?: () => Promise<void>;
  882. headers: Record<string, string>;
  883. statusCode: number;
  884. statusMessage: string;
  885. },
  886. ) {
  887. const responseChunks = normalizeReplayChunks(fixtureResponse.chunks);
  888. const destroyStream = fixtureResponse.closeMode === "destroy";
  889. // 同时带 text/chunks 的 fixture 实际发送 chunks,证据也必须记录真正发出的字节。
  890. const responseBody =
  891. responseChunks.length > 0
  892. ? Buffer.concat(responseChunks.map((chunk) => chunk.body))
  893. : Buffer.from(fixtureResponse.body, "utf-8");
  894. const responseHeaders = sanitizeResponseHeaders(fixtureResponse.headers);
  895. if (responseChunks.length === 0 && !destroyStream) {
  896. responseHeaders["content-length"] = String(responseBody.length);
  897. } else {
  898. delete responseHeaders["content-length"];
  899. }
  900. response.writeHead(fixtureResponse.statusCode, fixtureResponse.statusMessage, responseHeaders);
  901. let actualOffsets: number[] | undefined;
  902. if (responseChunks.length > 0) {
  903. // 边界已在加载时统一校验;同一响应逐段创建 gate,释放前一段不预放行后一段。
  904. actualOffsets = await writeReplayChunks(response, responseChunks, fixtureResponse);
  905. if (!destroyStream) response.end();
  906. } else if (destroyStream) {
  907. await writeResponseChunk(response, responseBody);
  908. } else {
  909. response.end(responseBody);
  910. }
  911. record.status = destroyStream ? "error" : "complete";
  912. record.completedAt = new Date().toISOString();
  913. record.durationMs = durationMs(record.startedAt, record.completedAt);
  914. record.statusCode = fixtureResponse.statusCode;
  915. record.statusMessage = fixtureResponse.statusMessage;
  916. record.responseBodyBytes = responseBody.length;
  917. record.responseHeaders = sanitizeE2ENetworkCaptureHeaders(responseHeaders);
  918. record.responseTextPreview = redactE2ENetworkCaptureJsonText(responseBody.toString("utf-8"));
  919. if (responseChunks.length > 0) {
  920. record.responseChunkTimeline = responseChunks.map((chunk, index) => ({
  921. base64: chunk.body.toString("base64"),
  922. byteLength: chunk.byteLength,
  923. offsetMs: fixtureResponse.release ? actualOffsets![index]! : chunk.offsetMs,
  924. }));
  925. }
  926. if (destroyStream) {
  927. // chunks/body 与 events 必须执行相同的故障合同;只在 artifact 标 destroy
  928. // 却正常 end 会把网络中断测试变成正常 EOF,并制造“产品假完成”的错误结论。
  929. record.error = "Replay fixture destroyed SSE response stream";
  930. response.destroy();
  931. }
  932. }
  933. async function writeReplayChunks(
  934. response: ServerResponse,
  935. chunks: NormalizedReplayChunk[],
  936. control?: { releaseAfterChunks?: number | number[]; release?: () => Promise<void> },
  937. ) {
  938. let previousOffsetMs = 0;
  939. const startedAt = Date.now();
  940. const actualOffsets: number[] = [];
  941. for (const [index, chunk] of chunks.entries()) {
  942. const boundary = control?.releaseAfterChunks;
  943. if (
  944. (Array.isArray(boundary) ? boundary.includes(index) : index === boundary) &&
  945. control?.release
  946. ) {
  947. await control.release();
  948. // 只移除被释放的那段人为慢窗口,后续 chunk 间距及内容原样保留。
  949. previousOffsetMs = chunk.offsetMs;
  950. }
  951. const delayMs = Math.max(0, chunk.offsetMs - previousOffsetMs);
  952. if (delayMs > 0) {
  953. await new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs));
  954. }
  955. previousOffsetMs = chunk.offsetMs;
  956. actualOffsets.push(Date.now() - startedAt);
  957. // 等待写入完成后再进入下一帧/销毁连接,避免最后一帧只进用户态队列就被丢弃。
  958. await writeResponseChunk(response, chunk.body);
  959. }
  960. return actualOffsets;
  961. }
  962. interface NormalizedReplayChunk {
  963. body: Buffer;
  964. byteLength: number;
  965. offsetMs: number;
  966. }
  967. function normalizeReplayChunks(
  968. chunks: UpstreamReplayResponseChunk[] | undefined,
  969. ): NormalizedReplayChunk[] {
  970. return (
  971. chunks
  972. ?.map((chunk) => {
  973. const body =
  974. chunk.base64 !== undefined
  975. ? Buffer.from(chunk.base64, "base64")
  976. : Buffer.from(chunk.text ?? "", "utf-8");
  977. return {
  978. body,
  979. byteLength: chunk.byteLength ?? body.length,
  980. offsetMs: Math.max(0, Math.round(chunk.offsetMs)),
  981. };
  982. })
  983. .filter((chunk) => chunk.body.length > 0) ?? []
  984. );
  985. }
  986. async function writeEventStreamResponse(
  987. response: ServerResponse,
  988. record: MutableCaptureRecord,
  989. fixtureResponse: {
  990. closeMode: UpstreamReplayCloseMode;
  991. events: E2ENetworkCaptureResponseEvent[];
  992. headers: Record<string, string>;
  993. statusCode: number;
  994. statusMessage: string;
  995. },
  996. ) {
  997. const responseHeaders = sanitizeResponseHeaders(fixtureResponse.headers);
  998. delete responseHeaders["content-length"];
  999. response.writeHead(fixtureResponse.statusCode, fixtureResponse.statusMessage, responseHeaders);
  1000. const startedAtMs = Date.now();
  1001. const sortedEvents = [...fixtureResponse.events].sort(
  1002. (left, right) => left.offsetMs - right.offsetMs || left.sequence - right.sequence,
  1003. );
  1004. const chunks: string[] = [];
  1005. const replayedEvents: E2ENetworkCaptureResponseEvent[] = [];
  1006. for (const event of sortedEvents) {
  1007. const elapsedMs = Date.now() - startedAtMs;
  1008. const waitMs = Math.max(0, event.offsetMs - elapsedMs);
  1009. if (waitMs > 0) {
  1010. await new Promise((resolveDelay) => setTimeout(resolveDelay, waitMs));
  1011. }
  1012. const text = event.text;
  1013. await writeResponseChunk(response, text);
  1014. chunks.push(text);
  1015. replayedEvents.push({
  1016. byteLength: Buffer.byteLength(text, "utf-8"),
  1017. offsetMs: Math.max(0, Date.now() - startedAtMs),
  1018. ...(event.partial ? { partial: true } : {}),
  1019. sequence: replayedEvents.length,
  1020. text,
  1021. });
  1022. }
  1023. const body = chunks.join("");
  1024. record.status = fixtureResponse.closeMode === "destroy" ? "error" : "complete";
  1025. record.completedAt = new Date().toISOString();
  1026. record.durationMs = durationMs(record.startedAt, record.completedAt);
  1027. record.statusCode = fixtureResponse.statusCode;
  1028. record.statusMessage = fixtureResponse.statusMessage;
  1029. record.responseBodyBytes = Buffer.byteLength(body, "utf-8");
  1030. record.responseEvents = replayedEvents;
  1031. record.responseHeaders = sanitizeE2ENetworkCaptureHeaders(responseHeaders);
  1032. record.responseTextPreview = redactE2ENetworkCaptureJsonText(body);
  1033. record.replay = {
  1034. ...record.replay,
  1035. closeMode: fixtureResponse.closeMode,
  1036. };
  1037. if (fixtureResponse.closeMode === "destroy") {
  1038. // 修复原因:SSE fault case 需要区分“provider 正常 EOF 但内容不完整”和
  1039. // “连接在流式响应中异常断开”。这里按 fixture 显式销毁 socket,artifact 也标记为 error,
  1040. // 让后续 E2E 能稳定构造断流语义,而不是依赖真实网络抖动。
  1041. record.error = "Replay fixture destroyed SSE response stream";
  1042. response.destroy();
  1043. return;
  1044. }
  1045. response.end();
  1046. }
  1047. function writeResponseChunk(response: ServerResponse, text: string | Buffer): Promise<void> {
  1048. return new Promise((resolveWrite, rejectWrite) => {
  1049. response.write(text, (error) => {
  1050. if (error) {
  1051. rejectWrite(error);
  1052. return;
  1053. }
  1054. resolveWrite();
  1055. });
  1056. });
  1057. }
  1058. function findFixtureIndex(
  1059. fixtures: UpstreamReplayFixture[],
  1060. record: E2ENetworkCaptureRecord,
  1061. requestText: string,
  1062. requestJson: unknown,
  1063. fixtureMatchCounts: ReadonlyMap<string, number>,
  1064. ) {
  1065. return fixtures.findIndex((fixture) => {
  1066. // 回放需要表达“同一类请求前 N 次失败、之后成功”的时序。
  1067. // maxMatches 只影响测试 fixture 匹配,不进入产品协议。
  1068. if (
  1069. fixture.maxMatches !== undefined &&
  1070. (fixtureMatchCounts.get(fixture.id) ?? 0) >= fixture.maxMatches
  1071. ) {
  1072. return false;
  1073. }
  1074. const expectedMethod = fixture.match.method?.toUpperCase();
  1075. if (expectedMethod && expectedMethod !== record.method.toUpperCase()) {
  1076. return false;
  1077. }
  1078. if (fixture.match.pathIncludes && !record.path.includes(fixture.match.pathIncludes)) {
  1079. return false;
  1080. }
  1081. const latestUserMessageText =
  1082. fixture.match.lastUserMessageIncludes || fixture.match.lastUserMessageExcludes
  1083. ? readLatestUserMessageText(requestJson)
  1084. : "";
  1085. return (
  1086. (fixture.match.bodyIncludes?.every(
  1087. (text) => requestText.includes(text) || captureContainsText(requestJson, text),
  1088. ) ??
  1089. true) &&
  1090. (fixture.match.bodyExcludes?.every(
  1091. (text) => !requestText.includes(text) && !captureContainsText(requestJson, text),
  1092. ) ??
  1093. true) &&
  1094. (fixture.match.lastUserMessageIncludes?.every((text) =>
  1095. latestUserMessageText.includes(text),
  1096. ) ??
  1097. true) &&
  1098. (fixture.match.lastUserMessageExcludes?.every(
  1099. (text) => !latestUserMessageText.includes(text),
  1100. ) ??
  1101. true)
  1102. );
  1103. });
  1104. }
  1105. function readLatestUserMessageText(requestJson: unknown): string {
  1106. if (!requestJson || typeof requestJson !== "object") {
  1107. return "";
  1108. }
  1109. const messages = (requestJson as { messages?: unknown }).messages;
  1110. if (!Array.isArray(messages)) {
  1111. return "";
  1112. }
  1113. for (let index = messages.length - 1; index >= 0; index -= 1) {
  1114. const message = messages[index];
  1115. if (!message || typeof message !== "object") {
  1116. continue;
  1117. }
  1118. if ((message as { role?: unknown }).role !== "user") {
  1119. continue;
  1120. }
  1121. return readMessageContentText((message as { content?: unknown }).content);
  1122. }
  1123. return "";
  1124. }
  1125. function readMessageContentText(content: unknown): string {
  1126. if (typeof content === "string") {
  1127. return content;
  1128. }
  1129. if (!Array.isArray(content)) {
  1130. return "";
  1131. }
  1132. return content
  1133. .map((part) => {
  1134. if (!part || typeof part !== "object") {
  1135. return "";
  1136. }
  1137. const text = (part as { text?: unknown }).text;
  1138. if (typeof text === "string") {
  1139. return text;
  1140. }
  1141. // 修复原因:Anthropic Messages continuation 把工具结果放在 user/tool_result.content,
  1142. // 旧实现只读 text,导致 fixture 只能在整段 body 搜 marker;而 tool code 本身
  1143. // 也包含成功 marker,会把真实失败结果误匹配成成功 continuation。
  1144. if ((part as { type?: unknown }).type === "tool_result") {
  1145. return readMessageContentText((part as { content?: unknown }).content);
  1146. }
  1147. return "";
  1148. })
  1149. .filter(Boolean)
  1150. .join("\n");
  1151. }
  1152. function loadFixtureFile(
  1153. path: string,
  1154. fixtureVariables: Readonly<Record<string, string>> = {},
  1155. ): UpstreamReplayFixture[] {
  1156. const resolvedPath = resolve(path);
  1157. const parsed = JSON.parse(readFileSync(resolvedPath, "utf-8")) as
  1158. | UpstreamReplayFixtureFile
  1159. | E2ENetworkCaptureArtifact;
  1160. if (isUpstreamReplayFixtureFile(parsed)) {
  1161. return applyFixtureVariables(parsed.fixtures, fixtureVariables) as UpstreamReplayFixture[];
  1162. }
  1163. if (isNetworkCaptureArtifact(parsed)) {
  1164. return applyFixtureVariables(
  1165. convertCaptureArtifactToFixtures(parsed, resolvedPath),
  1166. fixtureVariables,
  1167. ) as UpstreamReplayFixture[];
  1168. }
  1169. throw new Error(`Invalid Upstream e2e replay fixture: ${path}`);
  1170. }
  1171. function applyFixtureVariables(
  1172. value: unknown,
  1173. variables: Readonly<Record<string, string>>,
  1174. ): unknown {
  1175. if (typeof value === "string") {
  1176. return Object.entries(variables).reduce(
  1177. (resolvedValue, [name, replacement]) => resolvedValue.split(`{{${name}}}`).join(replacement),
  1178. value,
  1179. );
  1180. }
  1181. if (Array.isArray(value)) {
  1182. return value.map((item) => applyFixtureVariables(item, variables));
  1183. }
  1184. if (!value || typeof value !== "object") {
  1185. return value;
  1186. }
  1187. return Object.fromEntries(
  1188. Object.entries(value).map(([key, child]) => [key, applyFixtureVariables(child, variables)]),
  1189. );
  1190. }
  1191. function isUpstreamReplayFixtureFile(
  1192. value: UpstreamReplayFixtureFile | E2ENetworkCaptureArtifact,
  1193. ): value is UpstreamReplayFixtureFile {
  1194. return value.version === 1 && Array.isArray((value as UpstreamReplayFixtureFile).fixtures);
  1195. }
  1196. function isNetworkCaptureArtifact(
  1197. value: UpstreamReplayFixtureFile | E2ENetworkCaptureArtifact,
  1198. ): value is E2ENetworkCaptureArtifact {
  1199. return value.version === 1 && Array.isArray((value as E2ENetworkCaptureArtifact).records);
  1200. }
  1201. function convertCaptureArtifactToFixtures(
  1202. artifact: E2ENetworkCaptureArtifact,
  1203. sourcePath: string,
  1204. ): UpstreamReplayFixture[] {
  1205. const fixtures = artifact.records
  1206. .filter((record) => record.status === "complete" && record.statusCode)
  1207. .filter(
  1208. (record) =>
  1209. record.responseTextPreview ||
  1210. record.responseChunkTimeline?.length ||
  1211. record.responseEvents?.length,
  1212. )
  1213. .map((record, index) => {
  1214. const responseBody = resolveCapturedResponseBody(record);
  1215. return {
  1216. id: `capture-${String(index + 1).padStart(3, "0")}-${record.id}`,
  1217. description: `Captured replay response from ${sourcePath}`,
  1218. match: {
  1219. method: record.method,
  1220. pathIncludes: capturePathname(record),
  1221. },
  1222. replay: {
  1223. consumeOnce: true,
  1224. },
  1225. captured: {
  1226. capturedAt: record.completedAt ?? record.startedAt,
  1227. requestBodyBytes: record.requestBodyBytes,
  1228. responseBodyBytes: record.responseBodyBytes,
  1229. statusCode: record.statusCode,
  1230. url: record.url,
  1231. },
  1232. response: {
  1233. body: responseBody,
  1234. chunks: record.responseChunkTimeline?.map(captureChunkToReplayChunk),
  1235. events: record.responseEvents,
  1236. headers: record.responseHeaders,
  1237. statusCode: record.statusCode ?? 200,
  1238. statusMessage: record.statusMessage,
  1239. },
  1240. } satisfies UpstreamReplayFixture;
  1241. });
  1242. if (fixtures.length === 0) {
  1243. throw new Error(`Upstream capture artifact has no replayable records: ${sourcePath}`);
  1244. }
  1245. return fixtures;
  1246. }
  1247. function resolveCapturedResponseBody(record: E2ENetworkCaptureRecord) {
  1248. if (record.responseTextPreview && !record.responseBodyTruncated) {
  1249. return record.responseTextPreview;
  1250. }
  1251. if (record.responseEvents?.length) {
  1252. return record.responseEvents.map((event) => event.text).join("");
  1253. }
  1254. if (record.responseChunkTimeline?.length && !record.responseChunkTimelineTruncated) {
  1255. return Buffer.concat(
  1256. record.responseChunkTimeline.map((chunk) => Buffer.from(chunk.base64, "base64")),
  1257. ).toString("utf-8");
  1258. }
  1259. return record.responseTextPreview ?? "";
  1260. }
  1261. function captureChunkToReplayChunk(chunk: E2ENetworkResponseChunk): UpstreamReplayResponseChunk {
  1262. return {
  1263. base64: chunk.base64,
  1264. byteLength: chunk.byteLength,
  1265. offsetMs: chunk.offsetMs,
  1266. };
  1267. }
  1268. function capturePathname(record: E2ENetworkCaptureRecord) {
  1269. try {
  1270. return new URL(record.url).pathname;
  1271. } catch {
  1272. return record.path.split("?")[0] || record.path;
  1273. }
  1274. }
  1275. async function readRequestBody(request: IncomingMessage): Promise<Buffer> {
  1276. const chunks: Buffer[] = [];
  1277. for await (const chunk of request) {
  1278. chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  1279. }
  1280. return Buffer.concat(chunks);
  1281. }
  1282. function buildRequestUrl(request: IncomingMessage, baseUrl: string): URL {
  1283. const rawUrl = request.url ?? "/";
  1284. if (/^https?:\/\//i.test(rawUrl)) {
  1285. return new URL(rawUrl);
  1286. }
  1287. const path = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
  1288. return new URL(path, baseUrl);
  1289. }
  1290. function sanitizeResponseHeaders(headers: Record<string, string>): Record<string, string> {
  1291. const sanitized: Record<string, string> = {};
  1292. for (const [name, value] of Object.entries(headers)) {
  1293. const normalizedName = name.toLowerCase();
  1294. if (normalizedName === "connection" || normalizedName === "transfer-encoding") {
  1295. continue;
  1296. }
  1297. sanitized[normalizedName] = value;
  1298. }
  1299. return sanitized;
  1300. }
  1301. function parseJson(text: string): unknown {
  1302. if (!text.trim()) {
  1303. return undefined;
  1304. }
  1305. try {
  1306. return JSON.parse(text) as unknown;
  1307. } catch {
  1308. return undefined;
  1309. }
  1310. }
  1311. function captureContainsText(value: unknown, expected: string): boolean {
  1312. if (typeof value === "string") {
  1313. return value.includes(expected);
  1314. }
  1315. if (Array.isArray(value)) {
  1316. return value.some((item) => captureContainsText(item, expected));
  1317. }
  1318. if (!value || typeof value !== "object") {
  1319. return false;
  1320. }
  1321. return Object.values(value).some((child) => captureContainsText(child, expected));
  1322. }
  1323. function serializeRecord(record: MutableCaptureRecord): E2ENetworkCaptureRecord {
  1324. return record;
  1325. }
  1326. function durationMs(startedAt: string, completedAt: string): number {
  1327. return Math.max(0, Date.parse(completedAt) - Date.parse(startedAt));
  1328. }
  1329. async function stopServer(server: Server, writeArtifact: () => Promise<void>): Promise<void> {
  1330. await closeServerListener(server);
  1331. await writeArtifact();
  1332. }
  1333. async function closeServerListener(server: Server): Promise<void> {
  1334. await new Promise<void>((resolveStop, rejectStop) => {
  1335. server.close((error) => {
  1336. if (error) {
  1337. rejectStop(error);
  1338. return;
  1339. }
  1340. resolveStop();
  1341. });
  1342. });
  1343. }