upstream-replay-server.ts 40 KB

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