subagent-explore.test.ts 167 KB

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