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

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