upstream-replay-server.ts 57 KB

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