conversation-session-subagent-prompt-assembly.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. import { assertSubagentListingTrajectory } from "../helpers/subagent-listing-assertions.js";
  2. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  3. import { dirname, join } from "node:path";
  4. import { clearAppData, DEFAULT_WORKSPACE } from "../helpers/desktop-app.js";
  5. import { resolveE2EHomeDir } from "../helpers/e2e-runtime-paths.js";
  6. import type {
  7. E2ENetworkCaptureArtifact,
  8. E2ENetworkCaptureRecord,
  9. } from "../helpers/network-capture-proxy.js";
  10. import { UPSTREAM_MODEL } from "../helpers/upstream-provider.js";
  11. import { prepareIncomingMessageCapability } from "../helpers/incoming-message-capability.js";
  12. import { waitForToolCallBlockByToolName } from "../helpers/conversation-session-tool.js";
  13. import {
  14. assertVisibleV4UserMessagesNotContaining,
  15. sendV4Prompt,
  16. startNewV4Draft,
  17. waitForV4AssistantMessageContaining,
  18. waitForV4ComposerText,
  19. waitForV4ConversationState,
  20. waitForV4UserMessageContaining,
  21. } from "../helpers/v4-conversation.js";
  22. const BUILTIN_PARENT_MARKER = "E2E_SUBAGENT_PROMPT_ASSEMBLY_BUILTIN_PARENT";
  23. const BUILTIN_CHILD_MARKER = "E2E_SUBAGENT_PROMPT_ASSEMBLY_BUILTIN_CHILD";
  24. const BUILTIN_CHILD_REPLY_TOKEN = "E2E_SUBAGENT_PROMPT_ASSEMBLY_BUILTIN_CHILD_OK";
  25. const BUILTIN_FINAL_TOKEN = "subagent-prompt-assembly-builtin-done";
  26. const EXPLORE_PARENT_MARKER = "E2E_SUBAGENT_PROMPT_ASSEMBLY_EXPLORE_PARENT";
  27. const EXPLORE_CHILD_MARKER = "E2E_SUBAGENT_PROMPT_ASSEMBLY_EXPLORE_CHILD";
  28. const EXPLORE_CHILD_REPLY_TOKEN = "E2E_SUBAGENT_PROMPT_ASSEMBLY_EXPLORE_CHILD_OK";
  29. const EXPLORE_FINAL_TOKEN = "subagent-prompt-assembly-explore-done";
  30. const CUSTOM_AGENT_NAME = "e2e-prompt-assembly-reviewer";
  31. const CUSTOM_AGENT_PROMPT_MARKER = "E2E_CUSTOM_PROMPT_ASSEMBLY_AGENT_BODY";
  32. const CUSTOM_PARENT_MARKER = "E2E_SUBAGENT_PROMPT_ASSEMBLY_CUSTOM_PARENT";
  33. const CUSTOM_CHILD_MARKER = "E2E_SUBAGENT_PROMPT_ASSEMBLY_CUSTOM_CHILD";
  34. const CUSTOM_CHILD_REPLY_TOKEN = "E2E_SUBAGENT_PROMPT_ASSEMBLY_CUSTOM_CHILD_OK";
  35. const CUSTOM_FINAL_TOKEN = "subagent-prompt-assembly-custom-done";
  36. const ISOLATED_CUSTOM_AGENT_NAME = "e2e-prompt-assembly-isolated";
  37. const ISOLATED_CUSTOM_AGENT_PROMPT_MARKER = "E2E_ISOLATED_CUSTOM_PROMPT_ASSEMBLY_AGENT_BODY";
  38. const ISOLATED_CUSTOM_PARENT_MARKER = "E2E_SUBAGENT_PROMPT_ASSEMBLY_ISOLATED_PARENT";
  39. const ISOLATED_CUSTOM_CHILD_MARKER = "E2E_SUBAGENT_PROMPT_ASSEMBLY_ISOLATED_CHILD";
  40. const ISOLATED_CUSTOM_CHILD_REPLY_TOKEN = "E2E_SUBAGENT_PROMPT_ASSEMBLY_ISOLATED_CHILD_OK";
  41. const ISOLATED_CUSTOM_FINAL_TOKEN = "subagent-prompt-assembly-isolated-done";
  42. const USER_AGENTS_MARKER = "E2E_SUBAGENT_USER_AGENTS_INSTRUCTION";
  43. const WORKSPACE_AGENTS_MARKER = "E2E_SUBAGENT_WORKSPACE_AGENTS_INSTRUCTION";
  44. const TEST_HOME_DIR = resolveE2EHomeDir();
  45. const USER_AGENTS_PATH = join(TEST_HOME_DIR, ".zcode", "AGENTS.md");
  46. const WORKSPACE_AGENTS_PATH = join(DEFAULT_WORKSPACE, "AGENTS.md");
  47. const CUSTOM_AGENT_PROFILE = `---
  48. name: ${CUSTOM_AGENT_NAME}
  49. description: E2E custom reviewer for subagent prompt assembly.
  50. tools: Read
  51. maxTurns: 1
  52. ---
  53. You are the E2E custom prompt assembly reviewer.
  54. ${CUSTOM_AGENT_PROMPT_MARKER}
  55. Reply only with the requested marker.
  56. `;
  57. const ISOLATED_CUSTOM_AGENT_PROFILE = `---
  58. name: ${ISOLATED_CUSTOM_AGENT_NAME}
  59. description: E2E custom reviewer that omits injected AGENTS.md.
  60. tools: Read
  61. maxTurns: 1
  62. injectAgentsMd: false
  63. ---
  64. You are the isolated E2E custom prompt assembly reviewer.
  65. ${ISOLATED_CUSTOM_AGENT_PROMPT_MARKER}
  66. Reply only with the requested marker.
  67. `;
  68. const CUSTOM_AGENT_PATHS = [
  69. join(TEST_HOME_DIR, ".zcode", "agents", `${CUSTOM_AGENT_NAME}.md`),
  70. join(TEST_HOME_DIR, ".zcode", "cli", "agents", `${CUSTOM_AGENT_NAME}.md`),
  71. ];
  72. const ISOLATED_CUSTOM_AGENT_PATHS = [
  73. join(TEST_HOME_DIR, ".zcode", "agents", `${ISOLATED_CUSTOM_AGENT_NAME}.md`),
  74. join(TEST_HOME_DIR, ".zcode", "cli", "agents", `${ISOLATED_CUSTOM_AGENT_NAME}.md`),
  75. ];
  76. describe("会话区 subagent prompt assembly E2E", () => {
  77. after(async () => {
  78. await browser.electron.restoreAllMocks();
  79. await clearAppData();
  80. await removeSubagentInstructionFixtures();
  81. });
  82. it("I21: child trajectory 应按 profile 注入或省略父级 AGENTS.md", async function () {
  83. this.timeout(240000);
  84. await seedSubagentInstructionFixtures();
  85. await prepareIncomingMessageCapability(false);
  86. await runSubagentPromptAssemblyScenario({
  87. agentPromptIncludes: [
  88. "You are an agent for ZCode CLI",
  89. "the caller will relay this to the user",
  90. ],
  91. agentPromptExcludes: [CUSTOM_AGENT_PROMPT_MARKER],
  92. childMarker: BUILTIN_CHILD_MARKER,
  93. childReplyToken: BUILTIN_CHILD_REPLY_TOKEN,
  94. finalToken: BUILTIN_FINAL_TOKEN,
  95. parentMarker: BUILTIN_PARENT_MARKER,
  96. shouldInjectAgentsMd: true,
  97. subagentType: "general-purpose",
  98. });
  99. // Bug 根因:四类请求复用同一历史会话会在第二轮前触发 compact,令本 case
  100. // 混入无关的压缩 fixture;保持同一窗口,但用新任务隔离每类 child trajectory。
  101. await startNewV4Draft();
  102. await runSubagentPromptAssemblyScenario({
  103. agentPromptIncludes: ["You are ZCode Explore", "READ-ONLY MODE"],
  104. agentPromptExcludes: [CUSTOM_AGENT_PROMPT_MARKER],
  105. childMarker: EXPLORE_CHILD_MARKER,
  106. childReplyToken: EXPLORE_CHILD_REPLY_TOKEN,
  107. finalToken: EXPLORE_FINAL_TOKEN,
  108. parentMarker: EXPLORE_PARENT_MARKER,
  109. shouldInjectAgentsMd: false,
  110. subagentType: "Explore",
  111. });
  112. await startNewV4Draft();
  113. await runSubagentPromptAssemblyScenario({
  114. agentPromptIncludes: [
  115. "You are the E2E custom prompt assembly reviewer.",
  116. CUSTOM_AGENT_PROMPT_MARKER,
  117. "Reply only with the requested marker.",
  118. ],
  119. agentPromptExcludes: ["You are an agent for ZCode CLI"],
  120. childMarker: CUSTOM_CHILD_MARKER,
  121. childReplyToken: CUSTOM_CHILD_REPLY_TOKEN,
  122. finalToken: CUSTOM_FINAL_TOKEN,
  123. parentMarker: CUSTOM_PARENT_MARKER,
  124. shouldInjectAgentsMd: true,
  125. subagentType: CUSTOM_AGENT_NAME,
  126. });
  127. await startNewV4Draft();
  128. await runSubagentPromptAssemblyScenario({
  129. agentPromptIncludes: [
  130. "You are the isolated E2E custom prompt assembly reviewer.",
  131. ISOLATED_CUSTOM_AGENT_PROMPT_MARKER,
  132. "Reply only with the requested marker.",
  133. ],
  134. agentPromptExcludes: ["You are an agent for ZCode CLI"],
  135. childMarker: ISOLATED_CUSTOM_CHILD_MARKER,
  136. childReplyToken: ISOLATED_CUSTOM_CHILD_REPLY_TOKEN,
  137. finalToken: ISOLATED_CUSTOM_FINAL_TOKEN,
  138. parentMarker: ISOLATED_CUSTOM_PARENT_MARKER,
  139. shouldInjectAgentsMd: false,
  140. subagentType: ISOLATED_CUSTOM_AGENT_NAME,
  141. });
  142. await assertCompleteSubagentInstructionTrajectory();
  143. });
  144. it("I21: MCS 首发 listing 与工具后去重应走通用 attachment", async function () {
  145. this.timeout(120000);
  146. await seedSubagentInstructionFixtures();
  147. await prepareIncomingMessageCapability(true);
  148. const modelId = "claude-opus-4-8";
  149. await runSubagentPromptAssemblyScenario({
  150. modelId,
  151. agentPromptIncludes: [
  152. "You are an agent for ZCode CLI",
  153. "the caller will relay this to the user",
  154. ],
  155. agentPromptExcludes: [CUSTOM_AGENT_PROMPT_MARKER],
  156. childMarker: BUILTIN_CHILD_MARKER,
  157. childReplyToken: BUILTIN_CHILD_REPLY_TOKEN,
  158. finalToken: BUILTIN_FINAL_TOKEN,
  159. parentMarker: BUILTIN_PARENT_MARKER,
  160. shouldInjectAgentsMd: true,
  161. subagentType: "general-purpose",
  162. });
  163. const artifact = await readCaptureArtifact();
  164. expect(artifact).not.toBeNull();
  165. assertSubagentListingTrajectory(
  166. {
  167. ...artifact!,
  168. records: artifact!.records.filter(
  169. (record) => readModelFromCapture(record.requestJson) === modelId,
  170. ),
  171. },
  172. { parentMarker: BUILTIN_PARENT_MARKER, childMarker: BUILTIN_CHILD_MARKER },
  173. [CUSTOM_AGENT_NAME, ISOLATED_CUSTOM_AGENT_NAME],
  174. true,
  175. );
  176. });
  177. });
  178. async function seedSubagentInstructionFixtures() {
  179. const files = [
  180. ...CUSTOM_AGENT_PATHS.map((path) => ({ content: CUSTOM_AGENT_PROFILE, path })),
  181. ...ISOLATED_CUSTOM_AGENT_PATHS.map((path) => ({
  182. content: ISOLATED_CUSTOM_AGENT_PROFILE,
  183. path,
  184. })),
  185. { content: `${USER_AGENTS_MARKER}\n`, path: USER_AGENTS_PATH },
  186. { content: `${WORKSPACE_AGENTS_MARKER}\n`, path: WORKSPACE_AGENTS_PATH },
  187. ];
  188. for (const file of files) {
  189. await mkdir(dirname(file.path), { recursive: true });
  190. await writeFile(file.path, file.content, "utf-8");
  191. }
  192. }
  193. async function removeSubagentInstructionFixtures() {
  194. await Promise.all(
  195. [
  196. ...CUSTOM_AGENT_PATHS,
  197. ...ISOLATED_CUSTOM_AGENT_PATHS,
  198. USER_AGENTS_PATH,
  199. WORKSPACE_AGENTS_PATH,
  200. ].map((path) => rm(path, { force: true })),
  201. );
  202. }
  203. async function runSubagentPromptAssemblyScenario(input: {
  204. modelId?: string;
  205. agentPromptExcludes: string[];
  206. agentPromptIncludes: string[];
  207. childMarker: string;
  208. childReplyToken: string;
  209. finalToken: string;
  210. parentMarker: string;
  211. shouldInjectAgentsMd: boolean;
  212. subagentType: string;
  213. }) {
  214. const marker = `${input.parentMarker}_${Date.now()}`;
  215. const prompt =
  216. `${marker}: Use the Agent tool with subagent_type "${input.subagentType}". ` +
  217. `Ask it to reply with exactly "${input.childReplyToken}". ` +
  218. `After the subagent returns, reply with exactly "${input.finalToken}" and no other text.`;
  219. await sendV4Prompt(prompt);
  220. await waitForV4ComposerText("", `${input.subagentType} 首发后输入框没有清空`);
  221. await waitForV4UserMessageContaining(marker);
  222. const childRecord = await waitForChildSubagentRequestCapture({
  223. childMarker: input.childMarker,
  224. parentMarker: input.parentMarker,
  225. modelId: input.modelId ?? UPSTREAM_MODEL,
  226. });
  227. expect(readModelFromCapture(childRecord.requestJson)).toBe(input.modelId ?? UPSTREAM_MODEL);
  228. assertChildSystemPromptShape(childRecord.requestJson, {
  229. agentPromptExcludes: input.agentPromptExcludes,
  230. agentPromptIncludes: input.agentPromptIncludes,
  231. });
  232. assertChildUserInstructions(childRecord.requestJson, {
  233. childMarker: input.childMarker,
  234. shouldInject: input.shouldInjectAgentsMd,
  235. });
  236. await waitForV4AssistantMessageContaining(input.finalToken);
  237. await waitForV4ConversationState(
  238. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  239. `${input.subagentType} prompt assembly case 完成后没有回到 idle`,
  240. 90000,
  241. );
  242. const agentBlock = await waitForToolCallBlockByToolName("Agent");
  243. expect(agentBlock.status).toBe("completed");
  244. await assertVisibleV4UserMessagesNotContaining("Available agent types for the Agent tool:");
  245. }
  246. async function waitForChildSubagentRequestCapture(input: {
  247. modelId: string;
  248. childMarker: string;
  249. parentMarker: string;
  250. }) {
  251. let latestArtifact: E2ENetworkCaptureArtifact | null = null;
  252. try {
  253. await browser.waitUntil(
  254. async () => {
  255. latestArtifact = await readCaptureArtifact();
  256. return Boolean(findChildSubagentRequest(latestArtifact, input));
  257. },
  258. {
  259. timeout: 30000,
  260. timeoutMsg: `没有捕获到 subagent prompt assembly child 请求: ${input.childMarker}`,
  261. },
  262. );
  263. } catch (error) {
  264. throw new Error(
  265. `没有捕获到 subagent prompt assembly child 请求\n${JSON.stringify(
  266. summarizeRequestsContaining(latestArtifact, input.childMarker),
  267. null,
  268. 2,
  269. )}`,
  270. { cause: error },
  271. );
  272. }
  273. const record = findChildSubagentRequest(latestArtifact, input);
  274. if (!record) {
  275. throw new Error("subagent prompt assembly child 请求在等待完成后仍不存在");
  276. }
  277. return record;
  278. }
  279. async function readCaptureArtifact(): Promise<E2ENetworkCaptureArtifact | null> {
  280. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  281. if (!capturePath) {
  282. return null;
  283. }
  284. try {
  285. return JSON.parse(await readFile(capturePath, "utf-8")) as E2ENetworkCaptureArtifact;
  286. } catch (error) {
  287. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  288. return null;
  289. }
  290. throw error;
  291. }
  292. }
  293. function findChildSubagentRequest(
  294. artifact: E2ENetworkCaptureArtifact | null,
  295. input: { childMarker: string; parentMarker: string; modelId: string },
  296. ) {
  297. return (
  298. artifact?.records.find(
  299. (record) =>
  300. isUpstreamMessageRequest(record) &&
  301. record.status === "complete" &&
  302. captureContainsText(record.requestJson, input.childMarker) &&
  303. !captureContainsText(record.requestJson, input.parentMarker) &&
  304. readModelFromCapture(record.requestJson) === input.modelId,
  305. ) ?? null
  306. );
  307. }
  308. function assertChildSystemPromptShape(
  309. requestJson: unknown,
  310. input: { agentPromptExcludes: string[]; agentPromptIncludes: string[] },
  311. ) {
  312. const systems = readSystemMessagesFromCapture(requestJson);
  313. expect(systems).toHaveLength(2);
  314. expect(readSystemCacheControlsFromCapture(requestJson)).toEqual([
  315. { type: "ephemeral" },
  316. { type: "ephemeral" },
  317. ]);
  318. expect(systems[0]).toBe("You are ZCode, an interactive coding agent");
  319. for (const expected of input.agentPromptIncludes) {
  320. expect(systems[1]).toContain(expected);
  321. }
  322. for (const forbidden of input.agentPromptExcludes) {
  323. expect(systems[1]).not.toContain(forbidden);
  324. }
  325. expect(systems[1]).toContain("\n\nNotes:");
  326. expect(systems[1]).toContain("the parent agent reads your text output");
  327. expect(systems[1]).toContain(
  328. "\n\nHere is useful information about the environment you are running in:",
  329. );
  330. expect(systems[1]!.indexOf("\n\nHere is useful information")).toBeGreaterThan(
  331. systems[1]!.indexOf("\n\nNotes:"),
  332. );
  333. expect(systems[1]).toContain("Working directory:");
  334. expect(systems[1]).toContain("Is directory a git repo:");
  335. expect(systems[1]).toContain("Platform:");
  336. expect(systems[1]).toContain("Shell:");
  337. expect(systems[1]).toContain("OS Version:");
  338. expect(systems[1]).toContain("You are powered by the model named");
  339. }
  340. function assertChildUserInstructions(
  341. requestJson: unknown,
  342. input: { childMarker: string; shouldInject: boolean },
  343. ) {
  344. const systems = readSystemMessagesFromCapture(requestJson).join("\n");
  345. // Bug 根因:provider projection 会把 context_prefix 与真实任务编码为同一条 user
  346. // message 的相邻 text blocks;按 message 聚合文本会把两者误判为同一位置。
  347. const messageBlocks = readMessageTextBlocksFromCapture(requestJson);
  348. const contextIndex = messageBlocks.findIndex(
  349. (block) => block.role === "user" && block.text.includes("# currentDate"),
  350. );
  351. const taskIndex = messageBlocks.findIndex(
  352. (block) => block.role === "user" && block.text.includes(input.childMarker),
  353. );
  354. expect(contextIndex).toBeGreaterThanOrEqual(0);
  355. expect(taskIndex).toBeGreaterThan(contextIndex);
  356. expect(messageBlocks[contextIndex]?.text).toContain("<system-reminder>");
  357. expect(systems).not.toContain("# agentsMd");
  358. expect(systems).not.toContain("# claudeMd");
  359. expect(systems).not.toContain(USER_AGENTS_MARKER);
  360. expect(systems).not.toContain(WORKSPACE_AGENTS_MARKER);
  361. if (!input.shouldInject) {
  362. expect(countCaptureOccurrences(requestJson, "# agentsMd")).toBe(0);
  363. expect(countCaptureOccurrences(requestJson, "# claudeMd")).toBe(0);
  364. expect(countCaptureOccurrences(requestJson, USER_AGENTS_MARKER)).toBe(0);
  365. expect(countCaptureOccurrences(requestJson, WORKSPACE_AGENTS_MARKER)).toBe(0);
  366. return;
  367. }
  368. const contextText = messageBlocks[contextIndex]?.text ?? "";
  369. expect(countCaptureOccurrences(requestJson, "# agentsMd")).toBe(1);
  370. expect(countCaptureOccurrences(requestJson, "# claudeMd")).toBe(0);
  371. expect(countCaptureOccurrences(requestJson, USER_AGENTS_MARKER)).toBe(1);
  372. expect(countCaptureOccurrences(requestJson, WORKSPACE_AGENTS_MARKER)).toBe(1);
  373. expect(contextText).toContain("# agentsMd");
  374. expect(contextText).toContain("Codebase and user instructions are shown below.");
  375. expect(contextText.indexOf("# agentsMd")).toBeLessThan(contextText.indexOf(USER_AGENTS_MARKER));
  376. expect(contextText.indexOf(USER_AGENTS_MARKER)).toBeLessThan(
  377. contextText.indexOf(WORKSPACE_AGENTS_MARKER),
  378. );
  379. expect(contextText.indexOf(WORKSPACE_AGENTS_MARKER)).toBeLessThan(
  380. contextText.indexOf("# currentDate"),
  381. );
  382. }
  383. async function assertCompleteSubagentInstructionTrajectory() {
  384. const captured = await readCaptureArtifact();
  385. const artifact = captured && {
  386. ...captured,
  387. records: captured.records.filter(
  388. (record) => readModelFromCapture(record.requestJson) === UPSTREAM_MODEL,
  389. ),
  390. };
  391. expect(artifact).not.toBeNull();
  392. const scenarios = [
  393. { childMarker: BUILTIN_CHILD_MARKER, parentMarker: BUILTIN_PARENT_MARKER },
  394. { childMarker: EXPLORE_CHILD_MARKER, parentMarker: EXPLORE_PARENT_MARKER },
  395. { childMarker: CUSTOM_CHILD_MARKER, parentMarker: CUSTOM_PARENT_MARKER },
  396. {
  397. childMarker: ISOLATED_CUSTOM_CHILD_MARKER,
  398. parentMarker: ISOLATED_CUSTOM_PARENT_MARKER,
  399. },
  400. ];
  401. for (const scenario of scenarios) {
  402. assertSubagentListingTrajectory(
  403. artifact!,
  404. scenario,
  405. [CUSTOM_AGENT_NAME, ISOLATED_CUSTOM_AGENT_NAME],
  406. false,
  407. );
  408. const matches =
  409. artifact?.records.filter(
  410. (record) =>
  411. isUpstreamMessageRequest(record) &&
  412. record.status === "complete" &&
  413. captureContainsText(record.requestJson, scenario.childMarker) &&
  414. !captureContainsText(record.requestJson, scenario.parentMarker),
  415. ) ?? [];
  416. expect(matches).toHaveLength(1);
  417. }
  418. }
  419. function readMessageTextBlocksFromCapture(value: unknown): Array<{ role: string; text: string }> {
  420. if (!value || typeof value !== "object" || Array.isArray(value)) {
  421. return [];
  422. }
  423. const messages = (value as { messages?: unknown }).messages;
  424. if (!Array.isArray(messages)) {
  425. return [];
  426. }
  427. return messages.flatMap((message) => {
  428. if (!message || typeof message !== "object" || Array.isArray(message)) {
  429. return [];
  430. }
  431. const role = (message as { role?: unknown }).role;
  432. if (typeof role !== "string") {
  433. return [];
  434. }
  435. return readSystemContent((message as { content?: unknown }).content).map((text) => ({
  436. role,
  437. text,
  438. }));
  439. });
  440. }
  441. function readSystemMessagesFromCapture(value: unknown): string[] {
  442. if (!value || typeof value !== "object" || Array.isArray(value)) {
  443. return [];
  444. }
  445. // Anthropic Messages API 的 provider-visible system 在顶层 system 字段。
  446. const topLevelSystem = readSystemContent((value as { system?: unknown }).system);
  447. if (topLevelSystem.length > 0) {
  448. return topLevelSystem;
  449. }
  450. const messages = (value as { messages?: unknown }).messages;
  451. if (!Array.isArray(messages)) {
  452. return [];
  453. }
  454. return messages.flatMap((message) => {
  455. if (!message || typeof message !== "object" || Array.isArray(message)) {
  456. return [];
  457. }
  458. const role = (message as { role?: unknown }).role;
  459. if (role !== "system") {
  460. return [];
  461. }
  462. const content = (message as { content?: unknown }).content;
  463. return readSystemContent(content);
  464. });
  465. }
  466. function readSystemContent(content: unknown): string[] {
  467. if (typeof content === "string") {
  468. return [content];
  469. }
  470. if (!Array.isArray(content)) {
  471. return [];
  472. }
  473. return content.flatMap((part) => {
  474. if (typeof part === "string") {
  475. return [part];
  476. }
  477. if (!part || typeof part !== "object" || Array.isArray(part)) {
  478. return [];
  479. }
  480. const text = (part as { text?: unknown }).text;
  481. return typeof text === "string" ? [text] : [];
  482. });
  483. }
  484. function readSystemCacheControlsFromCapture(value: unknown): unknown[] {
  485. if (!value || typeof value !== "object" || Array.isArray(value)) {
  486. return [];
  487. }
  488. const topLevelSystem = readSystemCacheControls((value as { system?: unknown }).system);
  489. if (topLevelSystem.length > 0) {
  490. return topLevelSystem;
  491. }
  492. const messages = (value as { messages?: unknown }).messages;
  493. if (!Array.isArray(messages)) {
  494. return [];
  495. }
  496. return messages.flatMap((message) => {
  497. if (!message || typeof message !== "object" || Array.isArray(message)) {
  498. return [];
  499. }
  500. const role = (message as { role?: unknown }).role;
  501. if (role !== "system") {
  502. return [];
  503. }
  504. const messageRecord = message as Record<string, unknown>;
  505. const contentControls = readSystemCacheControls(messageRecord.content);
  506. if (contentControls.length > 0) {
  507. return contentControls;
  508. }
  509. return [readCacheControl(messageRecord)];
  510. });
  511. }
  512. function readSystemCacheControls(content: unknown): unknown[] {
  513. if (typeof content === "string") {
  514. return [undefined];
  515. }
  516. if (!Array.isArray(content)) {
  517. return [];
  518. }
  519. return content.flatMap((part) => {
  520. if (typeof part === "string") {
  521. return [undefined];
  522. }
  523. if (!part || typeof part !== "object" || Array.isArray(part)) {
  524. return [];
  525. }
  526. const partRecord = part as Record<string, unknown>;
  527. const text = partRecord.text;
  528. return typeof text === "string" ? [readCacheControl(partRecord)] : [];
  529. });
  530. }
  531. function readCacheControl(record: Record<string, unknown>): unknown {
  532. return record.cache_control ?? record.cacheControl;
  533. }
  534. function summarizeRequestsContaining(
  535. artifact: E2ENetworkCaptureArtifact | null,
  536. expectedText: string,
  537. ) {
  538. return {
  539. records:
  540. artifact?.records
  541. .filter((record) => captureContainsText(record.requestJson, expectedText))
  542. .map((record) => ({
  543. model: readModelFromCapture(record.requestJson),
  544. path: record.path,
  545. status: record.status,
  546. statusCode: record.statusCode,
  547. systems: readSystemMessagesFromCapture(record.requestJson).length,
  548. })) ?? [],
  549. };
  550. }
  551. function isUpstreamMessageRequest(record: E2ENetworkCaptureRecord) {
  552. return (
  553. record.method === "POST" &&
  554. (record.path.includes("/messages") || record.path.includes("/chat/completions"))
  555. );
  556. }
  557. function readModelFromCapture(value: unknown) {
  558. if (!value || typeof value !== "object" || Array.isArray(value)) {
  559. return null;
  560. }
  561. const model = (value as { model?: unknown }).model;
  562. return typeof model === "string" ? model : null;
  563. }
  564. function captureContainsText(value: unknown, expected: string): boolean {
  565. if (typeof value === "string") {
  566. return value.includes(expected);
  567. }
  568. if (Array.isArray(value)) {
  569. return value.some((item) => captureContainsText(item, expected));
  570. }
  571. if (!value || typeof value !== "object") {
  572. return false;
  573. }
  574. return Object.values(value).some((child) => captureContainsText(child, expected));
  575. }
  576. function countCaptureOccurrences(value: unknown, marker: string): number {
  577. if (typeof value === "string") {
  578. return value.split(marker).length - 1;
  579. }
  580. if (Array.isArray(value)) {
  581. return value.reduce((total, item) => total + countCaptureOccurrences(item, marker), 0);
  582. }
  583. if (!value || typeof value !== "object") {
  584. return 0;
  585. }
  586. return Object.values(value).reduce(
  587. (total, item) => total + countCaptureOccurrences(item, marker),
  588. 0,
  589. );
  590. }