subagent-explore.test.ts 160 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344
  1. import { setup as setupProfileScenario, done as profileDone } from "./subagent-profile-scenario.js";
  2. import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
  3. import { describe, expect, it, vi } from "vitest";
  4. import { createTestModelSelection } from "./test-model-selection.js";
  5. import { mkdtemp, readFile } from "node:fs/promises";
  6. import { tmpdir } from "node:os";
  7. import { join } from "node:path";
  8. import {
  9. CoreErrorType,
  10. type HttpClientPort,
  11. type McpPort,
  12. type SkillContent,
  13. type SkillLoadOutcome,
  14. type SkillPort,
  15. SEND_MESSAGE_TOOL_NAME,
  16. RESPOND_TO_COORDINATOR_TOOL_NAME,
  17. SessionEventType,
  18. type SessionId,
  19. type SessionEvent,
  20. type SessionStorePort,
  21. createModelId,
  22. createModelProviderId,
  23. createSessionId,
  24. createToolCallId,
  25. createTraceId,
  26. createTurnId,
  27. isCoreError,
  28. modelMessageContentToText,
  29. } from "@zcode/contracts";
  30. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  31. import { toMcpToolName } from "../src/mcp/index.js";
  32. import { PermissionService } from "../src/permission/index.js";
  33. import { createExploreSubagentPort } from "../src/subagent/runner.js";
  34. import { createTestSessionEventStore } from "./test-event-store.js";
  35. import {
  36. createTestModelFactory,
  37. type TestModelExecutionObservation,
  38. } from "./test-runtime-model.js";
  39. const exploreAgentPrompt = `You are ZCode Explore, a file search and codebase research specialist for ZCode CLI. You excel at thoroughly navigating and exploring codebases.
  40. === CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
  41. This is a READ-ONLY exploration task. You are STRICTLY PROHIBITED from:
  42. - Creating new files (no Write, touch, or file creation of any kind)
  43. - Modifying existing files (no Edit operations)
  44. - Deleting files (no rm or deletion)
  45. - Moving or copying files (no mv or cp)
  46. - Creating temporary files anywhere, including /tmp
  47. - Using redirect operators (>, >>, |) or heredocs to write to files
  48. - Running ANY commands that change system state
  49. Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools - attempting to edit files will fail.
  50. Your strengths:
  51. - Rapidly finding files using glob patterns
  52. - Searching code and text with powerful regex patterns
  53. - Reading and analyzing file contents
  54. Guidelines:
  55. - Use \`find\` via Bash for broad file pattern matching
  56. - Use \`grep\` via Bash for searching file contents with regex
  57. - Use Read when you know the specific file path you need to read
  58. - Use Bash ONLY for read-only operations (ls, git status, git log, git diff, find, grep, cat, head, tail)
  59. - NEVER use Bash for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or any file creation/modification
  60. - Adapt your search approach based on the thoroughness level specified by the caller
  61. - Communicate your final report directly as a regular message - do NOT attempt to create files
  62. NOTE: You are meant to be a fast agent that returns output as quickly as possible. In order to achieve this you must:
  63. - Make efficient use of the tools that you have at your disposal: be smart about how you search for files and implementations
  64. - Wherever possible you should try to spawn multiple parallel tool calls for grepping and reading files
  65. Complete the user's search request efficiently and report your findings clearly.`;
  66. const subagentCommonNotes = `Notes:
  67. - Agent threads always have their cwd reset between bash calls, as a result please only use absolute file paths.
  68. - In your final response, share file paths (always absolute, never relative) that are relevant to the task. Include code snippets only when the exact text is load-bearing (e.g., a bug you found, a function signature the caller asked for) — do not recap code you merely read.
  69. - For clear communication with the user the assistant MUST avoid using emojis.
  70. - Do not use a colon before tool calls. Text like "Let me read the file:" followed by a read tool call should just be "Let me read the file." with a period.
  71. - Do NOT Write report/summary/findings/analysis .md files. Return findings directly as your final assistant message — the parent agent reads your text output, not files you create.`;
  72. const subagentEnvironmentContext = `Here is useful information about the environment you are running in:
  73. <env>
  74. Working directory: /Users/dev/Desktop/Z/z-code/apps/zcode-cli
  75. Is directory a git repo: Yes
  76. Platform: darwin
  77. Shell: Git Bash
  78. OS Version: Darwin 24.3.0
  79. </env>
  80. You are powered by the model named anthropic/claude-haiku-4-5-20251001-cc.`;
  81. const exploreSystemMessages = [
  82. "You are ZCode, an interactive coding agent",
  83. // 正文已合并为一段;保留原 prompt、Notes、环境及换行顺序的逐字校验。
  84. `\n${exploreAgentPrompt}\n\n${subagentCommonNotes}\n\n${subagentEnvironmentContext}`,
  85. ];
  86. async function waitForCondition(check: () => boolean, timeoutMs = 1_000): Promise<void> {
  87. const startedAt = Date.now();
  88. while (!check()) {
  89. if (Date.now() - startedAt > timeoutMs) {
  90. throw new Error("Timed out waiting for condition");
  91. }
  92. await new Promise((resolve) => setTimeout(resolve, 5));
  93. }
  94. }
  95. describe("Explore subagent", () => {
  96. it("fails a foreground run after the child runner stays inactive", async () => {
  97. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-subagent-inactive-"));
  98. const emittedEvents: any[] = [];
  99. const port = createExploreSubagentPort({
  100. createAgentId: () => "agent_inactive",
  101. inactivityTimeoutMs: 20,
  102. outputRootDir,
  103. async emitParentEvent(event) {
  104. emittedEvents.push(event);
  105. },
  106. runExploreAgent: async (request) => {
  107. await request.onSessionReady?.();
  108. return new Promise(() => {});
  109. },
  110. });
  111. const runPromise = port
  112. .run({
  113. agentType: "Explore",
  114. description: "Inactive child",
  115. parentToolCallId: createToolCallId("call_inactive_child"),
  116. prompt: "Search until the child stops reporting activity.",
  117. sessionId: createSessionId("parent_inactive_child"),
  118. trace: {
  119. traceId: createTraceId(),
  120. sessionId: createSessionId("parent_inactive_child"),
  121. turnId: createTurnId("turn_inactive_child"),
  122. },
  123. turnId: createTurnId("turn_inactive_child"),
  124. workingDirectory: "/tmp",
  125. workspaceRoot: "/tmp",
  126. })
  127. .then(
  128. () => ({ kind: "completed" as const }),
  129. (error: unknown) => ({ error, kind: "failed" as const }),
  130. );
  131. const result = await Promise.race([
  132. runPromise,
  133. new Promise<{ kind: "hung" }>((resolve) => setTimeout(() => resolve({ kind: "hung" }), 160)),
  134. ]);
  135. expect(result.kind).toBe("failed");
  136. if (result.kind !== "failed") return;
  137. expect(isCoreError(result.error)).toBe(true);
  138. if (isCoreError(result.error)) {
  139. expect(result.error.type).toBe(CoreErrorType.ToolTimeout);
  140. }
  141. expect(
  142. emittedEvents.some(
  143. (event) =>
  144. event.type === SessionEventType.SubagentStopped &&
  145. (event.payload as any).status === "failed",
  146. ),
  147. ).toBe(true);
  148. });
  149. it("fails a foreground run when the child stays inactive before session ready", async () => {
  150. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-subagent-pre-ready-inactive-"));
  151. const emittedEvents: SessionEvent[] = [];
  152. const childStarted = createDeferred<void>();
  153. const port = createExploreSubagentPort({
  154. createAgentId: () => "agent_pre_ready_inactive",
  155. inactivityTimeoutMs: 20,
  156. outputRootDir,
  157. async emitParentEvent(event) {
  158. emittedEvents.push(event);
  159. },
  160. runExploreAgent: async () => {
  161. childStarted.resolve();
  162. return new Promise(() => {});
  163. },
  164. });
  165. const runPromise = port
  166. .run({
  167. agentType: "Explore",
  168. description: "Pre-ready inactive child",
  169. parentToolCallId: createToolCallId("call_pre_ready_inactive_child"),
  170. prompt: "Never finish child setup.",
  171. sessionId: createSessionId("parent_pre_ready_inactive_child"),
  172. trace: {
  173. traceId: createTraceId(),
  174. sessionId: createSessionId("parent_pre_ready_inactive_child"),
  175. turnId: createTurnId("turn_pre_ready_inactive_child"),
  176. },
  177. turnId: createTurnId("turn_pre_ready_inactive_child"),
  178. workingDirectory: "/tmp",
  179. workspaceRoot: "/tmp",
  180. })
  181. .then(
  182. () => ({ kind: "completed" as const }),
  183. (error: unknown) => ({ error, kind: "failed" as const }),
  184. );
  185. await childStarted.promise;
  186. const result = await Promise.race([
  187. runPromise,
  188. new Promise<{ kind: "hung" }>((resolve) => setTimeout(() => resolve({ kind: "hung" }), 160)),
  189. ]);
  190. expect(result.kind).toBe("failed");
  191. if (result.kind !== "failed") return;
  192. expect(isCoreError(result.error)).toBe(true);
  193. if (isCoreError(result.error)) {
  194. expect(result.error.type).toBe(CoreErrorType.ToolTimeout);
  195. }
  196. expect(emittedEvents).toEqual([]);
  197. await expect(port.getTask?.("agent_pre_ready_inactive")).resolves.toBeUndefined();
  198. });
  199. it("stops waiting when the parent aborts while the child runner is unresponsive", async () => {
  200. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-subagent-abort-"));
  201. const abortController = new AbortController();
  202. const emittedEvents: any[] = [];
  203. const port = createExploreSubagentPort({
  204. createAgentId: () => "agent_unresponsive",
  205. outputRootDir,
  206. async emitParentEvent(event) {
  207. emittedEvents.push(event);
  208. },
  209. runExploreAgent: async (request) => {
  210. await request.onSessionReady?.();
  211. return new Promise(() => {});
  212. },
  213. });
  214. const runPromise = port
  215. .run(
  216. {
  217. agentType: "Explore",
  218. description: "Unresponsive child",
  219. parentToolCallId: createToolCallId("call_unresponsive_child"),
  220. prompt: "Search until the model stops responding.",
  221. sessionId: createSessionId("parent_unresponsive_child"),
  222. trace: {
  223. traceId: createTraceId(),
  224. sessionId: createSessionId("parent_unresponsive_child"),
  225. turnId: createTurnId("turn_unresponsive_child"),
  226. },
  227. turnId: createTurnId("turn_unresponsive_child"),
  228. workingDirectory: "/tmp",
  229. workspaceRoot: "/tmp",
  230. },
  231. { signal: abortController.signal },
  232. )
  233. .then(
  234. () => ({ kind: "completed" as const }),
  235. (error: unknown) => ({ error, kind: "failed" as const }),
  236. );
  237. await waitForCondition(() =>
  238. emittedEvents.some((event) => event.type === SessionEventType.SubagentSpawned),
  239. );
  240. abortController.abort(new Error("parent aborted unresponsive subagent"));
  241. const result = await Promise.race([
  242. runPromise,
  243. new Promise<{ kind: "hung" }>((resolve) => setTimeout(() => resolve({ kind: "hung" }), 80)),
  244. ]);
  245. expect(result.kind).toBe("failed");
  246. if (result.kind !== "failed") return;
  247. expect(isCoreError(result.error)).toBe(true);
  248. if (isCoreError(result.error)) {
  249. expect(result.error.type).toBe(CoreErrorType.ToolCancelled);
  250. }
  251. expect(
  252. emittedEvents.some(
  253. (event) =>
  254. event.type === SessionEventType.SubagentStopped &&
  255. (event.payload as any).status === "failed",
  256. ),
  257. ).toBe(true);
  258. });
  259. it("stops waiting when the parent aborts before the child session is ready", async () => {
  260. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-subagent-pre-ready-abort-"));
  261. const abortController = new AbortController();
  262. const emittedEvents: SessionEvent[] = [];
  263. const childStarted = createDeferred<void>();
  264. const port = createExploreSubagentPort({
  265. createAgentId: () => "agent_pre_ready_abort",
  266. outputRootDir,
  267. async emitParentEvent(event) {
  268. emittedEvents.push(event);
  269. },
  270. runExploreAgent: async () => {
  271. childStarted.resolve();
  272. return new Promise(() => {});
  273. },
  274. });
  275. const runPromise = port
  276. .run(
  277. {
  278. agentType: "Explore",
  279. description: "Pre-ready aborted child",
  280. parentToolCallId: createToolCallId("call_pre_ready_aborted_child"),
  281. prompt: "Never finish child setup.",
  282. sessionId: createSessionId("parent_pre_ready_aborted_child"),
  283. trace: {
  284. traceId: createTraceId(),
  285. sessionId: createSessionId("parent_pre_ready_aborted_child"),
  286. turnId: createTurnId("turn_pre_ready_aborted_child"),
  287. },
  288. turnId: createTurnId("turn_pre_ready_aborted_child"),
  289. workingDirectory: "/tmp",
  290. workspaceRoot: "/tmp",
  291. },
  292. { signal: abortController.signal },
  293. )
  294. .then(
  295. () => ({ kind: "completed" as const }),
  296. (error: unknown) => ({ error, kind: "failed" as const }),
  297. );
  298. await childStarted.promise;
  299. abortController.abort(new Error("parent aborted before child session ready"));
  300. const result = await Promise.race([
  301. runPromise,
  302. new Promise<{ kind: "hung" }>((resolve) => setTimeout(() => resolve({ kind: "hung" }), 80)),
  303. ]);
  304. expect(result.kind).toBe("failed");
  305. if (result.kind !== "failed") return;
  306. expect(isCoreError(result.error)).toBe(true);
  307. if (isCoreError(result.error)) {
  308. expect(result.error.type).toBe(CoreErrorType.ToolCancelled);
  309. }
  310. expect(emittedEvents).toEqual([]);
  311. await expect(port.getTask?.("agent_pre_ready_abort")).resolves.toBeUndefined();
  312. });
  313. it("runs through Agent with a read-only Explore tool pool and preserves trace context", async () => {
  314. const sessionId = createSessionId("runtime-explore-subagent");
  315. const eventStore = createTestSessionEventStore();
  316. const sessionStore = createRecordingSubagentSessionStore();
  317. const parentRequests: any[] = [];
  318. const childRequests: any[] = [];
  319. const childObservations: TestModelExecutionObservation[] = [];
  320. const parentSecondRequests: any[] = [];
  321. const liveEvents: SessionEvent[] = [];
  322. const childPersistedAtSpawn: boolean[] = [];
  323. let parentCallCount = 0;
  324. const modelSelection = {
  325. providerId: createModelProviderId("anthropic"),
  326. modelId: createModelId("claude-haiku-4-5-20251001-cc"),
  327. };
  328. const runtime = createTestAgentRuntime(
  329. sessionId,
  330. {
  331. mode: "build",
  332. modelSelection: createTestModelSelection(modelSelection),
  333. bashShellSelection: {
  334. dialect: "git-bash",
  335. display: { name: "Git Bash" },
  336. path: "C:\\Program Files\\Git\\bin\\bash.exe",
  337. source: "user-config",
  338. },
  339. workingDirectory: "/Users/dev/Desktop/Z/z-code/apps/zcode-cli",
  340. currentDate: "2026-06-04",
  341. projectContext: {
  342. type: "node",
  343. packageManager: "pnpm",
  344. scripts: {
  345. test: "vitest",
  346. },
  347. },
  348. envInfo: {
  349. cwd: "/Users/dev/Desktop/Z/z-code/apps/zcode-cli",
  350. platform: "darwin",
  351. shell: "zsh",
  352. osVersion: "Darwin 24.3.0",
  353. nodeVersion: "24.14.0",
  354. isGitRepository: true,
  355. },
  356. },
  357. {
  358. eventStore,
  359. eventSink: {
  360. async onSessionEvent(event) {
  361. liveEvents.push(event);
  362. if (event.type === SessionEventType.SubagentSpawned) {
  363. const childSessionId = (event.payload as { childSessionId: string }).childSessionId;
  364. const child = await sessionStore.getSession(childSessionId as SessionId);
  365. childPersistedAtSpawn.push(child?.taskType === "subagent_child");
  366. }
  367. },
  368. },
  369. sessionStore,
  370. modelFactory: createTestModelFactory({
  371. properties: { supportsNativeWebSearch: true },
  372. async generateText(request: any, observation) {
  373. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  374. if (toolNames.includes("Agent")) {
  375. parentRequests.push(request);
  376. parentCallCount++;
  377. if (parentCallCount === 1) {
  378. return {
  379. finishReason: "tool-calls",
  380. providerMetadata: undefined,
  381. text: "",
  382. toolCalls: [
  383. {
  384. id: "call_explore",
  385. name: "Agent",
  386. input: {
  387. description: "Find runtime loop",
  388. prompt: "Find where the runtime injects tool results.",
  389. subagent_type: "Explore",
  390. },
  391. },
  392. ],
  393. usage: {
  394. inputTokens: 1,
  395. outputTokens: 1,
  396. totalTokens: 2,
  397. },
  398. };
  399. }
  400. parentSecondRequests.push(request);
  401. return {
  402. finishReason: "stop",
  403. providerMetadata: undefined,
  404. text: "parent used explore result",
  405. usage: {
  406. inputTokens: 2,
  407. outputTokens: 3,
  408. totalTokens: 5,
  409. },
  410. };
  411. }
  412. childRequests.push(request);
  413. childObservations.push(observation);
  414. return {
  415. finishReason: "stop",
  416. providerMetadata: undefined,
  417. text: "Explore found runtime tool result injection in packages/core/src/runtime.ts.",
  418. usage: {
  419. inputTokens: 3,
  420. outputTokens: 4,
  421. totalTokens: 7,
  422. },
  423. };
  424. },
  425. } as never),
  426. },
  427. );
  428. const result = await runtime.executeTurn("Use an explore agent for this question");
  429. const parentEvents = await eventStore.getEvents(sessionId);
  430. const spawnEvent = parentEvents.find(
  431. (event) => event.type === SessionEventType.SubagentSpawned,
  432. );
  433. const stoppedEvent = parentEvents.find(
  434. (event) => event.type === SessionEventType.SubagentStopped,
  435. );
  436. const toolResultEvent = parentEvents.find(
  437. (event) => event.type === SessionEventType.ToolCallResult,
  438. );
  439. const childSessionId = (spawnEvent?.payload as any)?.childSessionId;
  440. const childEvents = await eventStore.getEvents(childSessionId);
  441. const childPersistedMessages = await sessionStore.messages({ sessionID: childSessionId });
  442. const childPersistedUserMessage = childPersistedMessages.find(
  443. (message) => message.info.role === "user",
  444. );
  445. const initialModelTimeline = childPersistedMessages
  446. .flatMap((message) => message.parts)
  447. .find((part) => part.type === "timeline" && part.timelineType === "model_change");
  448. const parentFirstRequestText = parentRequests[0].messages
  449. .map((message: any) => modelMessageContentToText(message.content))
  450. .join("\n");
  451. const parentFirstToolNames = parentRequests[0].tools.map((tool: any) => tool.name);
  452. const childRequestText = childRequests[0].messages
  453. .map((message: any) => modelMessageContentToText(message.content))
  454. .join("\n");
  455. const parentToolMessage = parentSecondRequests[0].messages.find(
  456. (message: any) => message.role === "tool",
  457. );
  458. expect(result.response).toBe("parent used explore result");
  459. expect(parentFirstRequestText).not.toContain("# agentsMd");
  460. expect(parentFirstRequestText).not.toContain("# claudeMd");
  461. expect(parentFirstRequestText).not.toContain("Project context:");
  462. expect(parentFirstRequestText).not.toContain("- Package manager: pnpm");
  463. expect(parentFirstRequestText).not.toContain("- `test`: vitest");
  464. expect(parentFirstRequestText).toContain("# currentDate");
  465. expect(parentFirstToolNames).toContain("Agent");
  466. expect(parentFirstToolNames).not.toContain("Task");
  467. expect(parentFirstToolNames).not.toContain("Glob");
  468. expect(parentFirstToolNames).not.toContain("Grep");
  469. expect(parentFirstToolNames).not.toContain("GoalRead");
  470. expect(childRequests).toHaveLength(1);
  471. expect(childRequestText).not.toContain("# agentsMd");
  472. expect(childRequestText).not.toContain("# claudeMd");
  473. expect(childRequestText).not.toContain("# user_instructions");
  474. expect(childRequestText).not.toContain("Project context:");
  475. expect(childRequestText).not.toContain("- Package manager: pnpm");
  476. expect(childRequestText).toContain("# currentDate");
  477. expect(childRequestText).toContain("Today's date is 2026-06-04.");
  478. expect(childObservations[0].model).toMatchObject({
  479. providerId: modelSelection.providerId,
  480. modelId: modelSelection.modelId,
  481. });
  482. expect(childObservations[0].factoryInput.providerOptions).toBeUndefined();
  483. expect(childRequests[0].options?.maxOutputTokens).toBe(32_000);
  484. // Explore 工具面:本地搜索/读取工具 + WebSearch client-side wrapper。
  485. // provider-visible 顺序由最终输出边界统一排序,本地工具追加在后。
  486. expect(childRequests[0].tools.map((tool: any) => tool.name)).toEqual([
  487. "Bash",
  488. "Read",
  489. "TodoWrite",
  490. "WebFetch",
  491. "WebSearch",
  492. RESPOND_TO_COORDINATOR_TOOL_NAME,
  493. ]);
  494. const childToolsByName = new Map(childRequests[0].tools.map((tool: any) => [tool.name, tool]));
  495. expect(childToolsByName.has("Glob")).toBe(false);
  496. expect(childToolsByName.has("Grep")).toBe(false);
  497. expect(childRequests[0].tools.map((tool: any) => tool.name)).not.toContain("Agent");
  498. expect(childRequests[0].tools.map((tool: any) => tool.name)).not.toContain("Task");
  499. expect(
  500. childRequests[0].messages
  501. .filter((message: any) => message.role === "system")
  502. .map((message: any) => message.content),
  503. ).toEqual(exploreSystemMessages);
  504. expect(childRequests[0].messages[1].content).not.toContain(
  505. "You help the user with software engineering work in the current workspace.",
  506. );
  507. expect(childPersistedUserMessage?.info.contextSnapshot?.envInfo?.shell).toBe("Git Bash");
  508. expect(childObservations[0].invocationContext?.traceContext?.traceId).toBe(result.traceId);
  509. if (!spawnEvent || !stoppedEvent || !toolResultEvent) {
  510. throw new Error("Expected subagent lifecycle events");
  511. }
  512. const spawnPayload = spawnEvent.payload as any;
  513. const stoppedPayload = stoppedEvent.payload as any;
  514. const toolResultPayload = toolResultEvent.payload as any;
  515. expect(spawnPayload.allowedTools).toEqual([
  516. "Bash",
  517. "Read",
  518. "WebFetch",
  519. "WebSearch",
  520. "TodoWrite",
  521. ]);
  522. expect(stoppedPayload.status).toBe("completed");
  523. expect(toolResultPayload.toolCallId).toBe("call_explore");
  524. expect(parentToolMessage.toolCallId).toBe("call_explore");
  525. expect(parentToolMessage.content).toContain(
  526. "Explore found runtime tool result injection in packages/core/src/runtime.ts.",
  527. );
  528. expect(parentToolMessage.content).toContain("agentId: agent_");
  529. expect(parentToolMessage.content).toContain("use SendMessage with to:");
  530. expect(parentToolMessage.content).toContain("<usage>subagent_tokens:");
  531. expect(parentToolMessage.content).toContain("tool_uses:");
  532. expect(parentToolMessage.content).toContain("duration_ms:");
  533. expect(parentToolMessage.content).not.toContain("totalToolUseCount");
  534. expect(childEvents.length).toBeGreaterThan(0);
  535. const initialModelSelected = childEvents.find(
  536. (event) => event.type === SessionEventType.ModelSelected,
  537. )?.payload;
  538. expect(initialModelSelected).toMatchObject({
  539. previousModelSelection: null,
  540. modelSelection: {
  541. providerId: modelSelection.providerId,
  542. modelId: modelSelection.modelId,
  543. },
  544. });
  545. expect(
  546. initialModelSelected && "modelSelection" in initialModelSelected
  547. ? initialModelSelected.modelSelection
  548. : undefined,
  549. ).not.toHaveProperty("role");
  550. expect(initialModelSelected).not.toHaveProperty("origin");
  551. expect(initialModelTimeline).toMatchObject({
  552. timelineType: "model_change",
  553. toModel: {
  554. providerId: modelSelection.providerId,
  555. modelId: modelSelection.modelId,
  556. },
  557. });
  558. expect(
  559. initialModelTimeline?.type === "timeline" ? initialModelTimeline.fromModel : "unexpected",
  560. ).toBeUndefined();
  561. expect(childPersistedAtSpawn).toEqual([true]);
  562. expect(
  563. liveEvents.filter((event) => event.sessionId === childSessionId).map((event) => event.id),
  564. ).toEqual(childEvents.map((event) => event.id));
  565. expect(new Set([...parentEvents, ...childEvents].map((event) => event.traceId))).toEqual(
  566. new Set([result.traceId]),
  567. );
  568. });
  569. it("reports child turn tool call count in the Agent result usage trailer", async () => {
  570. const sessionId = createSessionId("runtime-explore-subagent-tool-count");
  571. const eventStore = createTestSessionEventStore();
  572. const sessionStore = createRecordingSubagentSessionStore();
  573. const parentRequests: any[] = [];
  574. const childRequests: any[] = [];
  575. const childObservations: TestModelExecutionObservation[] = [];
  576. let parentCallCount = 0;
  577. let childCallCount = 0;
  578. const runtime = createTestAgentRuntime(
  579. sessionId,
  580. {
  581. mode: "build",
  582. workingDirectory: "/workspace/project",
  583. },
  584. {
  585. eventStore,
  586. sessionStore,
  587. modelFactory: createTestModelFactory({
  588. async generateText(request: any, observation) {
  589. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  590. if (toolNames.includes("Agent")) {
  591. parentRequests.push(request);
  592. parentCallCount++;
  593. if (parentCallCount === 1) {
  594. return {
  595. finishReason: "tool-calls",
  596. providerMetadata: undefined,
  597. text: "",
  598. toolCalls: [
  599. {
  600. id: "call_counted_explore",
  601. name: "Agent",
  602. input: {
  603. description: "Count child tools",
  604. prompt: "Use one todo update before returning.",
  605. subagent_type: "Explore",
  606. },
  607. },
  608. ],
  609. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  610. };
  611. }
  612. return {
  613. finishReason: "stop",
  614. providerMetadata: undefined,
  615. text: "parent saw counted child tool use",
  616. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  617. };
  618. }
  619. childRequests.push(request);
  620. childObservations.push(observation);
  621. childCallCount++;
  622. if (childCallCount === 1) {
  623. return {
  624. finishReason: "tool-calls",
  625. providerMetadata: undefined,
  626. text: "",
  627. toolCalls: [
  628. {
  629. id: "call_child_todo",
  630. name: "TodoWrite",
  631. input: {
  632. todos: [
  633. {
  634. content: "Count child tool calls",
  635. priority: "high",
  636. status: "in_progress",
  637. },
  638. ],
  639. },
  640. },
  641. ],
  642. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  643. };
  644. }
  645. return {
  646. finishReason: "stop",
  647. providerMetadata: undefined,
  648. text: "Child completed after one TodoWrite.",
  649. usage: { inputTokens: 3, outputTokens: 4, totalTokens: 7 },
  650. };
  651. },
  652. } as never),
  653. },
  654. );
  655. const result = await runtime.executeTurn("Use an explore agent and report its usage");
  656. const parentEvents = await eventStore.getEvents(sessionId);
  657. const stoppedEvent = parentEvents.find(
  658. (event) => event.type === SessionEventType.SubagentStopped,
  659. );
  660. const parentToolMessage = parentRequests[1].messages.find(
  661. (message: any) => message.role === "tool",
  662. );
  663. expect(result.response).toBe("parent saw counted child tool use");
  664. expect(childRequests).toHaveLength(2);
  665. expect((stoppedEvent?.payload as any)?.totalToolUseCount).toBe(1);
  666. expect(parentToolMessage.content).toContain("Child completed after one TodoWrite.");
  667. expect(parentToolMessage.content).toContain("tool_uses: 1");
  668. expect(parentToolMessage.content).not.toContain("tool_uses: 0");
  669. });
  670. it("normalizes lowercase built-in Explore subagent_type before launching", async () => {
  671. const sessionId = createSessionId("runtime-lowercase-explore-subagent");
  672. const eventStore = createTestSessionEventStore();
  673. const childRequests: any[] = [];
  674. let parentCallCount = 0;
  675. const runtime = createTestAgentRuntime(
  676. sessionId,
  677. {
  678. mode: "build",
  679. workingDirectory: "/workspace/project",
  680. },
  681. {
  682. eventStore,
  683. modelFactory: createTestModelFactory({
  684. async generateText(request: any) {
  685. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  686. if (toolNames.includes("Agent")) {
  687. parentCallCount++;
  688. if (parentCallCount === 1) {
  689. return {
  690. finishReason: "tool-calls",
  691. providerMetadata: undefined,
  692. text: "",
  693. toolCalls: [
  694. {
  695. id: "call_lowercase_explore",
  696. name: "Agent",
  697. input: {
  698. description: "Find runtime loop",
  699. prompt: "Find where runtime loop is implemented.",
  700. subagent_type: "explore",
  701. },
  702. },
  703. ],
  704. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  705. };
  706. }
  707. const toolResultText = request.messages
  708. .filter((message: any) => message.role === "tool")
  709. .map((message: any) => modelMessageContentToText(message.content))
  710. .join("\n");
  711. expect(toolResultText).not.toContain("Unknown subagent type");
  712. return {
  713. finishReason: "stop",
  714. providerMetadata: undefined,
  715. text: "parent used normalized explore result",
  716. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  717. };
  718. }
  719. childRequests.push(request);
  720. return {
  721. finishReason: "stop",
  722. providerMetadata: undefined,
  723. text: "lowercase explore resolved to the built-in Explore agent.",
  724. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  725. };
  726. },
  727. } as never),
  728. },
  729. );
  730. const result = await runtime.executeTurn("Use explore to inspect the runtime");
  731. expect(result.response).toBe("parent used normalized explore result");
  732. expect(childRequests).toHaveLength(1);
  733. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  734. expect(childToolNames).toContain("Read");
  735. expect(childToolNames).toContain("Bash");
  736. expect(childToolNames).toContain("TodoWrite");
  737. expect(childToolNames).not.toContain("Agent");
  738. expect(childToolNames).not.toContain("Write");
  739. });
  740. it("reports ambiguous normalized subagent_type from the launch path", async () => {
  741. const sessionId = createSessionId("runtime-ambiguous-normalized-subagent");
  742. const eventStore = createTestSessionEventStore();
  743. const runtime = createTestAgentRuntime(
  744. sessionId,
  745. {
  746. mode: "build",
  747. workingDirectory: "/workspace/project",
  748. subagents: {
  749. profiles: [
  750. {
  751. name: "foo-bar",
  752. description: "First normalized collision.",
  753. source: "project",
  754. systemPrompt: "first",
  755. tools: ["Read"],
  756. },
  757. {
  758. name: "foo_bar",
  759. description: "Second normalized collision.",
  760. source: "project",
  761. systemPrompt: "second",
  762. tools: ["Read"],
  763. background: true,
  764. },
  765. ],
  766. },
  767. },
  768. {
  769. eventStore,
  770. modelFactory: createTestModelFactory({
  771. async generateText(request: any) {
  772. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  773. if (!toolNames.includes("Agent")) {
  774. throw new Error("Ambiguous subagent_type must not launch a child agent");
  775. }
  776. const toolResultText = request.messages
  777. .filter((message: any) => message.role === "tool")
  778. .map((message: any) => modelMessageContentToText(message.content))
  779. .join("\n");
  780. if (toolResultText) {
  781. expect(toolResultText).toContain("Agent type 'foo bar' is ambiguous");
  782. expect(toolResultText).toContain("foo-bar");
  783. expect(toolResultText).toContain("foo_bar");
  784. return {
  785. finishReason: "stop",
  786. providerMetadata: undefined,
  787. text: "parent saw ambiguous agent type",
  788. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  789. };
  790. }
  791. return {
  792. finishReason: "tool-calls",
  793. providerMetadata: undefined,
  794. text: "",
  795. toolCalls: [
  796. {
  797. id: "call_ambiguous_agent",
  798. name: "Agent",
  799. input: {
  800. description: "Resolve ambiguous agent",
  801. prompt: "Try the ambiguous agent.",
  802. subagent_type: "foo bar",
  803. },
  804. },
  805. ],
  806. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  807. };
  808. },
  809. } as never),
  810. },
  811. );
  812. const result = await runtime.executeTurn("Use the ambiguous custom agent");
  813. expect(result.response).toBe("parent saw ambiguous agent type");
  814. });
  815. it("normalizes subagent_type without stripping arbitrary punctuation", async () => {
  816. const sessionId = createSessionId("runtime-punctuation-subagent");
  817. const eventStore = createTestSessionEventStore();
  818. const runtime = createTestAgentRuntime(
  819. sessionId,
  820. {
  821. mode: "build",
  822. workingDirectory: "/workspace/project",
  823. subagents: {
  824. profiles: [
  825. {
  826. name: "report-v2",
  827. description: "Report agent.",
  828. source: "project",
  829. systemPrompt: "report",
  830. tools: ["Read"],
  831. },
  832. ],
  833. },
  834. },
  835. {
  836. eventStore,
  837. modelFactory: createTestModelFactory({
  838. async generateText(request: any) {
  839. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  840. if (!toolNames.includes("Agent")) {
  841. throw new Error("Punctuation mismatch must not launch a child agent");
  842. }
  843. const toolResultText = request.messages
  844. .filter((message: any) => message.role === "tool")
  845. .map((message: any) => modelMessageContentToText(message.content))
  846. .join("\n");
  847. if (toolResultText) {
  848. expect(toolResultText).toContain("Agent type 'report.v2' not found");
  849. expect(toolResultText).toContain("report-v2");
  850. return {
  851. finishReason: "stop",
  852. providerMetadata: undefined,
  853. text: "parent saw unknown agent type",
  854. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  855. };
  856. }
  857. return {
  858. finishReason: "tool-calls",
  859. providerMetadata: undefined,
  860. text: "",
  861. toolCalls: [
  862. {
  863. id: "call_punctuation_agent",
  864. name: "Agent",
  865. input: {
  866. description: "Resolve punctuation agent",
  867. prompt: "Try the punctuation agent.",
  868. subagent_type: "report.v2",
  869. },
  870. },
  871. ],
  872. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  873. };
  874. },
  875. } as never),
  876. },
  877. );
  878. const result = await runtime.executeTurn("Use the report.v2 custom agent");
  879. expect(result.response).toBe("parent saw unknown agent type");
  880. });
  881. // docs/dynamic-workflow/launch.md「Gray release」:父会话关着灰度时,Agent 工具不能成为
  882. // 绕过它的后门;父会话开着(或根本不参与灰度)时子代理照旧拿得到。
  883. //
  884. // 这里刻意用**显式声明 tools 的自定义 agent profile**:默认 agent 的子工具面是「父
  885. // registry 里现存工具名」的交集,父会话已经被剃过,子代理自然也没有——那条路径挡得住,
  886. // 但挡住它的不是灰度门。profile 显式写 `tools: [...]` 时 resolveSubagentToolAllowlist
  887. // 走的是另一条分支(request.allowedTools 原样保留,只过 disallow 规则),父 registry
  888. // 不再参与。唯一能挡住它的就是子 runtime 自己继承到的 dynamicWorkflowEnabled。
  889. describe("dynamic-workflow gray gate inheritance into subagent children", () => {
  890. async function childToolNamesForParent(
  891. parentConfig: Record<string, unknown>,
  892. options: { activateParentFirst?: boolean } = {},
  893. ): Promise<{ child: string[]; parent: string[] }> {
  894. const sessionId = createSessionId(
  895. [
  896. "runtime-gray-gate-subagent",
  897. String(parentConfig.dynamicWorkflowEnabled),
  898. String(parentConfig.dynamicWorkflowToolsOnDemand),
  899. String(options.activateParentFirst),
  900. ].join("-"),
  901. );
  902. const childRequests: any[] = [];
  903. let parentCallCount = 0;
  904. const runtime = createTestAgentRuntime(
  905. sessionId,
  906. {
  907. mode: "build",
  908. ...parentConfig,
  909. modelSelection: createTestModelSelection({
  910. providerId: createModelProviderId("provider-main"),
  911. modelId: createModelId("main-model"),
  912. }),
  913. workingDirectory: "/workspace/project",
  914. subagents: {
  915. profiles: [
  916. {
  917. name: "workflow-author",
  918. description: "显式点名工作流工具的自定义 agent。",
  919. source: "project",
  920. systemPrompt: "You author workflows.",
  921. tools: ["Read", "CreateWorkflow", "ResumeWorkflowRun"],
  922. model: "main",
  923. maxTurns: 2,
  924. },
  925. ],
  926. },
  927. },
  928. {
  929. eventStore: createTestSessionEventStore(),
  930. modelFactory: createTestModelFactory({
  931. async generateText(request: any) {
  932. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  933. if (toolNames.includes("Agent")) {
  934. parentCallCount++;
  935. if (parentCallCount === 1) {
  936. return {
  937. finishReason: "tool-calls",
  938. providerMetadata: undefined,
  939. text: "",
  940. toolCalls: [
  941. {
  942. id: "call_gray_gate_agent",
  943. name: "Agent",
  944. input: {
  945. description: "Author a workflow",
  946. prompt: "Try to author a workflow.",
  947. subagent_type: "workflow-author",
  948. },
  949. },
  950. ],
  951. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  952. };
  953. }
  954. return {
  955. finishReason: "stop",
  956. providerMetadata: undefined,
  957. text: "parent done",
  958. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  959. };
  960. }
  961. childRequests.push(request);
  962. return {
  963. finishReason: "stop",
  964. providerMetadata: undefined,
  965. text: "child done.",
  966. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  967. };
  968. },
  969. } as never),
  970. },
  971. );
  972. if (options.activateParentFirst) {
  973. await runtime.activateDynamicWorkflowTools({ source: "command" });
  974. }
  975. await runtime.executeTurn("Use the workflow-author agent");
  976. return {
  977. child: childRequests[0].tools.map((tool: any) => tool.name),
  978. parent: runtime.getTools().map((tool) => tool.name),
  979. };
  980. }
  981. it.each([
  982. { parentConfig: { dynamicWorkflowEnabled: false }, available: false },
  983. { parentConfig: { dynamicWorkflowEnabled: true }, available: true },
  984. // 不参与灰度的父会话(TUI / headless `-p`,DWG-04):子代理必须保留全部工具。
  985. { parentConfig: {}, available: true },
  986. // DWG-12:onDemand 父会话未激活时子代理没有工作流工具;父已激活则子出生即有
  987. // (launch.md「On demand: activation」Children 段)。
  988. {
  989. parentConfig: { dynamicWorkflowEnabled: true, dynamicWorkflowToolsOnDemand: true },
  990. available: false,
  991. },
  992. {
  993. parentConfig: { dynamicWorkflowEnabled: true, dynamicWorkflowToolsOnDemand: true },
  994. activateParentFirst: true,
  995. available: true,
  996. },
  997. ])("parent %j", async ({ parentConfig, available, activateParentFirst }) => {
  998. const { child, parent } = await childToolNamesForParent(parentConfig, {
  999. activateParentFirst,
  1000. });
  1001. for (const name of ["CreateWorkflow", "ResumeWorkflowRun"]) {
  1002. expect({ name, inParent: parent.includes(name) }).toEqual({ name, inParent: available });
  1003. expect({ name, inChild: child.includes(name) }).toEqual({ name, inChild: available });
  1004. }
  1005. // 反向断言:profile 里其余工具在三种取值下都照常给到,门只碰工作流那几件。
  1006. expect(child).toContain("Read");
  1007. });
  1008. });
  1009. it("routes Explore provider runtime headers refreshes through the parent session", async () => {
  1010. const sessionId = createSessionId("runtime-explore-provider-headers-parent-route");
  1011. const eventStore = createTestSessionEventStore();
  1012. // 主 runtime 每次调用报自己的 sessionId;子 runtime 拿到的是父 runtime 派生的实例
  1013. // (helpers/child-client-ports.ts),派生层把 sessionId 改写成父会话。
  1014. const refreshes: Array<{ providerId: string; boundSessionId: string; routedSessionId?: string }> =
  1015. [];
  1016. const childRequests: any[] = [];
  1017. let parentCallCount = 0;
  1018. const modelSelection = {
  1019. providerId: createModelProviderId("provider-start-plan"),
  1020. modelId: createModelId("start-plan-model"),
  1021. };
  1022. const runtime = createTestAgentRuntime(
  1023. sessionId,
  1024. {
  1025. mode: "build",
  1026. modelSelection: createTestModelSelection(modelSelection),
  1027. workingDirectory: "/workspace/project",
  1028. },
  1029. {
  1030. eventStore,
  1031. providerRuntimeHeadersPort: {
  1032. shouldRefreshBeforeModelRequest: () => true,
  1033. async refreshBeforeModelRequest(input) {
  1034. refreshes.push({
  1035. providerId: input.providerId,
  1036. boundSessionId: sessionId,
  1037. // 回归守卫:子 runtime 的刷新到这里必须已经是父会话的 sessionId。若派生层漏掉
  1038. // 改写,子 runtime 会把子会话发给客户端(2026-09-09 挂死事故)。
  1039. routedSessionId: input.sessionId,
  1040. });
  1041. return {
  1042. headersApplied: true,
  1043. };
  1044. },
  1045. },
  1046. modelFactory: createTestModelFactory({
  1047. async generateText(request: any, observation) {
  1048. await observation.invocationContext?.refreshRuntimeHeadersBeforeAttempt?.({
  1049. attempt: 1,
  1050. abortSignal: request.abortSignal,
  1051. });
  1052. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1053. if (toolNames.includes("Agent")) {
  1054. parentCallCount++;
  1055. if (parentCallCount === 1) {
  1056. return {
  1057. finishReason: "tool-calls",
  1058. providerMetadata: undefined,
  1059. text: "",
  1060. toolCalls: [
  1061. {
  1062. id: "call_explore_headers",
  1063. name: "Agent",
  1064. input: {
  1065. description: "Check provider headers",
  1066. prompt: "Check the provider headers route.",
  1067. subagent_type: "Explore",
  1068. },
  1069. },
  1070. ],
  1071. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1072. };
  1073. }
  1074. return {
  1075. finishReason: "stop",
  1076. providerMetadata: undefined,
  1077. text: "parent completed after explore",
  1078. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1079. };
  1080. }
  1081. childRequests.push(request);
  1082. return {
  1083. finishReason: "stop",
  1084. providerMetadata: undefined,
  1085. text: "Explore checked the provider headers route.",
  1086. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1087. };
  1088. },
  1089. } as never),
  1090. },
  1091. );
  1092. await runtime.executeTurn("Use an explore agent to check headers");
  1093. const parentEvents = await eventStore.getEvents(sessionId);
  1094. const spawnEvent = parentEvents.find(
  1095. (event) => event.type === SessionEventType.SubagentSpawned,
  1096. );
  1097. if (!spawnEvent) {
  1098. throw new Error("Expected subagent spawn event");
  1099. }
  1100. const childSessionId = (spawnEvent.payload as any).childSessionId;
  1101. const childEvents = await eventStore.getEvents(childSessionId);
  1102. expect(childRequests).toHaveLength(1);
  1103. expect(childSessionId).not.toBe(sessionId);
  1104. expect(childEvents.length).toBeGreaterThan(0);
  1105. // 三次刷新(父两次 + 子一次)全部以父会话为路由身份到达端口。
  1106. expect(refreshes).toEqual([
  1107. { providerId: "provider-start-plan", boundSessionId: sessionId, routedSessionId: sessionId },
  1108. { providerId: "provider-start-plan", boundSessionId: sessionId, routedSessionId: sessionId },
  1109. { providerId: "provider-start-plan", boundSessionId: sessionId, routedSessionId: sessionId },
  1110. ]);
  1111. });
  1112. it("passes the parent HTTP client port into Explore WebFetch calls", async () => {
  1113. const sessionId = createSessionId("runtime-explore-webfetch-http-client");
  1114. const eventStore = createTestSessionEventStore();
  1115. const parentRequests: any[] = [];
  1116. const childRequests: any[] = [];
  1117. const childObservations: TestModelExecutionObservation[] = [];
  1118. const webFetchProcessingRequests: any[] = [];
  1119. let parentCallCount = 0;
  1120. let childCallCount = 0;
  1121. const body = new TextEncoder().encode(
  1122. "<html><body><h1>Explore WebFetch</h1><p>http client port is wired.</p></body></html>",
  1123. );
  1124. const httpClientPort: HttpClientPort = {
  1125. request: vi.fn<HttpClientPort["request"]>(async (request) => {
  1126. expect(request.url).toBe("https://example.com/explore-webfetch-port");
  1127. return {
  1128. body,
  1129. bytes: body.byteLength,
  1130. durationMs: 7,
  1131. headers: { "content-type": "text/html; charset=utf-8" },
  1132. status: 200,
  1133. statusText: "OK",
  1134. url: "https://example.com/explore-webfetch-port",
  1135. };
  1136. }),
  1137. };
  1138. const runtime = createTestAgentRuntime(
  1139. sessionId,
  1140. {
  1141. mode: "build",
  1142. workingDirectory: "/workspace/project",
  1143. },
  1144. {
  1145. eventStore,
  1146. httpClientPort,
  1147. modelFactory: createTestModelFactory({
  1148. async generateText(request: any, observation) {
  1149. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1150. if (toolNames.includes("Agent")) {
  1151. parentRequests.push(request);
  1152. parentCallCount++;
  1153. if (parentCallCount === 1) {
  1154. return {
  1155. finishReason: "tool-calls",
  1156. providerMetadata: undefined,
  1157. text: "",
  1158. toolCalls: [
  1159. {
  1160. id: "call_explore_webfetch",
  1161. name: "Agent",
  1162. input: {
  1163. description: "Fetch a public page",
  1164. prompt: "Use WebFetch to inspect the page.",
  1165. subagent_type: "Explore",
  1166. },
  1167. },
  1168. ],
  1169. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1170. };
  1171. }
  1172. return {
  1173. finishReason: "stop",
  1174. providerMetadata: undefined,
  1175. text: "parent saw Explore WebFetch result",
  1176. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1177. };
  1178. }
  1179. if (toolNames.includes("WebFetch")) {
  1180. childRequests.push(request);
  1181. childCallCount++;
  1182. if (childCallCount === 1) {
  1183. return {
  1184. finishReason: "tool-calls",
  1185. providerMetadata: undefined,
  1186. text: "",
  1187. toolCalls: [
  1188. {
  1189. id: "call_child_webfetch",
  1190. name: "WebFetch",
  1191. input: {
  1192. prompt: "What confirms the HTTP client port wiring?",
  1193. url: "https://example.com/explore-webfetch-port",
  1194. },
  1195. },
  1196. ],
  1197. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1198. };
  1199. }
  1200. return {
  1201. finishReason: "stop",
  1202. providerMetadata: undefined,
  1203. text: "Explore fetched the page through the injected HTTP client.",
  1204. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1205. };
  1206. }
  1207. webFetchProcessingRequests.push(request);
  1208. return {
  1209. finishReason: "stop",
  1210. providerMetadata: undefined,
  1211. text: "The page confirms the HTTP client port is wired.",
  1212. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1213. };
  1214. },
  1215. } as never),
  1216. },
  1217. );
  1218. const result = await runtime.executeTurn("Use an explore agent to fetch a URL");
  1219. expect(result.response).toBe("parent saw Explore WebFetch result");
  1220. expect(parentRequests).toHaveLength(2);
  1221. expect(childRequests).toHaveLength(2);
  1222. expect(httpClientPort.request).toHaveBeenCalledTimes(1);
  1223. expect(webFetchProcessingRequests).toHaveLength(1);
  1224. expect(
  1225. webFetchProcessingRequests[0].messages
  1226. .map((message: any) => modelMessageContentToText(message.content))
  1227. .join("\n"),
  1228. ).toContain("http client port is wired");
  1229. });
  1230. it("runs a custom profile-backed subagent with its prompt and tool allowlist", async () => {
  1231. const sessionId = createSessionId("runtime-custom-subagent-profile");
  1232. const eventStore = createTestSessionEventStore();
  1233. const parentRequests: any[] = [];
  1234. const childRequests: any[] = [];
  1235. const runtime = createTestAgentRuntime(
  1236. sessionId,
  1237. {
  1238. mode: "build",
  1239. workingDirectory: "/workspace/project",
  1240. subagents: {
  1241. profiles: [
  1242. {
  1243. name: "zcode-reviewer",
  1244. description: "用中文检查实现边界和风险。",
  1245. source: "project",
  1246. systemPrompt: "你是 zcode-reviewer,只输出中文结论。",
  1247. tools: ["Read"],
  1248. disallowedTools: ["Bash"],
  1249. model: "main",
  1250. maxTurns: 2,
  1251. },
  1252. ],
  1253. },
  1254. },
  1255. {
  1256. eventStore,
  1257. modelFactory: createTestModelFactory({
  1258. async generateText(request: any) {
  1259. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1260. if (toolNames.includes("Agent")) {
  1261. parentRequests.push(request);
  1262. if (parentRequests.length === 1) {
  1263. return {
  1264. finishReason: "tool-calls",
  1265. providerMetadata: undefined,
  1266. text: "",
  1267. toolCalls: [
  1268. {
  1269. id: "call_custom_agent",
  1270. name: "Agent",
  1271. input: {
  1272. description: "检查实现边界",
  1273. prompt: "检查 subagent 与 main agent 的边界。",
  1274. subagent_type: "ZCode Reviewer",
  1275. },
  1276. },
  1277. ],
  1278. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1279. };
  1280. }
  1281. return {
  1282. finishReason: "stop",
  1283. providerMetadata: undefined,
  1284. text: "父 agent 采纳了自定义 agent 的结论。",
  1285. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1286. };
  1287. }
  1288. childRequests.push(request);
  1289. childObservations.push(observation);
  1290. return {
  1291. finishReason: "stop",
  1292. providerMetadata: undefined,
  1293. text: "自定义 agent 已按中文 system prompt 完成边界检查。",
  1294. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  1295. };
  1296. },
  1297. } as never),
  1298. },
  1299. );
  1300. const result = await runtime.executeTurn("让自定义 agent 检查边界");
  1301. const parentFirstRequestText = parentRequests[0].messages
  1302. .map((message: any) => modelMessageContentToText(message.content))
  1303. .join("\n");
  1304. const childRequestText = childRequests[0].messages
  1305. .map((message: any) => modelMessageContentToText(message.content))
  1306. .join("\n");
  1307. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  1308. const parentAgentToolDescription =
  1309. parentRequests[0].tools.find((tool: any) => tool.name === "Agent")?.description ?? "";
  1310. expect(result.response).toBe("父 agent 采纳了自定义 agent 的结论。");
  1311. expect(parentFirstRequestText).toContain("Available agent types for the Agent tool:");
  1312. expect(parentFirstRequestText).toContain("zcode-reviewer");
  1313. expect(parentAgentToolDescription).toContain(
  1314. "Available agent types are listed in <system-reminder> messages in the conversation.",
  1315. );
  1316. expect(parentFirstRequestText).toContain(
  1317. "- zcode-reviewer: 用中文检查实现边界和风险。 (Tools: Read)",
  1318. );
  1319. expect(childRequestText).toContain("你是 zcode-reviewer,只输出中文结论。");
  1320. expect(childRequestText).not.toContain("READ-ONLY MODE");
  1321. expect(childToolNames).toContain("Read");
  1322. expect(childToolNames).not.toContain("Bash");
  1323. expect(childToolNames).not.toContain("Edit");
  1324. expect(childToolNames).not.toContain("Agent");
  1325. expect(childToolNames).not.toContain("Task");
  1326. });
  1327. it("runs a custom Explore with its own prompt, main tools, MCP descriptor, and parent permissions", async () => {
  1328. const sessionId = createSessionId("runtime-custom-explore-profile");
  1329. const eventStore = createTestSessionEventStore();
  1330. const parentRequests: any[] = [];
  1331. const childRequests: any[] = [];
  1332. const descriptor = {
  1333. serverName: "search__server",
  1334. toolName: "lookup__item",
  1335. description: "Look up an indexed item.",
  1336. inputSchema: { type: "object", properties: {} },
  1337. };
  1338. const mcpToolName = toMcpToolName(descriptor);
  1339. const connectedStatus = {
  1340. status: "connected" as const,
  1341. toolCount: 1,
  1342. transport: "stdio" as const,
  1343. updatedAt: new Date(0).toISOString(),
  1344. };
  1345. const callTool = vi.fn(async () => ({ content: [{ text: "found", type: "text" as const }] }));
  1346. const mcpPort = createMockMcpPort({
  1347. callTool,
  1348. async connectConfiguredServers() {
  1349. return {
  1350. statuses: { search__server: connectedStatus },
  1351. tools: [descriptor],
  1352. };
  1353. },
  1354. });
  1355. const parentPermissionService = new PermissionService({
  1356. allowedTools: new Set([mcpToolName]),
  1357. disallowedTools: new Set(),
  1358. autoApproveHighRisk: false,
  1359. allowMediumRiskInAutoMode: false,
  1360. });
  1361. const checkPermission = vi.spyOn(parentPermissionService, "checkPermission");
  1362. const runtime = createTestAgentRuntime(
  1363. sessionId,
  1364. {
  1365. mcp: {
  1366. enabled: true,
  1367. servers: {
  1368. search__server: { command: "search-mcp", type: "stdio" },
  1369. },
  1370. },
  1371. mode: "build",
  1372. workingDirectory: "/workspace/project",
  1373. subagents: {
  1374. profiles: [
  1375. {
  1376. name: "Explore",
  1377. description: "自定义可写 Explore。",
  1378. source: "project",
  1379. systemPrompt: "你是项目自定义 Explore,可以执行写入和 MCP 查询。",
  1380. tools: ["Write", mcpToolName],
  1381. disallowedTools: ["Bash"],
  1382. mcpServers: ["search__server"],
  1383. model: "main",
  1384. maxTurns: 2,
  1385. },
  1386. ],
  1387. },
  1388. },
  1389. {
  1390. eventStore,
  1391. mcpPort,
  1392. permissionService: parentPermissionService,
  1393. modelFactory: createTestModelFactory({
  1394. async generateText(request: any) {
  1395. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1396. if (toolNames.includes("Agent")) {
  1397. parentRequests.push(request);
  1398. if (parentRequests.length === 1) {
  1399. return {
  1400. finishReason: "tool-calls",
  1401. providerMetadata: undefined,
  1402. text: "",
  1403. toolCalls: [
  1404. {
  1405. id: "call_custom_agent",
  1406. name: "Agent",
  1407. input: {
  1408. description: "检查实现边界",
  1409. prompt: "检查 subagent 与 main agent 的边界。",
  1410. subagent_type: "Explore",
  1411. },
  1412. },
  1413. ],
  1414. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1415. };
  1416. }
  1417. return {
  1418. finishReason: "stop",
  1419. providerMetadata: undefined,
  1420. text: "父 agent 采纳了自定义 agent 的结论。",
  1421. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1422. };
  1423. }
  1424. childRequests.push(request);
  1425. if (childRequests.length === 1) {
  1426. return {
  1427. finishReason: "tool-calls",
  1428. providerMetadata: undefined,
  1429. text: "",
  1430. toolCalls: [
  1431. {
  1432. id: "call_custom_explore_mcp",
  1433. name: mcpToolName,
  1434. input: {},
  1435. },
  1436. ],
  1437. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1438. };
  1439. }
  1440. return {
  1441. finishReason: "stop",
  1442. providerMetadata: undefined,
  1443. text: "自定义 Explore 已完成边界检查。",
  1444. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  1445. };
  1446. },
  1447. } as never),
  1448. },
  1449. );
  1450. const result = await runtime.executeTurn("让自定义 agent 检查边界");
  1451. const parentFirstRequestText = parentRequests[0].messages
  1452. .map((message: any) => modelMessageContentToText(message.content))
  1453. .join("\n");
  1454. const childRequestText = childRequests[0].messages
  1455. .map((message: any) => modelMessageContentToText(message.content))
  1456. .join("\n");
  1457. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  1458. const parentAgentToolDescription =
  1459. parentRequests[0].tools.find((tool: any) => tool.name === "Agent")?.description ?? "";
  1460. expect(result.response).toBe("父 agent 采纳了自定义 agent 的结论。");
  1461. expect(parentFirstRequestText).toContain("Available agent types for the Agent tool:");
  1462. expect(parentFirstRequestText).toContain("自定义可写 Explore");
  1463. expect(parentAgentToolDescription).toContain(
  1464. "Available agent types are listed in <system-reminder> messages in the conversation.",
  1465. );
  1466. expect(parentFirstRequestText).toContain(
  1467. `- Explore: 自定义可写 Explore。 (Tools: Write, ${mcpToolName})`,
  1468. );
  1469. expect(childRequestText).toContain("你是项目自定义 Explore,可以执行写入和 MCP 查询。");
  1470. expect(childRequestText).not.toContain("READ-ONLY MODE");
  1471. expect(childToolNames).toContain("Write");
  1472. expect(childToolNames).toContain(mcpToolName);
  1473. expect(childToolNames).not.toContain("Bash");
  1474. expect(childToolNames).not.toContain("Agent");
  1475. expect(childToolNames).not.toContain("Task");
  1476. expect(callTool).toHaveBeenCalledTimes(1);
  1477. expect(
  1478. checkPermission.mock.calls.some(
  1479. ([context]) => context.toolName === mcpToolName && context.mode === "build",
  1480. ),
  1481. ).toBe(true);
  1482. });
  1483. it.each([
  1484. { label: "omitted", mcpServers: undefined },
  1485. { label: "empty", mcpServers: [] as readonly string[] },
  1486. ])(
  1487. "keeps an empty-prompt custom Explore unrestricted when mcpServers is $label",
  1488. async ({ label, mcpServers }) => {
  1489. const sessionId = createSessionId(`runtime-custom-explore-unrestricted-${label}`);
  1490. const eventStore = createTestSessionEventStore();
  1491. const parentRequests: any[] = [];
  1492. const childRequests: any[] = [];
  1493. const descriptor = {
  1494. serverName: "plugin:android-emulator:android-emulator",
  1495. toolName: "android_preflight",
  1496. description: "Check Android emulator prerequisites.",
  1497. inputSchema: { type: "object", properties: {} },
  1498. };
  1499. const mcpToolName = toMcpToolName(descriptor);
  1500. const connectedStatus = {
  1501. status: "connected" as const,
  1502. toolCount: 1,
  1503. transport: "stdio" as const,
  1504. updatedAt: new Date(0).toISOString(),
  1505. };
  1506. const connectConfiguredServers = vi.fn(async () => ({
  1507. statuses: {
  1508. "plugin:android-emulator:android-emulator": connectedStatus,
  1509. },
  1510. tools: [descriptor],
  1511. }));
  1512. const listTools = vi.fn(async () => []);
  1513. const status = vi.fn(async () => ({}));
  1514. const mcpPort = createMockMcpPort({ connectConfiguredServers, listTools, status });
  1515. const runtime = createTestAgentRuntime(
  1516. sessionId,
  1517. {
  1518. mcp: {
  1519. enabled: true,
  1520. servers: {
  1521. "plugin:android-emulator:android-emulator": {
  1522. command: "android-emulator-mcp",
  1523. type: "stdio",
  1524. },
  1525. },
  1526. },
  1527. mode: "build",
  1528. workingDirectory: "/workspace/project",
  1529. subagents: {
  1530. profiles: [
  1531. {
  1532. name: "Explore",
  1533. description: "Custom Explore using the unrestricted parent MCP snapshot.",
  1534. source: "user",
  1535. systemPrompt: "",
  1536. tools: ["*"],
  1537. ...(mcpServers === undefined ? {} : { mcpServers }),
  1538. },
  1539. ],
  1540. },
  1541. },
  1542. {
  1543. eventStore,
  1544. mcpPort,
  1545. modelFactory: createTestModelFactory({
  1546. async generateText(request: any) {
  1547. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1548. if (toolNames.includes("Agent")) {
  1549. parentRequests.push(request);
  1550. if (parentRequests.length === 1) {
  1551. return {
  1552. finishReason: "tool-calls",
  1553. providerMetadata: undefined,
  1554. text: "",
  1555. toolCalls: [
  1556. {
  1557. id: `call_custom_explore_unrestricted_${label}`,
  1558. name: "Agent",
  1559. input: {
  1560. description: "Test unrestricted MCP snapshot",
  1561. prompt: "Confirm the custom Explore can use the parent MCP snapshot.",
  1562. subagent_type: "Explore",
  1563. },
  1564. },
  1565. ],
  1566. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1567. };
  1568. }
  1569. return {
  1570. finishReason: "stop",
  1571. providerMetadata: undefined,
  1572. text: "parent received the custom Explore result",
  1573. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1574. };
  1575. }
  1576. childRequests.push(request);
  1577. return {
  1578. finishReason: "stop",
  1579. providerMetadata: undefined,
  1580. text: "custom Explore received the unrestricted MCP descriptor",
  1581. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1582. };
  1583. },
  1584. } as never),
  1585. },
  1586. );
  1587. const result = await runtime.executeTurn("Use the custom Explore agent");
  1588. const childRequestText = childRequests[0].messages
  1589. .map((message: any) => modelMessageContentToText(message.content))
  1590. .join("\n");
  1591. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  1592. expect(result.response).toBe("parent received the custom Explore result");
  1593. expect(childRequests).toHaveLength(1);
  1594. expect(childRequestText).not.toContain("READ-ONLY MODE");
  1595. expect(childToolNames).toContain(mcpToolName);
  1596. expect(connectConfiguredServers).toHaveBeenCalledTimes(1);
  1597. expect(status).not.toHaveBeenCalled();
  1598. expect(listTools).not.toHaveBeenCalled();
  1599. },
  1600. );
  1601. it("removes plan-mode tools from custom wildcard subagents", async () => {
  1602. const sessionId = createSessionId("runtime-custom-subagent-no-plan-mode-tools");
  1603. const eventStore = createTestSessionEventStore();
  1604. const parentRequests: any[] = [];
  1605. const childRequests: any[] = [];
  1606. const runtime = createTestAgentRuntime(
  1607. sessionId,
  1608. {
  1609. mode: "build",
  1610. workingDirectory: "/workspace/project",
  1611. subagents: {
  1612. profiles: [
  1613. {
  1614. name: "wildcard-reviewer",
  1615. description: "Use every safe inherited tool.",
  1616. source: "project",
  1617. systemPrompt: "Review with inherited tools, but do not enter planning mode.",
  1618. tools: ["*"],
  1619. },
  1620. ],
  1621. },
  1622. },
  1623. {
  1624. eventStore,
  1625. modelFactory: createTestModelFactory({
  1626. async generateText(request: any) {
  1627. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1628. if (toolNames.includes("Agent")) {
  1629. parentRequests.push(request);
  1630. if (parentRequests.length === 1) {
  1631. return {
  1632. finishReason: "tool-calls",
  1633. providerMetadata: undefined,
  1634. text: "",
  1635. toolCalls: [
  1636. {
  1637. id: "call_wildcard_agent",
  1638. name: "Agent",
  1639. input: {
  1640. description: "检查 wildcard custom agent",
  1641. prompt: "检查 custom wildcard 子 agent 工具面。",
  1642. subagent_type: "wildcard-reviewer",
  1643. },
  1644. },
  1645. ],
  1646. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1647. };
  1648. }
  1649. return {
  1650. finishReason: "stop",
  1651. providerMetadata: undefined,
  1652. text: "父 agent 收到 wildcard 结果。",
  1653. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1654. };
  1655. }
  1656. childRequests.push(request);
  1657. return {
  1658. finishReason: "stop",
  1659. providerMetadata: undefined,
  1660. text: "wildcard child done",
  1661. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1662. };
  1663. },
  1664. } as never),
  1665. },
  1666. );
  1667. const result = await runtime.executeTurn("让 wildcard-reviewer 跑一下");
  1668. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  1669. expect(result.response).toBe("父 agent 收到 wildcard 结果。");
  1670. expect(childToolNames).toContain("Read");
  1671. expect(childToolNames).toContain("Bash");
  1672. expect(childToolNames).not.toContain("EnterPlanMode");
  1673. expect(childToolNames).not.toContain("ExitPlanMode");
  1674. expect(childToolNames).not.toContain("Agent");
  1675. expect(childToolNames).not.toContain("Task");
  1676. });
  1677. it("removes plan-mode tools from explicit custom subagent tool lists", async () => {
  1678. const sessionId = createSessionId("runtime-explicit-custom-subagent-no-plan-tools");
  1679. const eventStore = createTestSessionEventStore();
  1680. const parentRequests: any[] = [];
  1681. const childRequests: any[] = [];
  1682. const runtime = createTestAgentRuntime(
  1683. sessionId,
  1684. {
  1685. mode: "build",
  1686. workingDirectory: "/workspace/project",
  1687. subagents: {
  1688. profiles: [
  1689. {
  1690. name: "explicit-reviewer",
  1691. description: "Asks for an explicit tool subset.",
  1692. source: "project",
  1693. systemPrompt: "Review with explicitly declared tools.",
  1694. tools: ["Read", "EnterPlanMode", "ExitPlanMode"],
  1695. },
  1696. ],
  1697. },
  1698. },
  1699. {
  1700. eventStore,
  1701. modelFactory: createTestModelFactory({
  1702. async generateText(request: any) {
  1703. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1704. if (toolNames.includes("Agent")) {
  1705. parentRequests.push(request);
  1706. if (parentRequests.length === 1) {
  1707. return {
  1708. finishReason: "tool-calls",
  1709. providerMetadata: undefined,
  1710. text: "",
  1711. toolCalls: [
  1712. {
  1713. id: "call_explicit_agent",
  1714. name: "Agent",
  1715. input: {
  1716. description: "检查 explicit custom agent",
  1717. prompt: "检查 custom explicit 子 agent 工具面。",
  1718. subagent_type: "explicit-reviewer",
  1719. },
  1720. },
  1721. ],
  1722. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1723. };
  1724. }
  1725. return {
  1726. finishReason: "stop",
  1727. providerMetadata: undefined,
  1728. text: "父 agent 收到 explicit 结果。",
  1729. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1730. };
  1731. }
  1732. childRequests.push(request);
  1733. return {
  1734. finishReason: "stop",
  1735. providerMetadata: undefined,
  1736. text: "explicit child done",
  1737. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1738. };
  1739. },
  1740. } as never),
  1741. },
  1742. );
  1743. const result = await runtime.executeTurn("让 explicit-reviewer 跑一下");
  1744. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  1745. const parentAgentToolDescription =
  1746. parentRequests[0].tools.find((tool: any) => tool.name === "Agent")?.description ?? "";
  1747. expect(result.response).toBe("父 agent 收到 explicit 结果。");
  1748. expect(
  1749. modelMessageContentToText(
  1750. parentRequests[0].messages.find((message: any) =>
  1751. modelMessageContentToText(message.content).includes(
  1752. "Available agent types for the Agent tool:",
  1753. ),
  1754. ).content,
  1755. ),
  1756. ).toContain("- explicit-reviewer: Asks for an explicit tool subset. (Tools: Read)");
  1757. expect(parentAgentToolDescription).not.toContain("EnterPlanMode");
  1758. expect(parentAgentToolDescription).not.toContain("ExitPlanMode");
  1759. expect(childToolNames).toContain("Read");
  1760. expect(childToolNames).not.toContain("EnterPlanMode");
  1761. expect(childToolNames).not.toContain("ExitPlanMode");
  1762. });
  1763. it("inherits disabled native find and grep enhancements in child Bash", async () => {
  1764. const sessionId = createSessionId("runtime-subagent-native-search-disabled");
  1765. const eventStore = createTestSessionEventStore();
  1766. const backend = {
  1767. kind: "native-binaries" as const,
  1768. findCommand: "/tools/bfs",
  1769. grepCommand: "/tools/ugrep",
  1770. rgCommand: "/tools/rg",
  1771. };
  1772. let childCallCount = 0;
  1773. let parentCallCount = 0;
  1774. let childBashPrelude: unknown;
  1775. const runtime = createTestAgentRuntime(
  1776. sessionId,
  1777. {
  1778. bashShellSelection: {
  1779. dialect: "posix",
  1780. display: { name: "bash" },
  1781. id: "posix:/bin/bash",
  1782. label: "bash",
  1783. path: "/bin/bash",
  1784. source: "auto-detected",
  1785. },
  1786. embeddedSearchBackend: backend,
  1787. mode: "yolo",
  1788. nativeSearchEnhancementsEnabled: false,
  1789. workingDirectory: "/workspace/project",
  1790. subagents: {
  1791. profiles: [
  1792. {
  1793. name: "search-child",
  1794. description: "Runs one search command.",
  1795. source: "project",
  1796. systemPrompt: "Run the requested search.",
  1797. tools: ["Bash"],
  1798. },
  1799. ],
  1800. },
  1801. },
  1802. {
  1803. eventStore,
  1804. executionPort: {
  1805. async run(request) {
  1806. childBashPrelude = request.bashPrelude;
  1807. const now = new Date();
  1808. return {
  1809. status: "completed",
  1810. exitCode: 0,
  1811. stdout: { text: "needle", bytes: 6, truncated: false },
  1812. stderr: { text: "", bytes: 0, truncated: false },
  1813. durationMs: 1,
  1814. timedOut: false,
  1815. cancelled: false,
  1816. startedAt: now,
  1817. completedAt: now,
  1818. };
  1819. },
  1820. },
  1821. modelFactory: createTestModelFactory({
  1822. async generateText(request: any) {
  1823. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1824. if (toolNames.includes("Agent")) {
  1825. parentCallCount++;
  1826. if (parentCallCount === 1) {
  1827. return {
  1828. finishReason: "tool-calls",
  1829. providerMetadata: undefined,
  1830. text: "",
  1831. toolCalls: [
  1832. {
  1833. id: "call_native_search_child",
  1834. name: "Agent",
  1835. input: {
  1836. description: "检查搜索继承",
  1837. prompt: "搜索 needle。",
  1838. subagent_type: "search-child",
  1839. },
  1840. },
  1841. ],
  1842. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1843. };
  1844. }
  1845. return {
  1846. finishReason: "stop",
  1847. providerMetadata: undefined,
  1848. text: "parent done",
  1849. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1850. };
  1851. }
  1852. childCallCount++;
  1853. if (childCallCount === 1) {
  1854. return {
  1855. finishReason: "tool-calls",
  1856. providerMetadata: undefined,
  1857. text: "",
  1858. toolCalls: [
  1859. {
  1860. id: "call_child_grep",
  1861. name: "Bash",
  1862. input: { command: "grep needle file.txt" },
  1863. },
  1864. ],
  1865. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1866. };
  1867. }
  1868. return {
  1869. finishReason: "stop",
  1870. providerMetadata: undefined,
  1871. text: "child done",
  1872. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1873. };
  1874. },
  1875. } as never),
  1876. },
  1877. );
  1878. await runtime.executeTurn("让 search-child 搜索");
  1879. expect(childBashPrelude).toEqual({
  1880. kind: "embedded-search",
  1881. backend,
  1882. findAndGrepEnabled: false,
  1883. });
  1884. });
  1885. it("does not let a subagent profile re-add tools removed by the parent runtime", async () => {
  1886. const sessionId = createSessionId("runtime-subagent-parent-disallowed-tools");
  1887. const eventStore = createTestSessionEventStore();
  1888. const parentRequests: any[] = [];
  1889. const childRequests: any[] = [];
  1890. const runtime = createTestAgentRuntime(
  1891. sessionId,
  1892. {
  1893. mode: "build",
  1894. toolDisallowlist: ["Bash(git *)"],
  1895. workingDirectory: "/workspace/project",
  1896. subagents: {
  1897. profiles: [
  1898. {
  1899. name: "bashy-reviewer",
  1900. description: "Requests Bash and Read.",
  1901. source: "project",
  1902. systemPrompt: "Review without shell access.",
  1903. tools: ["Bash", "Read"],
  1904. model: "main",
  1905. maxTurns: 2,
  1906. },
  1907. ],
  1908. },
  1909. },
  1910. {
  1911. eventStore,
  1912. modelFactory: createTestModelFactory({
  1913. async generateText(request: any) {
  1914. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  1915. if (toolNames.includes("Agent")) {
  1916. parentRequests.push(request);
  1917. if (parentRequests.length === 1) {
  1918. return {
  1919. finishReason: "tool-calls",
  1920. providerMetadata: undefined,
  1921. text: "",
  1922. toolCalls: [
  1923. {
  1924. id: "call_bashy_agent",
  1925. name: "Agent",
  1926. input: {
  1927. description: "检查 Bash 是否被移除",
  1928. prompt: "检查子 agent 工具面。",
  1929. subagent_type: "bashy-reviewer",
  1930. },
  1931. },
  1932. ],
  1933. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1934. };
  1935. }
  1936. return {
  1937. finishReason: "stop",
  1938. providerMetadata: undefined,
  1939. text: "父 agent 收到结果。",
  1940. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1941. };
  1942. }
  1943. childRequests.push(request);
  1944. return {
  1945. finishReason: "stop",
  1946. providerMetadata: undefined,
  1947. text: "child done",
  1948. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  1949. };
  1950. },
  1951. } as never),
  1952. },
  1953. );
  1954. const result = await runtime.executeTurn("让 bashy-reviewer 跑一下");
  1955. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  1956. expect(result.response).toBe("父 agent 收到结果。");
  1957. expect(childToolNames).toContain("Read");
  1958. expect(childToolNames).not.toContain("Bash");
  1959. });
  1960. it("auto-enables Skill and allows bare aliases for declared plugin skills", async () => {
  1961. const sessionId = createSessionId("runtime-subagent-filtered-skills");
  1962. const eventStore = createTestSessionEventStore();
  1963. const loadedSkills: string[] = [];
  1964. const allowedPluginSkill = {
  1965. ...skillMetadata("allowed-skill", "/plugins/superpowers/skills/allowed/SKILL.md"),
  1966. pluginName: "superpowers",
  1967. qualifiedName: "superpowers:allowed-skill",
  1968. rootPath: "/plugins/superpowers/skills",
  1969. scope: "system" as const,
  1970. source: "plugin" as const,
  1971. };
  1972. const conflictingPluginSkill = {
  1973. ...skillMetadata("allowed-skill", "/plugins/other/skills/allowed/SKILL.md"),
  1974. pluginName: "other-plugin",
  1975. qualifiedName: "other-plugin:allowed-skill",
  1976. rootPath: "/plugins/other/skills",
  1977. scope: "system" as const,
  1978. source: "plugin" as const,
  1979. };
  1980. const skillOutcome: SkillLoadOutcome = {
  1981. diagnostics: [],
  1982. skills: [
  1983. conflictingPluginSkill,
  1984. allowedPluginSkill,
  1985. skillMetadata("blocked-skill", "/skills/blocked/SKILL.md"),
  1986. ],
  1987. totalDiscovered: 3,
  1988. };
  1989. const skillPort: SkillPort = {
  1990. async discoverSkills() {
  1991. return skillOutcome;
  1992. },
  1993. async loadSkill(request): Promise<SkillContent> {
  1994. const metadata = skillOutcome.skills.find(
  1995. (skill) => skill.name === request.name || skill.qualifiedName === request.name,
  1996. );
  1997. if (!metadata) throw new Error(`Skill not found: ${request.name}`);
  1998. loadedSkills.push(metadata.qualifiedName ?? metadata.name);
  1999. return {
  2000. baseDirectory: metadata.directory,
  2001. bytesRead: 12,
  2002. content: `# ${metadata.qualifiedName ?? metadata.name}\n\n只使用允许的 skill。`,
  2003. metadata,
  2004. sizeBytes: 12,
  2005. truncated: false,
  2006. };
  2007. },
  2008. };
  2009. const parentRequests: any[] = [];
  2010. const childRequests: any[] = [];
  2011. const runtime = createTestAgentRuntime(
  2012. sessionId,
  2013. {
  2014. mode: "build",
  2015. workingDirectory: "/workspace/project",
  2016. subagents: {
  2017. profiles: [
  2018. {
  2019. name: "skill-agent",
  2020. description: "使用声明的 skill 完成任务。",
  2021. source: "project",
  2022. systemPrompt: "你必须先加载允许的 skill。",
  2023. tools: ["Read"],
  2024. skills: ["superpowers:allowed-skill"],
  2025. },
  2026. ],
  2027. },
  2028. },
  2029. {
  2030. eventStore,
  2031. skillPort,
  2032. modelFactory: createTestModelFactory({
  2033. async generateText(request: any) {
  2034. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2035. if (toolNames.includes("Agent")) {
  2036. parentRequests.push(request);
  2037. if (parentRequests.length === 1) {
  2038. return {
  2039. finishReason: "tool-calls",
  2040. providerMetadata: undefined,
  2041. text: "",
  2042. toolCalls: [
  2043. {
  2044. id: "call_skill_agent",
  2045. name: "Agent",
  2046. input: {
  2047. description: "测试 skill 过滤",
  2048. prompt: "加载 allowed-skill 后返回结论。",
  2049. subagent_type: "skill-agent",
  2050. },
  2051. },
  2052. ],
  2053. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2054. };
  2055. }
  2056. return {
  2057. finishReason: "stop",
  2058. providerMetadata: undefined,
  2059. text: "父 agent 收到了 skill-agent 的结论。",
  2060. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2061. };
  2062. }
  2063. childRequests.push(request);
  2064. if (childRequests.length === 1) {
  2065. expect(toolNames).toContain("Skill");
  2066. expect(toolNames).toContain("Read");
  2067. expect(toolNames).not.toContain("Agent");
  2068. expect(toolNames).not.toContain("Task");
  2069. const requestText = request.messages
  2070. .map((message: any) => modelMessageContentToText(message.content))
  2071. .join("\n");
  2072. expect(requestText).toContain("superpowers:allowed-skill");
  2073. expect(requestText).not.toContain("other-plugin:allowed-skill");
  2074. expect(requestText).not.toContain("blocked-skill");
  2075. return {
  2076. finishReason: "tool-calls",
  2077. providerMetadata: undefined,
  2078. text: "",
  2079. toolCalls: [
  2080. {
  2081. id: "call_allowed_skill",
  2082. name: "Skill",
  2083. input: { skill: "allowed-skill" },
  2084. },
  2085. ],
  2086. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2087. };
  2088. }
  2089. return {
  2090. finishReason: "stop",
  2091. providerMetadata: undefined,
  2092. text: "skill-agent 已加载允许的 skill。",
  2093. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2094. };
  2095. },
  2096. } as never),
  2097. },
  2098. );
  2099. const result = await runtime.executeTurn("让 skill-agent 跑一下");
  2100. expect(result.response).toBe("父 agent 收到了 skill-agent 的结论。");
  2101. expect(loadedSkills).toEqual(["superpowers:allowed-skill"]);
  2102. expect(childRequests).toHaveLength(2);
  2103. });
  2104. it("fails before the child request when a scoped MCP server is unavailable in the parent startup snapshot", async () => {
  2105. const sessionId = createSessionId("runtime-subagent-scoped-mcp-server-unavailable");
  2106. const eventStore = createTestSessionEventStore();
  2107. const parentRequests: any[] = [];
  2108. const childRequests: any[] = [];
  2109. const mcpPort = createMockMcpPort();
  2110. const runtime = createTestAgentRuntime(
  2111. sessionId,
  2112. {
  2113. mcp: { enabled: true, servers: {} },
  2114. mode: "build",
  2115. workingDirectory: "/workspace/project",
  2116. subagents: {
  2117. profiles: [
  2118. {
  2119. name: "mcp-agent",
  2120. description: "需要 MCP server 的 agent。",
  2121. source: "project",
  2122. systemPrompt: "已配置的 MCP server 在 parent 启动快照中不可用时不应该启动。",
  2123. mcpServers: ["required-server"],
  2124. },
  2125. ],
  2126. },
  2127. },
  2128. {
  2129. eventStore,
  2130. mcpPort,
  2131. modelFactory: createTestModelFactory({
  2132. async generateText(request: any) {
  2133. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2134. if (toolNames.includes("Agent")) {
  2135. parentRequests.push(request);
  2136. if (parentRequests.length === 1) {
  2137. return {
  2138. finishReason: "tool-calls",
  2139. providerMetadata: undefined,
  2140. text: "",
  2141. toolCalls: [
  2142. {
  2143. id: "call_mcp_agent",
  2144. name: "Agent",
  2145. input: {
  2146. description: "测试 scoped MCP server 不可用",
  2147. prompt: "检查已配置的 MCP server 是否在 parent 启动快照中已连接。",
  2148. subagent_type: "mcp-agent",
  2149. },
  2150. },
  2151. ],
  2152. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2153. };
  2154. }
  2155. return {
  2156. finishReason: "stop",
  2157. providerMetadata: undefined,
  2158. text: "父 agent 看到了 scoped MCP server 不可用错误。",
  2159. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2160. };
  2161. }
  2162. childRequests.push(request);
  2163. return {
  2164. finishReason: "stop",
  2165. providerMetadata: undefined,
  2166. text: "mcp-agent 正常启动。",
  2167. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2168. };
  2169. },
  2170. } as never),
  2171. },
  2172. );
  2173. const result = await runtime.executeTurn("让 mcp-agent 跑一下");
  2174. const secondParentRequestText = parentRequests[1].messages
  2175. .map((message: any) => modelMessageContentToText(message.content))
  2176. .join("\n");
  2177. expect(result.response).toBe("父 agent 看到了 scoped MCP server 不可用错误。");
  2178. expect(childRequests).toEqual([]);
  2179. expect(secondParentRequestText).toContain("Required MCP server is not connected");
  2180. expect(secondParentRequestText).toContain("required-server");
  2181. });
  2182. it("fails fast when an explicitly allowed MCP descriptor is absent from the parent startup snapshot", async () => {
  2183. const sessionId = createSessionId("runtime-subagent-missing-mcp-descriptor");
  2184. const eventStore = createTestSessionEventStore();
  2185. const parentRequests: any[] = [];
  2186. const childRequests: any[] = [];
  2187. const mcpPort = createMockMcpPort();
  2188. const runtime = createTestAgentRuntime(
  2189. sessionId,
  2190. {
  2191. mcp: { enabled: true, servers: {} },
  2192. mode: "build",
  2193. workingDirectory: "/workspace/project",
  2194. subagents: {
  2195. profiles: [
  2196. {
  2197. name: "mcp-agent",
  2198. description: "需要 MCP tool 的 agent。",
  2199. source: "project",
  2200. systemPrompt: "如果显式 MCP tool 不在 parent 启动快照中就不应该启动。",
  2201. tools: ["mcp__required-server__search"],
  2202. },
  2203. ],
  2204. },
  2205. },
  2206. {
  2207. eventStore,
  2208. mcpPort,
  2209. modelFactory: createTestModelFactory({
  2210. async generateText(request: any) {
  2211. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2212. if (toolNames.includes("Agent")) {
  2213. parentRequests.push(request);
  2214. if (parentRequests.length === 1) {
  2215. return {
  2216. finishReason: "tool-calls",
  2217. providerMetadata: undefined,
  2218. text: "",
  2219. toolCalls: [
  2220. {
  2221. id: "call_mcp_agent",
  2222. name: "Agent",
  2223. input: {
  2224. description: "测试 MCP descriptor 缺失",
  2225. prompt: "检查显式 MCP tool 是否存在于 parent 启动快照。",
  2226. subagent_type: "mcp-agent",
  2227. },
  2228. },
  2229. ],
  2230. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2231. };
  2232. }
  2233. return {
  2234. finishReason: "stop",
  2235. providerMetadata: undefined,
  2236. text: "父 agent 看到了 MCP tool 缺失错误。",
  2237. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2238. };
  2239. }
  2240. childRequests.push(request);
  2241. return {
  2242. finishReason: "stop",
  2243. providerMetadata: undefined,
  2244. text: "不应该真正启动子 agent。",
  2245. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2246. };
  2247. },
  2248. } as never),
  2249. },
  2250. );
  2251. const result = await runtime.executeTurn("让 mcp-agent 跑一下");
  2252. const secondParentRequestText = parentRequests[1].messages
  2253. .map((message: any) => modelMessageContentToText(message.content))
  2254. .join("\n");
  2255. expect(result.response).toBe("父 agent 看到了 MCP tool 缺失错误。");
  2256. expect(childRequests).toEqual([]);
  2257. expect(secondParentRequestText).toContain(
  2258. "Required MCP tool is not available in the parent startup snapshot",
  2259. );
  2260. expect(secondParentRequestText).toContain("mcp__required-server__search");
  2261. });
  2262. it("starts a wildcard general-purpose subagent when plugin MCP status uses raw server names", async () => {
  2263. const sessionId = createSessionId("runtime-subagent-wildcard-plugin-mcp");
  2264. const eventStore = createTestSessionEventStore();
  2265. const parentRequests: any[] = [];
  2266. const childRequests: any[] = [];
  2267. const connectedStatus = {
  2268. status: "connected" as const,
  2269. toolCount: 1,
  2270. transport: "stdio" as const,
  2271. updatedAt: new Date(0).toISOString(),
  2272. };
  2273. const mcpPort = createMockMcpPort({
  2274. async connectConfiguredServers() {
  2275. return {
  2276. statuses: {
  2277. "plugin:android-emulator:android-emulator": connectedStatus,
  2278. },
  2279. tools: [
  2280. {
  2281. serverName: "plugin:android-emulator:android-emulator",
  2282. toolName: "android_preflight",
  2283. description: "Check Android emulator prerequisites.",
  2284. inputSchema: { type: "object", properties: {} },
  2285. },
  2286. ],
  2287. };
  2288. },
  2289. async listTools() {
  2290. return [
  2291. {
  2292. serverName: "plugin:android-emulator:android-emulator",
  2293. toolName: "android_preflight",
  2294. description: "Check Android emulator prerequisites.",
  2295. inputSchema: { type: "object", properties: {} },
  2296. },
  2297. ];
  2298. },
  2299. async status() {
  2300. return {
  2301. "plugin:android-emulator:android-emulator": connectedStatus,
  2302. };
  2303. },
  2304. });
  2305. const runtime = createTestAgentRuntime(
  2306. sessionId,
  2307. {
  2308. mcp: {
  2309. enabled: true,
  2310. servers: {
  2311. "plugin:android-emulator:android-emulator": {
  2312. command: "android-emulator-mcp",
  2313. type: "stdio",
  2314. },
  2315. },
  2316. },
  2317. mode: "build",
  2318. workingDirectory: "/workspace/project",
  2319. },
  2320. {
  2321. eventStore,
  2322. mcpPort,
  2323. modelFactory: createTestModelFactory({
  2324. async generateText(request: any) {
  2325. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2326. if (toolNames.includes("Agent")) {
  2327. parentRequests.push(request);
  2328. if (parentRequests.length === 1) {
  2329. expect(toolNames).toContain(
  2330. "mcp__plugin_android-emulator_android-emulator__android_preflight",
  2331. );
  2332. return {
  2333. finishReason: "tool-calls",
  2334. providerMetadata: undefined,
  2335. text: "",
  2336. toolCalls: [
  2337. {
  2338. id: "call_general_purpose",
  2339. name: "Agent",
  2340. input: {
  2341. description: "测试 plugin MCP 名称",
  2342. prompt: "确认 general-purpose 可以启动。",
  2343. subagent_type: "general-purpose",
  2344. },
  2345. },
  2346. ],
  2347. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2348. };
  2349. }
  2350. return {
  2351. finishReason: "stop",
  2352. providerMetadata: undefined,
  2353. text: "父 agent 收到了 general-purpose 结果。",
  2354. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2355. };
  2356. }
  2357. childRequests.push(request);
  2358. const childToolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2359. expect(childToolNames).toContain(
  2360. "mcp__plugin_android-emulator_android-emulator__android_preflight",
  2361. );
  2362. return {
  2363. finishReason: "stop",
  2364. providerMetadata: undefined,
  2365. text: "general-purpose 正常启动。",
  2366. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2367. };
  2368. },
  2369. } as never),
  2370. },
  2371. );
  2372. const result = await runtime.executeTurn("让 general-purpose 跑一下");
  2373. const secondParentRequestText = parentRequests[1].messages
  2374. .map((message: any) => modelMessageContentToText(message.content))
  2375. .join("\n");
  2376. expect(result.response).toBe("父 agent 收到了 general-purpose 结果。");
  2377. expect(childRequests).toHaveLength(1);
  2378. expect(secondParentRequestText).not.toContain("Required MCP server is not connected");
  2379. });
  2380. it("scopes custom Explore wildcard MCP tools to the fixed parent startup snapshot", async () => {
  2381. const sessionId = createSessionId("runtime-custom-explore-wildcard-mcp");
  2382. const eventStore = createTestSessionEventStore();
  2383. const parentRequests: any[] = [];
  2384. const childRequests: any[] = [];
  2385. const allowedDescriptor = {
  2386. serverName: "alpha__server",
  2387. toolName: "allowed__lookup",
  2388. description: "Allowed alpha lookup.",
  2389. inputSchema: { type: "object", properties: {} },
  2390. };
  2391. const blockedDescriptor = {
  2392. serverName: "alpha__server",
  2393. toolName: "blocked__lookup",
  2394. description: "Blocked alpha lookup.",
  2395. inputSchema: { type: "object", properties: {} },
  2396. };
  2397. const outOfScopeDescriptor = {
  2398. serverName: "beta__server",
  2399. toolName: "beta__lookup",
  2400. description: "Out-of-scope beta lookup.",
  2401. inputSchema: { type: "object", properties: {} },
  2402. };
  2403. const lateDescriptor = {
  2404. serverName: "alpha__server",
  2405. toolName: "late__lookup",
  2406. description: "Only visible after startup.",
  2407. inputSchema: { type: "object", properties: {} },
  2408. };
  2409. const allowedMcpToolName = toMcpToolName(allowedDescriptor);
  2410. const blockedMcpToolName = toMcpToolName(blockedDescriptor);
  2411. const outOfScopeMcpToolName = toMcpToolName(outOfScopeDescriptor);
  2412. const lateMcpToolName = toMcpToolName(lateDescriptor);
  2413. const connectedStatus = {
  2414. status: "connected" as const,
  2415. toolCount: 2,
  2416. transport: "stdio" as const,
  2417. updatedAt: new Date(0).toISOString(),
  2418. };
  2419. const connectConfiguredServers = vi.fn(async () => ({
  2420. statuses: {
  2421. alpha__server: connectedStatus,
  2422. beta__server: { ...connectedStatus, toolCount: 1 },
  2423. },
  2424. tools: [allowedDescriptor, blockedDescriptor, outOfScopeDescriptor],
  2425. }));
  2426. const listTools = vi.fn(async () => [lateDescriptor]);
  2427. const status = vi.fn(async () => ({
  2428. alpha__server: { ...connectedStatus, toolCount: 1 },
  2429. }));
  2430. const mcpPort = createMockMcpPort({
  2431. connectConfiguredServers,
  2432. listTools,
  2433. status,
  2434. });
  2435. const runtime = createTestAgentRuntime(
  2436. sessionId,
  2437. {
  2438. mcp: {
  2439. enabled: true,
  2440. servers: {
  2441. alpha__server: { command: "alpha-mcp", type: "stdio" },
  2442. beta__server: { command: "beta-mcp", type: "stdio" },
  2443. },
  2444. },
  2445. mode: "build",
  2446. workingDirectory: "/workspace/project",
  2447. subagents: {
  2448. profiles: [
  2449. {
  2450. name: "Explore",
  2451. description: "Custom wildcard Explore.",
  2452. source: "user",
  2453. systemPrompt: "Use every inherited tool within the configured MCP scope.",
  2454. tools: ["*"],
  2455. disallowedTools: [blockedMcpToolName],
  2456. mcpServers: ["alpha__server"],
  2457. },
  2458. ],
  2459. },
  2460. },
  2461. {
  2462. eventStore,
  2463. mcpPort,
  2464. modelFactory: createTestModelFactory({
  2465. async generateText(request: any) {
  2466. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2467. if (toolNames.includes("Agent")) {
  2468. parentRequests.push(request);
  2469. if (parentRequests.length === 1) {
  2470. return {
  2471. finishReason: "tool-calls",
  2472. providerMetadata: undefined,
  2473. text: "",
  2474. toolCalls: [
  2475. {
  2476. id: "call_custom_explore_wildcard",
  2477. name: "Agent",
  2478. input: {
  2479. description: "测试 wildcard MCP snapshot",
  2480. prompt: "确认 custom Explore 只看到 scoped startup snapshot。",
  2481. subagent_type: "Explore",
  2482. },
  2483. },
  2484. ],
  2485. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2486. };
  2487. }
  2488. return {
  2489. finishReason: "stop",
  2490. providerMetadata: undefined,
  2491. text: "父 agent 收到了 custom Explore 结果。",
  2492. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2493. };
  2494. }
  2495. childRequests.push(request);
  2496. const childToolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2497. expect(childToolNames).toContain(allowedMcpToolName);
  2498. expect(childToolNames).not.toContain(blockedMcpToolName);
  2499. expect(childToolNames).not.toContain(outOfScopeMcpToolName);
  2500. expect(childToolNames).not.toContain(lateMcpToolName);
  2501. expect(childToolNames).not.toContain("Agent");
  2502. expect(childToolNames).not.toContain("Task");
  2503. expect(childToolNames).not.toContain("EnterPlanMode");
  2504. expect(childToolNames).not.toContain("ExitPlanMode");
  2505. return {
  2506. finishReason: "stop",
  2507. providerMetadata: undefined,
  2508. text: "custom Explore 正常启动。",
  2509. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2510. };
  2511. },
  2512. } as never),
  2513. },
  2514. );
  2515. const result = await runtime.executeTurn("让 custom Explore 跑一下");
  2516. expect(result.response).toBe("父 agent 收到了 custom Explore 结果。");
  2517. expect(childRequests).toHaveLength(1);
  2518. expect(connectConfiguredServers).toHaveBeenCalledTimes(1);
  2519. expect(status).not.toHaveBeenCalled();
  2520. expect(listTools).not.toHaveBeenCalled();
  2521. });
  2522. it("does not require an MCP server for a parent-denied subagent tool", async () => {
  2523. const sessionId = createSessionId("runtime-subagent-parent-denied-mcp-tool");
  2524. const eventStore = createTestSessionEventStore();
  2525. const parentRequests: any[] = [];
  2526. const childRequests: any[] = [];
  2527. const mcpPort = createMockMcpPort();
  2528. const runtime = createTestAgentRuntime(
  2529. sessionId,
  2530. {
  2531. mcp: { enabled: true, servers: {} },
  2532. mode: "build",
  2533. toolDisallowlist: ["mcp__required-server__search"],
  2534. workingDirectory: "/workspace/project",
  2535. subagents: {
  2536. profiles: [
  2537. {
  2538. name: "mcp-agent",
  2539. description: "声明了会被 parent deny 的 MCP tool。",
  2540. source: "project",
  2541. systemPrompt: "被 parent 移除的 MCP tool 不应该触发 server 检查。",
  2542. tools: ["mcp__required-server__search", "Read"],
  2543. },
  2544. ],
  2545. },
  2546. },
  2547. {
  2548. eventStore,
  2549. mcpPort,
  2550. modelFactory: createTestModelFactory({
  2551. async generateText(request: any) {
  2552. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2553. if (toolNames.includes("Agent")) {
  2554. parentRequests.push(request);
  2555. if (parentRequests.length === 1) {
  2556. return {
  2557. finishReason: "tool-calls",
  2558. providerMetadata: undefined,
  2559. text: "",
  2560. toolCalls: [
  2561. {
  2562. id: "call_mcp_agent",
  2563. name: "Agent",
  2564. input: {
  2565. description: "测试被 deny 的 MCP tool",
  2566. prompt: "检查被 parent deny 的 MCP tool 是否还会要求 server。",
  2567. subagent_type: "mcp-agent",
  2568. },
  2569. },
  2570. ],
  2571. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2572. };
  2573. }
  2574. return {
  2575. finishReason: "stop",
  2576. providerMetadata: undefined,
  2577. text: "父 agent 收到了 mcp-agent 结果。",
  2578. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2579. };
  2580. }
  2581. childRequests.push(request);
  2582. return {
  2583. finishReason: "stop",
  2584. providerMetadata: undefined,
  2585. text: "mcp-agent 正常启动。",
  2586. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2587. };
  2588. },
  2589. } as never),
  2590. },
  2591. );
  2592. const result = await runtime.executeTurn("让 mcp-agent 跑一下");
  2593. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  2594. const secondParentRequestText = parentRequests[1].messages
  2595. .map((message: any) => modelMessageContentToText(message.content))
  2596. .join("\n");
  2597. expect(result.response).toBe("父 agent 收到了 mcp-agent 结果。");
  2598. expect(childToolNames).toContain("Read");
  2599. expect(childToolNames).not.toContain("mcp__required-server__search");
  2600. expect(secondParentRequestText).not.toContain("Required MCP server is not connected");
  2601. });
  2602. it("returns after launching background Explore and consumes notification on the next turn", async () => {
  2603. const sessionId = createSessionId("runtime-background-explore-join");
  2604. const eventStore = createTestSessionEventStore();
  2605. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-subagent-output-"));
  2606. const parentRequests: any[] = [];
  2607. const childRequests: any[] = [];
  2608. let releaseChild!: () => void;
  2609. const childCanComplete = new Promise<void>((resolve) => {
  2610. releaseChild = resolve;
  2611. });
  2612. const runtime = createTestAgentRuntime(
  2613. sessionId,
  2614. {
  2615. mode: "build",
  2616. workingDirectory: "/workspace/project",
  2617. subagents: {
  2618. outputRootDir,
  2619. },
  2620. },
  2621. {
  2622. eventStore,
  2623. modelFactory: createTestModelFactory({
  2624. async generateText(request: any) {
  2625. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2626. if (toolNames.includes("Agent")) {
  2627. parentRequests.push(request);
  2628. if (parentRequests.length === 1) {
  2629. return {
  2630. finishReason: "tool-calls",
  2631. providerMetadata: undefined,
  2632. text: "",
  2633. toolCalls: [
  2634. {
  2635. id: "call_background_explore",
  2636. name: "Agent",
  2637. input: {
  2638. description: "Find runtime join",
  2639. prompt: "Find whether the parent turn waits for background results.",
  2640. run_in_background: true,
  2641. subagent_type: "Explore",
  2642. },
  2643. },
  2644. ],
  2645. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2646. };
  2647. }
  2648. if (parentRequests.length === 2) {
  2649. return {
  2650. finishReason: "stop",
  2651. providerMetadata: undefined,
  2652. text: "background explore launched",
  2653. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2654. };
  2655. }
  2656. return {
  2657. finishReason: "stop",
  2658. providerMetadata: undefined,
  2659. text: "parent summarized the background explore result",
  2660. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2661. };
  2662. }
  2663. childRequests.push(request);
  2664. await childCanComplete;
  2665. return {
  2666. finishReason: "stop",
  2667. providerMetadata: undefined,
  2668. text: "Background Explore found the join boundary in turn-stop.ts.",
  2669. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2670. };
  2671. },
  2672. } as never),
  2673. },
  2674. );
  2675. let firstTurnSettled = false;
  2676. const turnPromise = runtime.executeTurn("Use a background explore agent").then((value) => {
  2677. firstTurnSettled = true;
  2678. return value;
  2679. });
  2680. await waitForCondition(() => parentRequests.length === 2 && childRequests.length === 1);
  2681. await waitForCondition(() => firstTurnSettled);
  2682. const eventsBeforeChildCompletes = await eventStore.getEvents(sessionId);
  2683. expect(
  2684. eventsBeforeChildCompletes.some((event) => event.type === SessionEventType.TurnComplete),
  2685. ).toBe(true);
  2686. expect(
  2687. eventsBeforeChildCompletes.some((event) => event.type === SessionEventType.SubagentStopped),
  2688. ).toBe(false);
  2689. const launchResult = await turnPromise;
  2690. releaseChild();
  2691. await waitForCondition(async () => {
  2692. const events = await eventStore.getEvents(sessionId);
  2693. return events.some((event) => event.type === SessionEventType.SubagentStopped);
  2694. });
  2695. await waitForCondition(async () => {
  2696. const events = await eventStore.getEvents(sessionId);
  2697. return events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted);
  2698. });
  2699. await waitForCondition(() => parentRequests.length === 3);
  2700. const parentThirdRequestText = parentRequests[2].messages
  2701. .map((message: any) => modelMessageContentToText(message.content))
  2702. .join("\n");
  2703. const events = await eventStore.getEvents(sessionId);
  2704. const stoppedIndex = events.findIndex(
  2705. (event) => event.type === SessionEventType.SubagentStopped,
  2706. );
  2707. expect(launchResult.response).toBe("background explore launched");
  2708. expect(parentRequests).toHaveLength(3);
  2709. expect(parentThirdRequestText).toContain("<task-notification>");
  2710. expect(parentThirdRequestText).toContain("<tool-use-id>call_background_explore</tool-use-id>");
  2711. expect(parentThirdRequestText).not.toContain("<task-type>local_agent</task-type>");
  2712. expect(parentThirdRequestText).toContain("<output-file>");
  2713. expect(parentThirdRequestText).toContain("<status>completed</status>");
  2714. expect(parentThirdRequestText).toContain("<usage>");
  2715. expect(parentThirdRequestText).toContain("<subagent_tokens>");
  2716. expect(parentThirdRequestText).toContain("<tool_uses>");
  2717. expect(parentThirdRequestText).toContain("<duration_ms>");
  2718. expect(parentThirdRequestText).toContain("Background Explore found the join boundary");
  2719. expect(stoppedIndex).toBeGreaterThanOrEqual(0);
  2720. const stoppedPayload = events[stoppedIndex]?.payload as any;
  2721. const agentOutputDir = join(outputRootDir, sessionId, stoppedPayload.agentId);
  2722. await expect(readFile(join(agentOutputDir, "output.txt"), "utf8")).resolves.toContain(
  2723. "Background Explore found the join boundary",
  2724. );
  2725. await expect(readFile(join(agentOutputDir, "task.output"), "utf8")).resolves.toContain(
  2726. "Background Explore found the join boundary",
  2727. );
  2728. await expect(readFile(join(agentOutputDir, "transcript.jsonl"), "utf8")).rejects.toMatchObject({
  2729. code: "ENOENT",
  2730. });
  2731. const metadata = JSON.parse(await readFile(join(agentOutputDir, "metadata.json"), "utf8"));
  2732. expect(metadata).toMatchObject({
  2733. agentId: stoppedPayload.agentId,
  2734. parentSessionId: sessionId,
  2735. parentToolUseId: "call_background_explore",
  2736. profileId: "Explore",
  2737. status: "completed",
  2738. });
  2739. expect(metadata).not.toHaveProperty("transcriptFile");
  2740. });
  2741. it("launches background Explore by default when run_in_background is requested", async () => {
  2742. const sessionId = createSessionId("runtime-subagent-background-default");
  2743. const eventStore = createTestSessionEventStore();
  2744. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-subagent-output-"));
  2745. const parentRequests: any[] = [];
  2746. const childRequests: any[] = [];
  2747. const childGate = createDeferred<void>();
  2748. const runtime = createTestAgentRuntime(
  2749. sessionId,
  2750. {
  2751. mode: "build",
  2752. workingDirectory: "/workspace/project",
  2753. subagents: {
  2754. outputRootDir,
  2755. },
  2756. },
  2757. {
  2758. eventStore,
  2759. modelFactory: createTestModelFactory({
  2760. async generateText(request: any) {
  2761. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2762. if (toolNames.includes("Agent")) {
  2763. parentRequests.push(request);
  2764. if (parentRequests.length === 1) {
  2765. return {
  2766. finishReason: "tool-calls",
  2767. providerMetadata: undefined,
  2768. text: "",
  2769. toolCalls: [
  2770. {
  2771. id: "call_legacy_background_explore",
  2772. name: "Agent",
  2773. input: {
  2774. description: "Legacy background",
  2775. prompt: "Return after the background child finishes.",
  2776. run_in_background: true,
  2777. subagent_type: "Explore",
  2778. },
  2779. },
  2780. ],
  2781. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2782. };
  2783. }
  2784. return {
  2785. finishReason: "stop",
  2786. providerMetadata: undefined,
  2787. text: "foreground subagent completed",
  2788. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2789. };
  2790. }
  2791. childRequests.push(request);
  2792. await childGate.promise;
  2793. return {
  2794. finishReason: "stop",
  2795. providerMetadata: undefined,
  2796. text: "Background child finished after run_in_background detached.",
  2797. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  2798. };
  2799. },
  2800. } as never),
  2801. },
  2802. );
  2803. let turnSettled = false;
  2804. const turnPromise = runtime.executeTurn("Use a legacy background explore").then((value) => {
  2805. turnSettled = true;
  2806. return value;
  2807. });
  2808. await waitFor(async () => childRequests.length === 1);
  2809. await waitFor(() => parentRequests.length === 2);
  2810. await waitFor(() => turnSettled);
  2811. const eventsBeforeChildCompletes = await eventStore.getEvents(sessionId);
  2812. expect(turnSettled).toBe(true);
  2813. expect(
  2814. eventsBeforeChildCompletes.some((event) => event.type === SessionEventType.TurnComplete),
  2815. ).toBe(true);
  2816. expect(
  2817. eventsBeforeChildCompletes.some(
  2818. (event) => event.type === SessionEventType.BackgroundTaskStarted,
  2819. ),
  2820. ).toBe(true);
  2821. expect(
  2822. eventsBeforeChildCompletes.some((event) => event.type === SessionEventType.SubagentStopped),
  2823. ).toBe(false);
  2824. childGate.resolve();
  2825. const result = await turnPromise;
  2826. await waitFor(async () => {
  2827. const events = await eventStore.getEvents(sessionId);
  2828. return events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted);
  2829. });
  2830. await waitFor(() => parentRequests.length === 3);
  2831. const notificationRequestText = parentRequests[2].messages
  2832. .map((message: any) => modelMessageContentToText(message.content))
  2833. .join("\n");
  2834. const events = await eventStore.getEvents(sessionId);
  2835. expect(result.response).toBe("foreground subagent completed");
  2836. expect(parentRequests).toHaveLength(3);
  2837. expect(notificationRequestText).toContain("<task-notification>");
  2838. expect(notificationRequestText).toContain(
  2839. "<tool-use-id>call_legacy_background_explore</tool-use-id>",
  2840. );
  2841. expect(notificationRequestText).toContain(
  2842. "Background child finished after run_in_background detached.",
  2843. );
  2844. expect(events.some((event) => event.type === SessionEventType.SubagentStopped)).toBe(true);
  2845. expect(events.some((event) => event.type === SessionEventType.BackgroundTaskStarted)).toBe(
  2846. true,
  2847. );
  2848. expect(events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted)).toBe(
  2849. true,
  2850. );
  2851. });
  2852. it("runs foreground subagents in parallel when run_in_background is omitted", async () => {
  2853. const sessionId = createSessionId("runtime-subagent-foreground-parallel");
  2854. const eventStore = createTestSessionEventStore();
  2855. const parentRequests: any[] = [];
  2856. const childRequests: any[] = [];
  2857. const childGate = createDeferred<void>();
  2858. const runtime = createTestAgentRuntime(
  2859. sessionId,
  2860. {
  2861. mode: "build",
  2862. workingDirectory: "/workspace/project",
  2863. },
  2864. {
  2865. eventStore,
  2866. modelFactory: createTestModelFactory({
  2867. async generateText(request: any) {
  2868. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2869. if (toolNames.includes("Agent")) {
  2870. parentRequests.push(request);
  2871. if (parentRequests.length === 1) {
  2872. return {
  2873. finishReason: "tool-calls",
  2874. providerMetadata: undefined,
  2875. text: "",
  2876. toolCalls: [
  2877. {
  2878. id: "call_foreground_parallel_one",
  2879. name: "Agent",
  2880. input: {
  2881. description: "Parallel one",
  2882. prompt: "Run foreground child one.",
  2883. subagent_type: "Explore",
  2884. },
  2885. },
  2886. {
  2887. id: "call_foreground_parallel_two",
  2888. name: "Agent",
  2889. input: {
  2890. description: "Parallel two",
  2891. prompt: "Run foreground child two.",
  2892. subagent_type: "Explore",
  2893. },
  2894. },
  2895. ],
  2896. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2897. };
  2898. }
  2899. return {
  2900. finishReason: "stop",
  2901. providerMetadata: undefined,
  2902. text: "foreground parallel subagents completed",
  2903. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  2904. };
  2905. }
  2906. const childIndex = childRequests.length + 1;
  2907. childRequests.push(request);
  2908. await childGate.promise;
  2909. return {
  2910. finishReason: "stop",
  2911. providerMetadata: undefined,
  2912. text: `Parallel foreground child ${childIndex} finished.`,
  2913. usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
  2914. };
  2915. },
  2916. } as never),
  2917. },
  2918. );
  2919. let turnSettled = false;
  2920. const turnPromise = runtime.executeTurn("Use parallel foreground agents").then((value) => {
  2921. turnSettled = true;
  2922. return value;
  2923. });
  2924. await waitFor(async () => childRequests.length === 2);
  2925. await new Promise((resolve) => setTimeout(resolve, 25));
  2926. const eventsBeforeChildCompletes = await eventStore.getEvents(sessionId);
  2927. expect(turnSettled).toBe(false);
  2928. expect(
  2929. eventsBeforeChildCompletes.some((event) => event.type === SessionEventType.TurnComplete),
  2930. ).toBe(false);
  2931. expect(
  2932. eventsBeforeChildCompletes.some(
  2933. (event) => event.type === SessionEventType.BackgroundTaskStarted,
  2934. ),
  2935. ).toBe(false);
  2936. childGate.resolve();
  2937. const result = await turnPromise;
  2938. const finalParentRequestText = parentRequests[1].messages
  2939. .map((message: any) => modelMessageContentToText(message.content))
  2940. .join("\n");
  2941. const events = await eventStore.getEvents(sessionId);
  2942. const spawnEvents = events.filter((event) => event.type === SessionEventType.SubagentSpawned);
  2943. expect(result.response).toBe("foreground parallel subagents completed");
  2944. expect(childRequests).toHaveLength(2);
  2945. expect(parentRequests).toHaveLength(2);
  2946. expect(finalParentRequestText).toContain("Parallel foreground child 1 finished.");
  2947. expect(finalParentRequestText).toContain("Parallel foreground child 2 finished.");
  2948. expect(spawnEvents).toHaveLength(2);
  2949. expect(spawnEvents.every((event) => (event.payload as any).background !== true)).toBe(true);
  2950. expect(events.some((event) => event.type === SessionEventType.BackgroundTaskStarted)).toBe(
  2951. false,
  2952. );
  2953. expect(events.some((event) => event.type === SessionEventType.BackgroundTaskCompleted)).toBe(
  2954. false,
  2955. );
  2956. });
  2957. it("can SendMessage to a running background local_agent", async () => {
  2958. const sessionId = createSessionId("runtime-background-local-agent-send-message");
  2959. const eventStore = createTestSessionEventStore();
  2960. const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-subagent-output-"));
  2961. const parentRequests: any[] = [];
  2962. const childRequests: any[] = [];
  2963. let capturedAgentId = "";
  2964. let releaseChild!: () => void;
  2965. const childCanComplete = new Promise<void>((resolve) => {
  2966. releaseChild = resolve;
  2967. });
  2968. const runtime = createTestAgentRuntime(
  2969. sessionId,
  2970. {
  2971. mode: "build",
  2972. workingDirectory: "/workspace/project",
  2973. subagents: {
  2974. outputRootDir,
  2975. },
  2976. },
  2977. {
  2978. eventStore,
  2979. modelFactory: createTestModelFactory({
  2980. async generateText(request: any) {
  2981. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  2982. if (toolNames.includes("Agent")) {
  2983. parentRequests.push(request);
  2984. if (parentRequests.length === 1) {
  2985. return {
  2986. finishReason: "tool-calls",
  2987. providerMetadata: undefined,
  2988. text: "",
  2989. toolCalls: [
  2990. {
  2991. id: "call_background_agent",
  2992. name: "Agent",
  2993. input: {
  2994. description: "后台 agent 等待消息",
  2995. prompt: "先等待父 agent 的补充消息。",
  2996. run_in_background: true,
  2997. subagent_type: "Explore",
  2998. },
  2999. },
  3000. ],
  3001. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3002. };
  3003. }
  3004. if (parentRequests.length === 2) {
  3005. return {
  3006. finishReason: "stop",
  3007. providerMetadata: undefined,
  3008. text: "background launched",
  3009. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3010. };
  3011. }
  3012. if (parentRequests.length === 3) {
  3013. return {
  3014. finishReason: "tool-calls",
  3015. providerMetadata: undefined,
  3016. text: "",
  3017. toolCalls: [
  3018. {
  3019. id: "call_SendMessage_to_agent",
  3020. name: SEND_MESSAGE_TOOL_NAME,
  3021. input: {
  3022. to: capturedAgentId,
  3023. summary: "补充检查目标",
  3024. message: "请把检查目标改成权限链路,并在最终回答里说明已收到消息。",
  3025. },
  3026. },
  3027. ],
  3028. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3029. };
  3030. }
  3031. return {
  3032. finishReason: "stop",
  3033. providerMetadata: undefined,
  3034. text: "message sent",
  3035. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3036. };
  3037. }
  3038. childRequests.push(request);
  3039. if (childRequests.length === 1) {
  3040. await childCanComplete;
  3041. return {
  3042. finishReason: "stop",
  3043. providerMetadata: undefined,
  3044. text: "child initial result",
  3045. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3046. };
  3047. }
  3048. return {
  3049. finishReason: "stop",
  3050. providerMetadata: undefined,
  3051. text: "child handled coordinator message",
  3052. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3053. };
  3054. },
  3055. } as never),
  3056. },
  3057. );
  3058. const launchResult = await runtime.executeTurn("启动后台 agent");
  3059. await waitForCondition(() => childRequests.length === 1);
  3060. const spawnEvent = (await eventStore.getEvents(sessionId)).find(
  3061. (event) => event.type === SessionEventType.SubagentSpawned,
  3062. );
  3063. capturedAgentId = String((spawnEvent?.payload as any)?.agentId ?? "");
  3064. const sendResult = await runtime.executeTurn("给后台 agent 发送补充消息");
  3065. releaseChild();
  3066. await waitForCondition(() => childRequests.length >= 2);
  3067. const secondChildRequestText = childRequests[1].messages
  3068. .map((message: any) => modelMessageContentToText(message.content))
  3069. .join("\n");
  3070. expect(launchResult.response).toBe("background launched");
  3071. expect(sendResult.response).toBe("message sent");
  3072. expect(capturedAgentId).toMatch(/^agent_/u);
  3073. expect(childRequests[1].messages.slice(-2).map((message: any) => message.role)).toEqual([
  3074. "assistant",
  3075. "user",
  3076. ]);
  3077. expect(secondChildRequestText).toContain(
  3078. "The coordinator sent a message while you were working:",
  3079. );
  3080. expect(secondChildRequestText).toContain("补充检查目标");
  3081. expect(secondChildRequestText).toContain("Address this before completing your current task.");
  3082. expect(secondChildRequestText).toContain("请把检查目标改成权限链路");
  3083. });
  3084. it("routes RespondToCoordinator to the parent and continues the child tool loop", async () => {
  3085. const sessionId = createSessionId("runtime-child-respond-to-coordinator");
  3086. const eventStore = createTestSessionEventStore();
  3087. const sessionStore = createRecordingSubagentSessionStore();
  3088. const parentRequests: any[] = [];
  3089. const childRequests: any[] = [];
  3090. const runtime = createTestAgentRuntime(
  3091. sessionId,
  3092. {
  3093. mode: "build",
  3094. workingDirectory: "/workspace/project",
  3095. },
  3096. {
  3097. eventStore,
  3098. sessionStore,
  3099. modelFactory: createTestModelFactory({
  3100. async generateText(request: any) {
  3101. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  3102. if (toolNames.includes("Agent")) {
  3103. parentRequests.push(request);
  3104. if (parentRequests.length === 1) {
  3105. return {
  3106. finishReason: "tool-calls",
  3107. providerMetadata: undefined,
  3108. text: "",
  3109. toolCalls: [
  3110. {
  3111. id: "call_child_response_agent",
  3112. name: "Agent",
  3113. input: {
  3114. description: "检查权限链路",
  3115. prompt: "检查权限链路,并在收到询问时回复进度后继续任务。",
  3116. subagent_type: "general-purpose",
  3117. },
  3118. },
  3119. ],
  3120. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3121. };
  3122. }
  3123. return {
  3124. finishReason: "stop",
  3125. providerMetadata: undefined,
  3126. text: "parent received child response",
  3127. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3128. };
  3129. }
  3130. childRequests.push(request);
  3131. if (childRequests.length === 1) {
  3132. return {
  3133. finishReason: "tool-calls",
  3134. providerMetadata: undefined,
  3135. text: "",
  3136. toolCalls: [
  3137. {
  3138. id: "call_child_todo_before_response",
  3139. name: "TodoRead",
  3140. input: {},
  3141. },
  3142. {
  3143. id: "call_child_response_progress",
  3144. name: RESPOND_TO_COORDINATOR_TOOL_NAME,
  3145. input: {
  3146. summary: "权限链路进度",
  3147. message: "已完成前半段检查,正在继续剩余权限分支。",
  3148. },
  3149. },
  3150. ],
  3151. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3152. };
  3153. }
  3154. if (childRequests.length === 2) {
  3155. return {
  3156. finishReason: "tool-calls",
  3157. providerMetadata: undefined,
  3158. text: "",
  3159. toolCalls: [
  3160. {
  3161. id: "call_child_todo_after_response",
  3162. name: "TodoRead",
  3163. input: {},
  3164. },
  3165. ],
  3166. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3167. };
  3168. }
  3169. return {
  3170. finishReason: "stop",
  3171. providerMetadata: undefined,
  3172. text: "child completed the remaining permission work",
  3173. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3174. };
  3175. },
  3176. } as never),
  3177. },
  3178. );
  3179. const result = await runtime.executeTurn("让 child 检查权限链路");
  3180. const secondChildRequestText = childRequests[1].messages
  3181. .map((message: any) => modelMessageContentToText(message.content))
  3182. .join("\n");
  3183. const finalParentRequestText = parentRequests[1].messages
  3184. .map((message: any) => modelMessageContentToText(message.content))
  3185. .join("\n");
  3186. expect(result.response).toBe("parent received child response");
  3187. expect(parentRequests).toHaveLength(2);
  3188. expect(childRequests).toHaveLength(3);
  3189. expect(childRequests[0].tools.map((tool: any) => tool.name)).toContain(
  3190. RESPOND_TO_COORDINATOR_TOOL_NAME,
  3191. );
  3192. expect(secondChildRequestText).toContain("was queued for the coordinator");
  3193. expect(finalParentRequestText).toContain("<subagent-message>");
  3194. expect(finalParentRequestText).toContain("<summary>权限链路进度</summary>");
  3195. expect(finalParentRequestText).toContain(
  3196. "<message>已完成前半段检查,正在继续剩余权限分支。</message>",
  3197. );
  3198. expect(finalParentRequestText).toContain("child completed the remaining permission work");
  3199. });
  3200. it("runs built-in Explore on the main model by default while attributing usage to the subagent role", async () => {
  3201. const sessionId = createSessionId("runtime-explore-main-model");
  3202. const eventStore = createTestSessionEventStore();
  3203. const childRequests: any[] = [];
  3204. const childObservations: TestModelExecutionObservation[] = [];
  3205. let parentCallCount = 0;
  3206. const modelSelection = {
  3207. providerId: createModelProviderId("provider-main"),
  3208. modelId: createModelId("main-model"),
  3209. };
  3210. const runtime = createTestAgentRuntime(
  3211. sessionId,
  3212. {
  3213. mode: "build",
  3214. modelSelection: createTestModelSelection(modelSelection),
  3215. workingDirectory: "/workspace/project",
  3216. },
  3217. {
  3218. eventStore,
  3219. modelFactory: createTestModelFactory({
  3220. async generateText(request: any, observation) {
  3221. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  3222. if (toolNames.includes("Agent")) {
  3223. parentCallCount++;
  3224. if (parentCallCount === 1) {
  3225. return {
  3226. finishReason: "tool-calls",
  3227. providerMetadata: undefined,
  3228. text: "",
  3229. toolCalls: [
  3230. {
  3231. id: "call_explore_main",
  3232. name: "Agent",
  3233. input: {
  3234. description: "Find runtime loop",
  3235. prompt: "Find where the runtime injects tool results.",
  3236. subagent_type: "Explore",
  3237. },
  3238. },
  3239. ],
  3240. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3241. };
  3242. }
  3243. return {
  3244. finishReason: "stop",
  3245. providerMetadata: undefined,
  3246. text: "done",
  3247. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3248. };
  3249. }
  3250. childRequests.push(request);
  3251. childObservations.push(observation);
  3252. return {
  3253. finishReason: "stop",
  3254. providerMetadata: undefined,
  3255. text: "Explore used the inherited main model.",
  3256. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3257. };
  3258. },
  3259. } as never),
  3260. },
  3261. );
  3262. await runtime.executeTurn("Use an explore agent");
  3263. expect(childRequests).toHaveLength(1);
  3264. // Explore 默认继承主 Loop 的 Model;usage 由 child runtime 的 taskType 归因,
  3265. // 不再依赖旧 ModelSelection.role 修改模型身份。
  3266. expect(childObservations[0].model).toMatchObject({
  3267. providerId: modelSelection.providerId,
  3268. modelId: modelSelection.modelId,
  3269. });
  3270. expect(childObservations[0].factoryInput.providerOptions).toBeUndefined();
  3271. });
  3272. it("ignores a legacy call model and runs the built-in general-purpose agent on its configured model", async () => {
  3273. const sessionId = createSessionId("runtime-general-purpose-built-in-model-override");
  3274. const eventStore = createTestSessionEventStore();
  3275. const childRequests: any[] = [];
  3276. const childObservations: TestModelExecutionObservation[] = [];
  3277. let parentCallCount = 0;
  3278. const runtime = createTestAgentRuntime(
  3279. sessionId,
  3280. {
  3281. mode: "build",
  3282. modelSelection: {
  3283. providerId: createModelProviderId("provider-main"),
  3284. modelId: createModelId("main-model"),
  3285. },
  3286. workingDirectory: "/workspace/project",
  3287. subagents: {
  3288. builtInModelSelectionOverrides: {
  3289. "general-purpose": {
  3290. providerId: "custom-openai",
  3291. modelId: "gpt-5.4",
  3292. options: { reasoningLevel: "high" },
  3293. },
  3294. },
  3295. },
  3296. },
  3297. {
  3298. eventStore,
  3299. modelFactory: createTestModelFactory({
  3300. async generateText(request: any, observation) {
  3301. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  3302. if (toolNames.includes("Agent")) {
  3303. parentCallCount++;
  3304. if (parentCallCount === 1) {
  3305. return {
  3306. finishReason: "tool-calls",
  3307. providerMetadata: undefined,
  3308. text: "",
  3309. toolCalls: [
  3310. {
  3311. id: "call_general_purpose_override",
  3312. name: "Agent",
  3313. input: {
  3314. description: "Investigate default agent override",
  3315. model: "haiku",
  3316. prompt: "Check the configured model override.",
  3317. },
  3318. },
  3319. ],
  3320. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3321. };
  3322. }
  3323. return {
  3324. finishReason: "stop",
  3325. providerMetadata: undefined,
  3326. text: "done",
  3327. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3328. };
  3329. }
  3330. childRequests.push(request);
  3331. childObservations.push(observation);
  3332. return {
  3333. finishReason: "stop",
  3334. providerMetadata: undefined,
  3335. text: "general-purpose used the override.",
  3336. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3337. };
  3338. },
  3339. } as never),
  3340. },
  3341. );
  3342. await runtime.executeTurn("Use the default Agent");
  3343. expect(childRequests).toHaveLength(1);
  3344. expect(childObservations[0].model).toMatchObject({
  3345. providerId: "custom-openai",
  3346. modelId: "gpt-5.4",
  3347. });
  3348. });
  3349. it("ignores a legacy call model and uses the built-in Explore override for child request, spawn event, and tool branch capability", async () => {
  3350. const sessionId = createSessionId("runtime-explore-built-in-model-override");
  3351. const eventStore = createTestSessionEventStore();
  3352. const childRequests: any[] = [];
  3353. const childObservations: TestModelExecutionObservation[] = [];
  3354. let parentCallCount = 0;
  3355. const runtime = createTestAgentRuntime(
  3356. sessionId,
  3357. {
  3358. mode: "build",
  3359. modelSelection: {
  3360. providerId: createModelProviderId("provider-main"),
  3361. modelId: createModelId("main-model"),
  3362. },
  3363. workingDirectory: "/workspace/project",
  3364. subagents: {
  3365. builtInModelSelectionOverrides: {
  3366. Explore: { providerId: "custom-openai", modelId: "glm-5.2" },
  3367. },
  3368. },
  3369. },
  3370. {
  3371. eventStore,
  3372. modelFactory: createTestModelFactory({
  3373. properties: { supportsNativeWebSearch: true },
  3374. async generateText(request: any, observation) {
  3375. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  3376. if (toolNames.includes("Agent")) {
  3377. parentCallCount++;
  3378. if (parentCallCount === 1) {
  3379. return {
  3380. finishReason: "tool-calls",
  3381. providerMetadata: undefined,
  3382. text: "",
  3383. toolCalls: [
  3384. {
  3385. id: "call_explore_override",
  3386. name: "Agent",
  3387. input: {
  3388. description: "Check Explore override",
  3389. // 修复原因:旧 transcript 可能继续生成调用级 model;Explore 也必须只消费 profile。
  3390. model: "haiku",
  3391. prompt: "Check the configured model override.",
  3392. subagent_type: "Explore",
  3393. },
  3394. },
  3395. ],
  3396. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3397. };
  3398. }
  3399. return {
  3400. finishReason: "stop",
  3401. providerMetadata: undefined,
  3402. text: "done",
  3403. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3404. };
  3405. }
  3406. childRequests.push(request);
  3407. childObservations.push(observation);
  3408. return {
  3409. finishReason: "stop",
  3410. providerMetadata: undefined,
  3411. text: "Explore used the override.",
  3412. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3413. };
  3414. },
  3415. } as never),
  3416. },
  3417. );
  3418. await runtime.executeTurn("Use an explore agent");
  3419. const events = await eventStore.getEvents(sessionId);
  3420. const spawnEvent = events.find((event) => event.type === SessionEventType.SubagentSpawned);
  3421. const childToolNames = childRequests[0].tools.map((tool: any) => tool.name);
  3422. expect(childRequests).toHaveLength(1);
  3423. expect(childObservations[0].model).toMatchObject({
  3424. providerId: "custom-openai",
  3425. modelId: "glm-5.2",
  3426. });
  3427. expect(spawnEvent?.payload).toMatchObject({
  3428. agentType: "Explore",
  3429. model: "custom-openai/glm-5.2",
  3430. });
  3431. expect(childToolNames).toEqual([
  3432. "Bash",
  3433. "Read",
  3434. "TodoWrite",
  3435. "WebFetch",
  3436. "WebSearch",
  3437. RESPOND_TO_COORDINATOR_TOOL_NAME,
  3438. ]);
  3439. });
  3440. it("freezes each custom child from the latest ModelFactory facts", async () => {
  3441. const sessionId = createSessionId("runtime-subagent-concrete-model");
  3442. const eventStore = createTestSessionEventStore();
  3443. const childRequests: any[] = [];
  3444. const childObservations: TestModelExecutionObservation[] = [];
  3445. let parentCallCount = 0;
  3446. let currentMaxOutputTokens = 64_000;
  3447. const modelSelection = {
  3448. providerId: createModelProviderId("provider-main"),
  3449. modelId: createModelId("main-model"),
  3450. };
  3451. const runtime = createTestAgentRuntime(
  3452. sessionId,
  3453. {
  3454. mode: "build",
  3455. modelSelection: createTestModelSelection(modelSelection),
  3456. workingDirectory: "/workspace/project",
  3457. subagents: {
  3458. profiles: [
  3459. {
  3460. name: "code-reviewer",
  3461. description: "Review code",
  3462. source: "user",
  3463. systemPrompt: "Review carefully.",
  3464. modelSelection: { providerId: "custom-openai", modelId: "gpt-5.4" },
  3465. tools: ["Read"],
  3466. },
  3467. ],
  3468. },
  3469. },
  3470. {
  3471. eventStore,
  3472. modelFactory: createTestModelFactory({
  3473. maxOutputTokens: (input) =>
  3474. input.selection.providerId === "custom-openai" && input.selection.modelId === "gpt-5.4"
  3475. ? currentMaxOutputTokens
  3476. : 32_000,
  3477. properties: { contextWindow: 128_000 },
  3478. async generateText(request: any, observation) {
  3479. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  3480. if (toolNames.includes("Agent")) {
  3481. parentCallCount++;
  3482. if (parentCallCount <= 2) {
  3483. return {
  3484. finishReason: "tool-calls",
  3485. providerMetadata: undefined,
  3486. text: "",
  3487. toolCalls: [
  3488. {
  3489. id: `call_custom_model_agent_${parentCallCount}`,
  3490. name: "Agent",
  3491. input: {
  3492. description: "Review changed files",
  3493. prompt: "Review changed files.",
  3494. subagent_type: "code-reviewer",
  3495. },
  3496. },
  3497. ],
  3498. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3499. };
  3500. }
  3501. return {
  3502. finishReason: "stop",
  3503. providerMetadata: undefined,
  3504. text: "done",
  3505. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3506. };
  3507. }
  3508. childRequests.push(request);
  3509. childObservations.push(observation);
  3510. currentMaxOutputTokens = 16_000;
  3511. return {
  3512. finishReason: "stop",
  3513. providerMetadata: undefined,
  3514. text: "custom model reviewer finished.",
  3515. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3516. };
  3517. },
  3518. } as never),
  3519. },
  3520. );
  3521. await runtime.executeTurn("Use custom reviewer");
  3522. expect(childRequests).toHaveLength(2);
  3523. expect(
  3524. childRequests.map((request, index) => ({
  3525. maxOutputTokens: request.options?.maxOutputTokens,
  3526. modelId: childObservations[index].model.modelId,
  3527. providerId: childObservations[index].model.providerId,
  3528. })),
  3529. ).toEqual([
  3530. {
  3531. maxOutputTokens: 64_000,
  3532. modelId: "gpt-5.4",
  3533. providerId: "custom-openai",
  3534. },
  3535. {
  3536. maxOutputTokens: 16_000,
  3537. modelId: "gpt-5.4",
  3538. providerId: "custom-openai",
  3539. },
  3540. ]);
  3541. });
  3542. it("resolves an explicit profile again for a resumed child new input without changing the profile", async () => {
  3543. const sessionId = createSessionId("subagent-effective-resume");
  3544. const original = {
  3545. providerId: "account:personal",
  3546. modelId: "fixture",
  3547. options: { reasoningLevel: "high" },
  3548. };
  3549. let effective = { ...original, providerId: "account:team" };
  3550. const resolveEffectiveModelSelection = vi.fn(() => ({ effectiveSelection: effective }));
  3551. const requests: string[] = [];
  3552. const requestMessages: unknown[] = [];
  3553. const runtime = createTestAgentRuntime(
  3554. sessionId,
  3555. {
  3556. mode: "yolo",
  3557. workingDirectory: "/workspace/project",
  3558. subagents: {
  3559. profiles: [
  3560. {
  3561. name: "reviewer",
  3562. description: "Review",
  3563. source: "user",
  3564. systemPrompt: "Review",
  3565. tools: ["Read"],
  3566. modelSelection: original,
  3567. },
  3568. ],
  3569. },
  3570. },
  3571. {
  3572. eventStore: createTestSessionEventStore(),
  3573. sessionStore: createRecordingSubagentSessionStore(),
  3574. resolveEffectiveModelSelection,
  3575. modelFactory: createTestModelFactory({
  3576. async generateText(_request, observation) {
  3577. requests.push(observation.model.providerId);
  3578. requestMessages.push(_request.messages);
  3579. return {
  3580. finishReason: "stop",
  3581. text: "done",
  3582. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3583. };
  3584. },
  3585. }),
  3586. },
  3587. );
  3588. const port = (runtime as any).subagentPort;
  3589. const turnId = createTurnId("effective-resume-turn");
  3590. const trace = { traceId: createTraceId("effective-resume-trace"), sessionId, turnId };
  3591. const first = await port.run({
  3592. agentType: "reviewer",
  3593. description: "Review",
  3594. parentToolCallId: "first",
  3595. prompt: "Review first",
  3596. sessionId,
  3597. trace,
  3598. turnId,
  3599. workingDirectory: "/workspace/project",
  3600. workspaceRoot: "/workspace/project",
  3601. });
  3602. expect(first.status).toBe("completed");
  3603. effective = original;
  3604. const resumed = await port.sendMessage({
  3605. to: first.agentId,
  3606. message: "Review next",
  3607. summary: "Next",
  3608. parentToolCallId: "second",
  3609. sessionId,
  3610. trace,
  3611. turnId,
  3612. workingDirectory: "/workspace/project",
  3613. workspaceRoot: "/workspace/project",
  3614. });
  3615. expect(resumed.delivery).toBe("resumed_background");
  3616. expect((await port.waitForTask(first.agentId))?.status).toBe("completed");
  3617. expect(requests).toEqual(["account:team", "account:personal"]);
  3618. expect(JSON.stringify(requestMessages[1])).toContain("Review next");
  3619. expect(JSON.stringify(requestMessages[1])).not.toContain(
  3620. "The coordinator sent a message while you were working:",
  3621. );
  3622. expect(resolveEffectiveModelSelection).toHaveBeenCalledTimes(2);
  3623. expect(original.providerId).toBe("account:personal");
  3624. });
  3625. it("resumes a failed child with the next context profile while retaining identity and transcript", async () => {
  3626. const profile = (version: string) => ({
  3627. name: "reviewer",
  3628. source: "user" as const,
  3629. description: "Review",
  3630. tools: version === "old" ? ["Read"] : ["Grep"],
  3631. systemPrompt: `PROFILE_${version}`,
  3632. modelSelection: {
  3633. providerId: "custom",
  3634. modelId: version,
  3635. options: { reasoningLevel: version === "old" ? "low" : "high" },
  3636. },
  3637. });
  3638. const scenario = setupProfileScenario(async ({ model }) => {
  3639. if (model === "old") throw new Error("Invalid model configuration");
  3640. return profileDone();
  3641. });
  3642. scenario.update(profile("old"));
  3643. const { runtime, store: sessionStore, children: requests } = scenario;
  3644. const sessionId = runtime.sessionId;
  3645. const internal = runtime as any;
  3646. const turnId = createTurnId();
  3647. const trace = { traceId: createTraceId(), sessionId, turnId };
  3648. const context = {
  3649. sessionId,
  3650. turnId,
  3651. trace,
  3652. workingDirectory: "/workspace/project",
  3653. workspaceRoot: "/workspace/project",
  3654. };
  3655. const prepare = () =>
  3656. internal.prepareAgentDefinitions({
  3657. signal: new AbortController().signal,
  3658. traceContext: trace,
  3659. });
  3660. await prepare();
  3661. await expect(
  3662. internal.subagentPort.run({
  3663. ...context,
  3664. agentType: "reviewer",
  3665. description: "Review",
  3666. parentToolCallId: "first",
  3667. prompt: "ORIGINAL_CHILD_INPUT",
  3668. }),
  3669. ).rejects.toThrow("Turn execution failed");
  3670. const first = Object.values(internal.runtimeTaskRegistry.all())[0] as {
  3671. status: string;
  3672. agentId: string;
  3673. };
  3674. expect(first.status).toBe("failed");
  3675. const originalTask = await internal.subagentPort.getTask(first.agentId);
  3676. scenario.update(profile("new"));
  3677. // 保存发生在当前上下文内:同轮 SendMessage 仍使用旧 profile,直到下轮 prepare。
  3678. await internal.subagentPort.sendMessage({
  3679. ...context,
  3680. to: first.agentId,
  3681. message: "SAME_TURN_RETRY",
  3682. summary: "Retry",
  3683. parentToolCallId: "same-turn",
  3684. });
  3685. expect((await internal.subagentPort.waitForTask(first.agentId))?.status).toBe("failed");
  3686. expect(requests.at(-1)?.model).toBe("old");
  3687. await prepare();
  3688. const resumed = await internal.subagentPort.sendMessage({
  3689. ...context,
  3690. to: first.agentId,
  3691. message: "RESUME_CHILD_INPUT",
  3692. summary: "Next",
  3693. parentToolCallId: "second",
  3694. });
  3695. expect(resumed.delivery).toBe("resumed_background");
  3696. const task = await internal.subagentPort.waitForTask(first.agentId);
  3697. expect(task).toMatchObject({
  3698. status: "completed",
  3699. agentId: first.agentId,
  3700. childSessionId: originalTask.childSessionId,
  3701. });
  3702. const captured = requests.at(-1)!;
  3703. const request = {
  3704. ...captured,
  3705. content: JSON.stringify(captured.request.messages),
  3706. tools: captured.request.tools?.map((tool) => tool.name) ?? [],
  3707. };
  3708. expect(request.model).toBe("new");
  3709. expect(request.reasoning).toBe("high");
  3710. expect(request.content).toContain("PROFILE_new");
  3711. expect(request.content).not.toContain("PROFILE_old");
  3712. expect(request.content).toContain("ORIGINAL_CHILD_INPUT");
  3713. expect(request.content).toContain("RESUME_CHILD_INPUT");
  3714. expect(request.tools).toContain("Grep");
  3715. expect(request.tools).not.toContain("Read");
  3716. const modelEntry = (
  3717. await sessionStore.sessionEntries({
  3718. sessionID: task.childSessionId,
  3719. type: "runtime/model_selection",
  3720. })
  3721. ).at(-1);
  3722. expect(modelEntry?.data).toMatchObject({ modelId: "new", options: { reasoningLevel: "high" } });
  3723. const history = await sessionStore.messages({ sessionID: task.childSessionId });
  3724. expect(history.flatMap((message) => message.parts)).toEqual(
  3725. expect.arrayContaining([
  3726. expect.objectContaining({
  3727. type: "timeline",
  3728. timelineType: "model_change",
  3729. fromModel: expect.objectContaining({ modelId: "old" }),
  3730. toModel: expect.objectContaining({ modelId: "new" }),
  3731. }),
  3732. ]),
  3733. );
  3734. scenario.load.mockResolvedValueOnce({ activeAgents: [] });
  3735. await prepare();
  3736. const missing = await internal.subagentPort.sendMessage({
  3737. ...context,
  3738. to: first.agentId,
  3739. message: "Again",
  3740. summary: "Next",
  3741. parentToolCallId: "third",
  3742. });
  3743. expect(missing.status).toBe("failed");
  3744. expect(JSON.stringify(missing)).toContain("profile reviewer is unavailable");
  3745. scenario.update(profile("new"));
  3746. await prepare();
  3747. const childSessions = async () =>
  3748. (await sessionStore.listSessions({} as never)).filter((session) => session.id !== sessionId);
  3749. const sessionsBeforeMissingHistory = await childSessions();
  3750. sessionStore.messages = async () => [];
  3751. await expect(
  3752. internal.subagentPort.sendMessage({
  3753. ...context,
  3754. to: first.agentId,
  3755. message: "Again",
  3756. summary: "Next",
  3757. parentToolCallId: "fourth",
  3758. }),
  3759. ).rejects.toThrow("No transcript found");
  3760. expect(await childSessions()).toEqual(sessionsBeforeMissingHistory);
  3761. });
  3762. it("fails custom profiles instead of falling back when the configured model is invalid", async () => {
  3763. const sessionId = createSessionId("runtime-subagent-invalid-model");
  3764. const eventStore = createTestSessionEventStore();
  3765. const parentRequests: any[] = [];
  3766. const childRequests: any[] = [];
  3767. let parentCallCount = 0;
  3768. const runtime = createTestAgentRuntime(
  3769. sessionId,
  3770. {
  3771. mode: "build",
  3772. modelSelection: {
  3773. providerId: createModelProviderId("provider-main"),
  3774. modelId: createModelId("main-model"),
  3775. },
  3776. workingDirectory: "/workspace/project",
  3777. subagents: {
  3778. profiles: [
  3779. {
  3780. name: "broken-reviewer",
  3781. description: "Review code",
  3782. source: "user",
  3783. systemPrompt: "Review carefully.",
  3784. modelSelection: { providerId: "missing-provider", modelId: "missing-model" },
  3785. tools: ["Read"],
  3786. },
  3787. ],
  3788. },
  3789. },
  3790. {
  3791. eventStore,
  3792. modelFactory: ((factory) => (input: Parameters<typeof factory>[0]) => {
  3793. if (
  3794. input.selection.providerId === "missing-provider" &&
  3795. input.selection.modelId === "missing-model"
  3796. ) {
  3797. throw new Error("Invalid subagent model configuration");
  3798. }
  3799. return factory(input);
  3800. })(
  3801. createTestModelFactory({
  3802. async generateText(request: any) {
  3803. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  3804. if (toolNames.includes("Agent")) {
  3805. parentRequests.push(request);
  3806. parentCallCount++;
  3807. if (parentCallCount === 1) {
  3808. return {
  3809. finishReason: "tool-calls",
  3810. providerMetadata: undefined,
  3811. text: "",
  3812. toolCalls: [
  3813. {
  3814. id: "call_invalid_model_agent",
  3815. name: "Agent",
  3816. input: {
  3817. description: "Review changed files",
  3818. prompt: "Review changed files.",
  3819. subagent_type: "broken-reviewer",
  3820. },
  3821. },
  3822. ],
  3823. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3824. };
  3825. }
  3826. return {
  3827. finishReason: "stop",
  3828. providerMetadata: undefined,
  3829. text: "done",
  3830. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3831. };
  3832. }
  3833. childRequests.push(request);
  3834. return {
  3835. finishReason: "stop",
  3836. providerMetadata: undefined,
  3837. text: "should not run",
  3838. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3839. };
  3840. },
  3841. } as never),
  3842. ),
  3843. },
  3844. );
  3845. const result = await runtime.executeTurn("Use broken reviewer");
  3846. const toolBatchCompleteEvent = result.events.find(
  3847. (event) => event.type === SessionEventType.ToolBatchComplete,
  3848. );
  3849. const toolMessage = parentRequests[1]?.messages.find((message: any) => message.role === "tool");
  3850. expect(toolMessage).toMatchObject({
  3851. content: "Invalid subagent model configuration",
  3852. isError: true,
  3853. toolName: "Agent",
  3854. });
  3855. expect(toolBatchCompleteEvent?.payload).toMatchObject({
  3856. successCount: 0,
  3857. errorCount: 1,
  3858. });
  3859. expect(childRequests).toHaveLength(0);
  3860. });
  3861. it("inherits parent model streaming for Explore child requests", async () => {
  3862. const sessionId = createSessionId("runtime-explore-streaming-inheritance");
  3863. const eventStore = createTestSessionEventStore();
  3864. const streamRequests: any[] = [];
  3865. const childStreamRequests: any[] = [];
  3866. let parentCallCount = 0;
  3867. const runtime = createTestAgentRuntime(
  3868. sessionId,
  3869. {
  3870. mode: "build",
  3871. modelStreaming: "on",
  3872. workingDirectory: "/workspace/project",
  3873. },
  3874. {
  3875. eventStore,
  3876. modelFactory: createTestModelFactory({
  3877. properties: { supportsNativeWebSearch: true },
  3878. async generateText() {
  3879. throw new Error("generateText should not be used when modelStreaming is on");
  3880. },
  3881. async *streamText(request: any) {
  3882. streamRequests.push(request);
  3883. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  3884. if (toolNames.includes("Agent")) {
  3885. parentCallCount++;
  3886. if (parentCallCount === 1) {
  3887. yield {
  3888. type: "tool_call",
  3889. toolCall: {
  3890. id: "call_explore_stream",
  3891. name: "Agent",
  3892. input: {
  3893. description: "Find runtime loop",
  3894. prompt: "Find where the runtime injects tool results.",
  3895. subagent_type: "Explore",
  3896. },
  3897. },
  3898. };
  3899. yield {
  3900. type: "finish",
  3901. finishReason: "tool-calls",
  3902. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3903. };
  3904. return;
  3905. }
  3906. yield { type: "text_delta", text: "parent used streamed explore result" };
  3907. yield {
  3908. type: "finish",
  3909. finishReason: "stop",
  3910. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3911. };
  3912. return;
  3913. }
  3914. childStreamRequests.push(request);
  3915. yield { type: "text_delta", text: "Explore streamed child result." };
  3916. yield {
  3917. type: "finish",
  3918. finishReason: "stop",
  3919. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3920. };
  3921. },
  3922. } as never),
  3923. },
  3924. );
  3925. const result = await runtime.executeTurn("Use an explore agent with streaming");
  3926. expect(result.response).toBe("parent used streamed explore result");
  3927. expect(streamRequests).toHaveLength(3);
  3928. expect(childStreamRequests).toHaveLength(1);
  3929. expect(childStreamRequests[0].tools.map((tool: any) => tool.name)).toEqual([
  3930. "Bash",
  3931. "Read",
  3932. "TodoWrite",
  3933. "WebFetch",
  3934. "WebSearch",
  3935. RESPOND_TO_COORDINATOR_TOOL_NAME,
  3936. ]);
  3937. });
  3938. it("uses the latest parent model config when spawning Explore", async () => {
  3939. const sessionId = createSessionId("runtime-explore-model-update");
  3940. const eventStore = createTestSessionEventStore();
  3941. const childRequests: any[] = [];
  3942. const childObservations: TestModelExecutionObservation[] = [];
  3943. let parentCallCount = 0;
  3944. const initialModelSelection = {
  3945. providerId: createModelProviderId("provider-old"),
  3946. modelId: createModelId("old-model"),
  3947. };
  3948. const updatedModelSelection = {
  3949. providerId: createModelProviderId("provider-new"),
  3950. modelId: createModelId("new-model"),
  3951. };
  3952. const runtime = createTestAgentRuntime(
  3953. sessionId,
  3954. {
  3955. mode: "build",
  3956. modelSelection: createTestModelSelection(initialModelSelection),
  3957. workingDirectory: "/workspace/project",
  3958. },
  3959. {
  3960. eventStore,
  3961. modelFactory: createTestModelFactory({
  3962. async generateText(request: any, observation) {
  3963. const toolNames = (request.tools ?? []).map((tool: any) => tool.name);
  3964. if (toolNames.includes("Agent")) {
  3965. parentCallCount++;
  3966. if (parentCallCount === 1) {
  3967. return {
  3968. finishReason: "tool-calls",
  3969. providerMetadata: undefined,
  3970. text: "",
  3971. toolCalls: [
  3972. {
  3973. id: "call_explore_updated_model",
  3974. name: "Agent",
  3975. input: {
  3976. description: "Check model",
  3977. prompt: "Check the inherited model.",
  3978. subagent_type: "Explore",
  3979. },
  3980. },
  3981. ],
  3982. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3983. };
  3984. }
  3985. return {
  3986. finishReason: "stop",
  3987. providerMetadata: undefined,
  3988. text: "done",
  3989. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3990. };
  3991. }
  3992. childRequests.push(request);
  3993. childObservations.push(observation);
  3994. return {
  3995. finishReason: "stop",
  3996. providerMetadata: undefined,
  3997. text: "child used updated model",
  3998. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  3999. };
  4000. },
  4001. } as never),
  4002. },
  4003. );
  4004. runtime.setSessionModelSelection({
  4005. providerId: String(updatedModelSelection.providerId),
  4006. modelId: String(updatedModelSelection.modelId),
  4007. });
  4008. await runtime.executeTurn("Use an explore agent");
  4009. expect(childRequests).toHaveLength(1);
  4010. expect(childObservations[0].model).toMatchObject({
  4011. providerId: updatedModelSelection.providerId,
  4012. modelId: updatedModelSelection.modelId,
  4013. });
  4014. });
  4015. it("does not register Agent when subagents are disabled", () => {
  4016. const runtime = createTestAgentRuntime(
  4017. createSessionId("runtime-explore-disabled"),
  4018. {
  4019. subagents: {
  4020. enabled: false,
  4021. },
  4022. },
  4023. {
  4024. eventStore: createTestSessionEventStore(),
  4025. modelFactory: createTestModelFactory({
  4026. async generateText() {
  4027. throw new Error("model should not be called");
  4028. },
  4029. } as never),
  4030. },
  4031. );
  4032. expect(runtime.getToolRegistry().has("Agent")).toBe(false);
  4033. expect(runtime.getToolRegistry().has("Task")).toBe(false);
  4034. });
  4035. });
  4036. function createDeferred<T>(): {
  4037. promise: Promise<T>;
  4038. reject: (reason?: unknown) => void;
  4039. resolve: (value?: T | PromiseLike<T>) => void;
  4040. } {
  4041. let resolve!: (value?: T | PromiseLike<T>) => void;
  4042. let reject!: (reason?: unknown) => void;
  4043. const promise = new Promise<T>((innerResolve, innerReject) => {
  4044. resolve = (value) => innerResolve(value as T | PromiseLike<T>);
  4045. reject = innerReject;
  4046. });
  4047. return { promise, reject, resolve };
  4048. }
  4049. async function waitFor(
  4050. predicate: () => boolean | Promise<boolean>,
  4051. timeoutMs = 2_500,
  4052. ): Promise<void> {
  4053. const deadline = Date.now() + timeoutMs;
  4054. while (Date.now() < deadline) {
  4055. if (await predicate()) return;
  4056. await new Promise((resolve) => setTimeout(resolve, 10));
  4057. }
  4058. throw new Error("Timed out waiting for condition");
  4059. }
  4060. function skillMetadata(name: string, path: string): SkillLoadOutcome["skills"][number] {
  4061. return {
  4062. description: `${name} description`,
  4063. directory: path.slice(0, path.lastIndexOf("/")),
  4064. frontmatterKeys: ["name", "description"],
  4065. name,
  4066. path,
  4067. rootPath: "/skills",
  4068. safeToAutoLoad: true,
  4069. scope: "project",
  4070. source: "zcode",
  4071. };
  4072. }
  4073. function createMockMcpPort(overrides: Partial<McpPort> = {}): McpPort {
  4074. return {
  4075. async callTool() {
  4076. return { content: [{ text: "ok", type: "text" }] };
  4077. },
  4078. async close() {},
  4079. async connectConfiguredServers() {
  4080. return { statuses: {}, tools: [] };
  4081. },
  4082. async connectServer() {
  4083. return {
  4084. status: "connected",
  4085. toolCount: 0,
  4086. transport: "stdio",
  4087. updatedAt: new Date(0).toISOString(),
  4088. };
  4089. },
  4090. async disconnectServer() {
  4091. return undefined;
  4092. },
  4093. async listTools() {
  4094. return [];
  4095. },
  4096. async status() {
  4097. return {};
  4098. },
  4099. ...overrides,
  4100. };
  4101. }