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

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