@duckmind/dm-darwin-x64 0.49.0 → 0.49.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +14 -4
  3. package/extensions/dm-subagents/src/extension/doctor.js +10 -10
  4. package/extensions/dm-subagents/src/extension/fanout-child.js +97 -97
  5. package/extensions/dm-subagents/src/extension/index.js +121 -121
  6. package/extensions/dm-subagents/src/extension/rpc.js +5 -5
  7. package/extensions/dm-subagents/src/extension/schemas.js +1 -1
  8. package/extensions/dm-subagents/src/extension/tool-description.js +2 -2
  9. package/extensions/dm-subagents/src/intercom/native-supervisor-channel.js +5 -5
  10. package/extensions/dm-subagents/src/runs/background/async-execution.js +19 -19
  11. package/extensions/dm-subagents/src/runs/background/async-job-tracker.js +9 -9
  12. package/extensions/dm-subagents/src/runs/background/async-resume.js +5 -5
  13. package/extensions/dm-subagents/src/runs/background/async-status.js +8 -8
  14. package/extensions/dm-subagents/src/runs/background/fleet-view.js +13 -13
  15. package/extensions/dm-subagents/src/runs/background/result-watcher.js +5 -5
  16. package/extensions/dm-subagents/src/runs/background/run-id-resolver.js +3 -3
  17. package/extensions/dm-subagents/src/runs/background/run-status.js +19 -19
  18. package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.js +7 -7
  19. package/extensions/dm-subagents/src/runs/background/subagent-runner.js +35 -35
  20. package/extensions/dm-subagents/src/runs/background/wait.js +7 -7
  21. package/extensions/dm-subagents/src/runs/foreground/chain-execution.js +32 -32
  22. package/extensions/dm-subagents/src/runs/foreground/execution.js +26 -26
  23. package/extensions/dm-subagents/src/runs/foreground/subagent-executor.js +96 -96
  24. package/extensions/dm-subagents/src/runs/shared/dm-args.js +1 -1
  25. package/extensions/dm-subagents/src/runs/shared/nested-events.js +6 -6
  26. package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.js +13 -13
  27. package/extensions/dm-subagents/src/shared/fork-context.js +4 -4
  28. package/package.json +1 -1
  29. package/extensions/dm-caveman/LICENSE +0 -21
  30. package/extensions/dm-cli-anything/LICENSE +0 -201
  31. package/extensions/dm-goal/LICENSE +0 -21
  32. package/extensions/dm-grill-me/LICENSE +0 -21
  33. package/extensions/dm-subagents/banner.png +0 -0
  34. package/extensions/dm-tasks/LICENSE +0 -21
  35. package/extensions/dm-usage/LICENSE +0 -21
  36. package/extensions/dm-usage/insights-screenshot.png +0 -0
  37. package/extensions/dm-usage/screenshot.png +0 -0
  38. package/extensions/greedysearch-dm/LICENSE +0 -21
@@ -1,10 +1,10 @@
1
- import{spawn as S5,spawnSync as d8}from"node:child_process";import*as e from"node:fs";import*as r from"node:path";import{pathToFileURL as D5}from"node:url";import*as e8 from"node:fs";import*as V0 from"node:path";var $2=[10,25,50,100,200,500,1000,2000,4000],j2=new Set(["EACCES","EBUSY","EPERM"]),uj=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,lj=uj?new Int32Array(uj):void 0;function J2($){if($<=0)return;if(lj)try{Atomics.wait(lj,0,0,$);return}catch{}let j=Date.now()+$;while(Date.now()<j);}function Z2($){let j=$?.code;return typeof j==="string"&&j2.has(j)}function Q2($,j,J,Z,Q){for(let X=0;;X++)try{$.renameSync(j,J);return}catch(W){let K=Z[X];if(K===void 0||!Z2(W))throw W;Q(K)}}function X2($={}){let j=$.fs??e8,J=$.now??Date.now,Z=$.pid??process.pid,Q=$.random??Math.random,W=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??$2:[],K=$.wait??J2;return(G,B)=>{j.mkdirSync(V0.dirname(G),{recursive:!0});let q=V0.join(V0.dirname(G),`.${V0.basename(G)}.${Z}.${J()}.${Q().toString(36).slice(2)}.tmp`);try{j.writeFileSync(q,JSON.stringify(B,null,2),"utf-8"),Q2(j,q,G,W,K)}finally{j.rmSync(q,{force:!0})}}}var D$=X2();import*as K0 from"node:fs";import*as XJ from"node:path";import*as N$ from"node:fs";import*as b0 from"node:os";import*as h$ from"node:path";import*as J0 from"node:fs";import*as $1 from"node:path";import*as q0 from"node:os";import*as F0 from"node:path";var S0=1;var nj={bytes:204800,lines:5000};function a0($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Y2($){let j=$?.env??process.env,J=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof J==="function")return`uid-${J()}`;for(let W of["USERNAME","USER","LOGNAME"]){let K=j[W];if(K)return`user-${a0(K)}`}let Z=$&&Object.hasOwn($,"userInfo")?$.userInfo:q0.userInfo;try{let W=Z?.().username;if(W)return`user-${a0(W)}`}catch{}let Q=j.USERPROFILE??j.HOME;if(Q)return`home-${a0(Q)}`;let X=$&&Object.hasOwn($,"homedir")?$.homedir:q0.homedir;try{let W=X?.();if(W)return`home-${a0(W)}`}catch{}return"shared"}var r$=F0.join(q0.tmpdir(),`dm-subagents-${Y2()}`),W2=F0.join(r$,"async-subagent-results"),H2=F0.join(r$,"async-subagent-runs"),U2=F0.join(r$,"chain-runs"),V2=F0.join(r$,"artifacts");var ij=250;var K2=2;function z2($){let j=typeof $==="number"?$:typeof $==="string"?Number($):NaN;if(!Number.isInteger(j)||j<0)return;return j}function I1($){return z2($)}function G2($){return I1(process.env.DM_SUBAGENT_MAX_DEPTH)??I1($)??K2}function rj($){let j=Number(process.env.DM_SUBAGENT_DEPTH??"0"),J=Number.isFinite(j)?j+1:1;return{DM_SUBAGENT_DEPTH:String(J),DM_SUBAGENT_MAX_DEPTH:String(I1($)??G2())}}function pj($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;return`${($/1048576).toFixed(1)}MB`}function sj($,j,J){let Z=$.split(`
1
+ import{spawn as D5,spawnSync as d8}from"node:child_process";import*as e from"node:fs";import*as r from"node:path";import{pathToFileURL as b5}from"node:url";import*as e8 from"node:fs";import*as K0 from"node:path";var $2=[10,25,50,100,200,500,1000,2000,4000],j2=new Set(["EACCES","EBUSY","EPERM"]),uj=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,lj=uj?new Int32Array(uj):void 0;function J2($){if($<=0)return;if(lj)try{Atomics.wait(lj,0,0,$);return}catch{}let j=Date.now()+$;while(Date.now()<j);}function Z2($){let j=$?.code;return typeof j==="string"&&j2.has(j)}function Q2($,j,J,Z,Q){for(let X=0;;X++)try{$.renameSync(j,J);return}catch(W){let U=Z[X];if(U===void 0||!Z2(W))throw W;Q(U)}}function X2($={}){let j=$.fs??e8,J=$.now??Date.now,Z=$.pid??process.pid,Q=$.random??Math.random,W=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??$2:[],U=$.wait??J2;return(G,B)=>{j.mkdirSync(K0.dirname(G),{recursive:!0});let q=K0.join(K0.dirname(G),`.${K0.basename(G)}.${Z}.${J()}.${Q().toString(36).slice(2)}.tmp`);try{j.writeFileSync(q,JSON.stringify(B,null,2),"utf-8"),Q2(j,q,G,W,U)}finally{j.rmSync(q,{force:!0})}}}var b$=X2();import*as U0 from"node:fs";import*as XJ from"node:path";import*as T$ from"node:fs";import*as b0 from"node:os";import*as h$ from"node:path";import*as J0 from"node:fs";import*as $1 from"node:path";import*as q0 from"node:os";import*as F0 from"node:path";var S0=1;var nj={bytes:204800,lines:5000};function a0($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Y2($){let j=$?.env??process.env,J=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof J==="function")return`uid-${J()}`;for(let W of["USERNAME","USER","LOGNAME"]){let U=j[W];if(U)return`user-${a0(U)}`}let Z=$&&Object.hasOwn($,"userInfo")?$.userInfo:q0.userInfo;try{let W=Z?.().username;if(W)return`user-${a0(W)}`}catch{}let Q=j.USERPROFILE??j.HOME;if(Q)return`home-${a0(Q)}`;let X=$&&Object.hasOwn($,"homedir")?$.homedir:q0.homedir;try{let W=X?.();if(W)return`home-${a0(W)}`}catch{}return"shared"}var r$=F0.join(q0.tmpdir(),`dm-subagents-${Y2()}`),W2=F0.join(r$,"async-subagent-results"),H2=F0.join(r$,"async-subagent-runs"),V2=F0.join(r$,"chain-runs"),K2=F0.join(r$,"artifacts");var ij=250;var U2=2;function z2($){let j=typeof $==="number"?$:typeof $==="string"?Number($):NaN;if(!Number.isInteger(j)||j<0)return;return j}function I1($){return z2($)}function G2($){return I1(process.env.DM_SUBAGENT_MAX_DEPTH)??I1($)??U2}function rj($){let j=Number(process.env.DM_SUBAGENT_DEPTH??"0"),J=Number.isFinite(j)?j+1:1;return{DM_SUBAGENT_DEPTH:String(J),DM_SUBAGENT_MAX_DEPTH:String(I1($)??G2())}}function pj($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;return`${($/1048576).toFixed(1)}MB`}function sj($,j,J){let Z=$.split(`
2
2
  `),Q=Buffer.byteLength($,"utf-8");if(Q<=j.bytes&&Z.length<=j.lines)return{text:$,truncated:!1};let X=Z;if(Z.length>j.lines)X=Z.slice(0,j.lines);let W=X.join(`
3
3
  `);if(Buffer.byteLength(W,"utf-8")>j.bytes){let B=0,q=W.length;while(B<q){let O=Math.floor((B+q+1)/2);if(Buffer.byteLength(W.slice(0,O),"utf-8")<=j.bytes)B=O;else q=O-1}W=W.slice(0,B)}return{text:`[TRUNCATED: showing first ${W.split(`
4
4
  `).length} of ${Z.length} lines, ${pj(Buffer.byteLength(W))} of ${pj(Q)}${J?` - full output at ${J}`:""}]
5
- `+W,truncated:!0,originalBytes:Q,originalLines:Z.length,artifactPath:J}}function $0($){return"parallel"in $&&Array.isArray($.parallel)}function j0($){return"expand"in $&&"collect"in $&&"parallel"in $&&!Array.isArray($.parallel)}function aj($){let j=[];for(let J of $)if($0(J))for(let Z of J.parallel)j.push(Z);else if(j0(J))continue;else j.push(J);return j}var tj=20;class y1{available;queue=[];constructor($){this.available=Math.max(1,Math.floor($)||1)}acquire(){if(this.available>0)return this.available--,Promise.resolve();return new Promise(($)=>{this.queue.push($)})}release(){let $=this.queue.shift();if($)$();else this.available++}}async function t0($,j,J,Z){let Q=Math.max(1,Math.floor(j)||1),X=Array($.length),W=0;async function K(G){while(W<$.length){let B=W++;if(Z){await Z.acquire();try{X[B]=await J($[B],B)}finally{Z.release()}}else X[B]=await J($[B],B)}}return await Promise.all(Array.from({length:Math.min(Q,$.length)},(G,B)=>K(B))),X}function e0($,j=(J,Z)=>`=== Parallel Task ${J+1} (${Z}) ===`){return $.map((J,Z)=>{let Q=j(J.taskIndex??Z,J.agent),X=Boolean(J.output?.trim()),W=J.timedOut?`TIMED OUT${J.error?`: ${J.error}`:""}`:J.exitCode===-1?"SKIPPED":J.exitCode!==0&&J.exitCode!==null?`FAILED (exit code ${J.exitCode})${J.error?`: ${J.error}`:""}`:J.error?`WARNING: ${J.error}`:!X&&J.outputTargetPath&&J.outputTargetExists===!1?`EMPTY OUTPUT (expected output file missing: ${J.outputTargetPath})`:!X&&!J.outputTargetPath?"EMPTY OUTPUT (no textual response returned)":"",K=W?X?`${W}
5
+ `+W,truncated:!0,originalBytes:Q,originalLines:Z.length,artifactPath:J}}function $0($){return"parallel"in $&&Array.isArray($.parallel)}function j0($){return"expand"in $&&"collect"in $&&"parallel"in $&&!Array.isArray($.parallel)}function aj($){let j=[];for(let J of $)if($0(J))for(let Z of J.parallel)j.push(Z);else if(j0(J))continue;else j.push(J);return j}var tj=20;class y1{available;queue=[];constructor($){this.available=Math.max(1,Math.floor($)||1)}acquire(){if(this.available>0)return this.available--,Promise.resolve();return new Promise(($)=>{this.queue.push($)})}release(){let $=this.queue.shift();if($)$();else this.available++}}async function t0($,j,J,Z){let Q=Math.max(1,Math.floor(j)||1),X=Array($.length),W=0;async function U(G){while(W<$.length){let B=W++;if(Z){await Z.acquire();try{X[B]=await J($[B],B)}finally{Z.release()}}else X[B]=await J($[B],B)}}return await Promise.all(Array.from({length:Math.min(Q,$.length)},(G,B)=>U(B))),X}function e0($,j=(J,Z)=>`=== Parallel Task ${J+1} (${Z}) ===`){return $.map((J,Z)=>{let Q=j(J.taskIndex??Z,J.agent),X=Boolean(J.output?.trim()),W=J.timedOut?`TIMED OUT${J.error?`: ${J.error}`:""}`:J.exitCode===-1?"SKIPPED":J.exitCode!==0&&J.exitCode!==null?`FAILED (exit code ${J.exitCode})${J.error?`: ${J.error}`:""}`:J.error?`WARNING: ${J.error}`:!X&&J.outputTargetPath&&J.outputTargetExists===!1?`EMPTY OUTPUT (expected output file missing: ${J.outputTargetPath})`:!X&&!J.outputTargetPath?"EMPTY OUTPUT (no textual response returned)":"",U=W?X?`${W}
6
6
  ${J.output}`:W:J.output;return`${Q}
7
- ${K}`}).join(`
7
+ ${U}`}).join(`
8
8
 
9
9
  `)}var k1=4;var B2=`# Progress
10
10
 
@@ -16,12 +16,12 @@ In Progress
16
16
  ## Files Changed
17
17
 
18
18
  ## Notes
19
- `;function ej($){J0.mkdirSync($,{recursive:!0}),J0.writeFileSync($1.join($,"progress.md"),B2)}var f1=["off","minimal","low","medium","high","xhigh"];function O0($,j){if(!$)return;let{thinkingSuffix:J}=P1($);if(J)return J.slice(1);return f1.find((Z)=>Z===j)}function P1($){let j=$.lastIndexOf(":");if(j===-1)return{baseModel:$,thinkingSuffix:""};let J=f1.find((Z)=>Z===$.substring(j+1));if(!J)return{baseModel:$,thinkingSuffix:""};return{baseModel:$.substring(0,j),thinkingSuffix:`:${J}`}}var L2=".dm",q2="@duckmind/dm-coding-agent",F2="DM_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT";function JJ($){return typeof $==="string"&&$.trim()?$:void 0}function $J($){if(!$)return;try{let j=JSON.parse(N$.readFileSync(h$.join($,"package.json"),"utf-8"));if(j.name!==q2)return;return JJ(j.piConfig?.configDir)}catch{return}}function O2($=process.argv[1],j=process.env[F2]){let J=$J(j);if(J)return J;if(!$)return;try{let Z=h$.dirname(N$.realpathSync($));while(Z!==h$.dirname(Z)){let Q=$J(Z);if(Q)return Q;Z=h$.dirname(Z)}}catch{}return}function A2($,j,J){return($&&typeof $==="object"?JJ($.CONFIG_DIR_NAME):void 0)??O2(j,J)??L2}function ZJ(){return A2()}function w1($){return h$.join($,ZJ())}function L0(){let $=process.env.DM_CODING_AGENT_DIR;if($==="~")return b0.homedir();if($?.startsWith("~/"))return h$.join(b0.homedir(),$.slice(2));return $||h$.join(b0.homedir(),ZJ(),"agent")}var D0=new Map;function x1($){return $ instanceof Error?$.message:String($)}function jJ($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function R0($){let j=h$.join($,"status.json"),J;try{J=N$.statSync(j)}catch(W){if(jJ(W))return null;throw Error(`Failed to inspect async status file '${j}': ${x1(W)}`,{cause:W instanceof Error?W:void 0})}let Z=D0.get(j);if(Z&&Z.mtime===J.mtimeMs)return Z.status;let Q;try{Q=N$.readFileSync(j,"utf-8")}catch(W){if(jJ(W))return null;throw Error(`Failed to read async status file '${j}': ${x1(W)}`,{cause:W instanceof Error?W:void 0})}let X;try{X=JSON.parse(Q)}catch(W){throw Error(`Failed to parse async status file '${j}': ${x1(W)}`,{cause:W instanceof Error?W:void 0})}if(D0.set(j,{mtime:J.mtimeMs,status:X}),D0.size>50){let W=D0.keys().next().value;if(W)D0.delete(W)}return X}function j1($){let j=[];for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.role!=="assistant")continue;if("errorMessage"in Z&&typeof Z.errorMessage==="string"&&Z.errorMessage.length>0||"stopReason"in Z&&Z.stopReason==="error")continue;for(let X=Z.content.length-1;X>=0;X--){let W=Z.content[X];if(W.type!=="text"||W.text.trim().length===0)continue;if(j.push(W.text),/```acceptance-report\s*\n[\s\S]*?```/i.test(W.text))return W.text;for(let K of W.text.matchAll(/```(?:json|jsonc|json5)\s*\n([\s\S]*?)```/gi)){let G=K[1]??"";if(/"criteriaSatisfied"/.test(G)&&/"(?:changedFiles|testsAddedOrUpdated|commandsRun|validationOutput|residualRisks|noStagedFiles|diffSummary|reviewFindings|manualNotes)"/.test(G))return W.text}if(/ACCEPTANCE_REPORT\s*:/i.test(W.text))return W.text}}return j[0]??""}function h1($){return $.finalOutput??j1($.messages??[])}function QJ($){let j=-1;for(let Z=$.length-1;Z>=0;Z--){let Q=$[Z];if(Q.role==="assistant"){if(Array.isArray(Q.content)&&Q.content.some((W)=>W.type==="text"&&("text"in W)&&typeof W.text==="string"&&W.text.trim().length>0)){j=Z;break}}}let J=j>=0?j+1:0;for(let Z=$.length-1;Z>=J;Z--){let Q=$[Z];if(Q.role!=="toolResult")continue;let X="toolName"in Q&&typeof Q.toolName==="string"?Q.toolName:void 0;if("isError"in Q&&Q.isError===!0){let O=Q.content.find((h)=>h.type==="text"),T=O&&"text"in O?O.text:void 0,y=T?.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);return{hasError:!0,exitCode:y?parseInt(y[1],10):1,errorType:X||"tool",details:T?.slice(0,200)}}if(X!=="bash")continue;let K=Q.content.find((O)=>O.type==="text");if(!K||!("text"in K))continue;let G=K.text,B=G.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);if(B){let O=parseInt(B[1],10);if(O!==0)return{hasError:!0,exitCode:O,errorType:"bash",details:G.slice(0,200)}}let q=[/command not found/i,/permission denied/i,/no such file or directory/i,/segmentation fault/i,/killed|terminated/i,/out of memory/i,/connection refused/i,/timeout/i];for(let O of q)if(O.test(G))return{hasError:!0,exitCode:1,errorType:"bash",details:G.slice(0,200)}}return{hasError:!1}}function w0($){let j=(K,G)=>K.length>G?`${K.slice(0,G-3)}...`:K,J=(K)=>{if(typeof K==="string"&&K.trim().length>0)return K;if(typeof K==="number"||typeof K==="boolean")return String(K);return},Z=(K)=>{if(!Array.isArray(K)||K.length===0)return;let G=J(K[0]);if(!G)return;let B=K.length>1?` (+${K.length-1} more)`:"";return`${G}${B}`};if($.tool&&typeof $.tool==="string"){let K=$.server&&typeof $.server==="string"?`${$.server}/`:"",G=$.args&&typeof $.args==="string"?` ${$.args.slice(0,40)}`:"";return`${K}${$.tool}${G}`}let Q=Z($.queries);if(Q)return j(Q,60);if(typeof $.query==="string"&&$.query.trim().length>0)return j($.query,60);if(typeof $.workflow==="string"&&$.workflow.trim().length>0)return`workflow=${j($.workflow,48)}`;if(typeof $.url==="string"&&$.url.trim().length>0)return j($.url,60);let X=Z($.urls);if(X)return j(X,60);if(typeof $.prompt==="string"&&$.prompt.trim().length>0)return j($.prompt,60);let W=["command","path","file_path","pattern","query","url","task","describe","search"];for(let K of W)if($[K]&&typeof $[K]==="string"){let G=$[K];return j(G,60)}for(let[K,G]of Object.entries($)){let B=Z(G);if(B)return`${K}=${j(B,50)}`;if(typeof G==="string"&&G.length>0){let q=j(G,50);return`${K}=${q}`}}return""}function s$($){if(!$)return"";if(typeof $==="string")return $;if(!Array.isArray($))return"";let j=[];for(let J of $)if(J&&typeof J==="object"){if("type"in J&&J.type==="text"&&"text"in J)j.push(String(J.text));else if("type"in J&&J.type==="tool_result"&&"content"in J){let Z=s$(J.content);if(Z)j.push(Z)}else if("text"in J)j.push(String(J.text))}return j.join(`
19
+ `;function ej($){J0.mkdirSync($,{recursive:!0}),J0.writeFileSync($1.join($,"progress.md"),B2)}var f1=["off","minimal","low","medium","high","xhigh"];function O0($,j){if(!$)return;let{thinkingSuffix:J}=P1($);if(J)return J.slice(1);return f1.find((Z)=>Z===j)}function P1($){let j=$.lastIndexOf(":");if(j===-1)return{baseModel:$,thinkingSuffix:""};let J=f1.find((Z)=>Z===$.substring(j+1));if(!J)return{baseModel:$,thinkingSuffix:""};return{baseModel:$.substring(0,j),thinkingSuffix:`:${J}`}}var L2=".dm",q2="@duckmind/dm-coding-agent",F2="DM_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT";function JJ($){return typeof $==="string"&&$.trim()?$:void 0}function $J($){if(!$)return;try{let j=JSON.parse(T$.readFileSync(h$.join($,"package.json"),"utf-8"));if(j.name!==q2)return;return JJ(j.piConfig?.configDir)}catch{return}}function O2($=process.argv[1],j=process.env[F2]){let J=$J(j);if(J)return J;if(!$)return;try{let Z=h$.dirname(T$.realpathSync($));while(Z!==h$.dirname(Z)){let Q=$J(Z);if(Q)return Q;Z=h$.dirname(Z)}}catch{}return}function A2($,j,J){return($&&typeof $==="object"?JJ($.CONFIG_DIR_NAME):void 0)??O2(j,J)??L2}function ZJ(){return A2()}function w1($){return h$.join($,ZJ())}function L0(){let $=process.env.DM_CODING_AGENT_DIR;if($==="~")return b0.homedir();if($?.startsWith("~/"))return h$.join(b0.homedir(),$.slice(2));return $||h$.join(b0.homedir(),ZJ(),"agent")}var D0=new Map;function x1($){return $ instanceof Error?$.message:String($)}function jJ($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function R0($){let j=h$.join($,"status.json"),J;try{J=T$.statSync(j)}catch(W){if(jJ(W))return null;throw Error(`Failed to inspect async status file '${j}': ${x1(W)}`,{cause:W instanceof Error?W:void 0})}let Z=D0.get(j);if(Z&&Z.mtime===J.mtimeMs)return Z.status;let Q;try{Q=T$.readFileSync(j,"utf-8")}catch(W){if(jJ(W))return null;throw Error(`Failed to read async status file '${j}': ${x1(W)}`,{cause:W instanceof Error?W:void 0})}let X;try{X=JSON.parse(Q)}catch(W){throw Error(`Failed to parse async status file '${j}': ${x1(W)}`,{cause:W instanceof Error?W:void 0})}if(D0.set(j,{mtime:J.mtimeMs,status:X}),D0.size>50){let W=D0.keys().next().value;if(W)D0.delete(W)}return X}function j1($){let j=[];for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.role!=="assistant")continue;if("errorMessage"in Z&&typeof Z.errorMessage==="string"&&Z.errorMessage.length>0||"stopReason"in Z&&Z.stopReason==="error")continue;for(let X=Z.content.length-1;X>=0;X--){let W=Z.content[X];if(W.type!=="text"||W.text.trim().length===0)continue;if(j.push(W.text),/```acceptance-report\s*\n[\s\S]*?```/i.test(W.text))return W.text;for(let U of W.text.matchAll(/```(?:json|jsonc|json5)\s*\n([\s\S]*?)```/gi)){let G=U[1]??"";if(/"criteriaSatisfied"/.test(G)&&/"(?:changedFiles|testsAddedOrUpdated|commandsRun|validationOutput|residualRisks|noStagedFiles|diffSummary|reviewFindings|manualNotes)"/.test(G))return W.text}if(/ACCEPTANCE_REPORT\s*:/i.test(W.text))return W.text}}return j[0]??""}function h1($){return $.finalOutput??j1($.messages??[])}function QJ($){let j=-1;for(let Z=$.length-1;Z>=0;Z--){let Q=$[Z];if(Q.role==="assistant"){if(Array.isArray(Q.content)&&Q.content.some((W)=>W.type==="text"&&("text"in W)&&typeof W.text==="string"&&W.text.trim().length>0)){j=Z;break}}}let J=j>=0?j+1:0;for(let Z=$.length-1;Z>=J;Z--){let Q=$[Z];if(Q.role!=="toolResult")continue;let X="toolName"in Q&&typeof Q.toolName==="string"?Q.toolName:void 0;if("isError"in Q&&Q.isError===!0){let O=Q.content.find((h)=>h.type==="text"),T=O&&"text"in O?O.text:void 0,y=T?.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);return{hasError:!0,exitCode:y?parseInt(y[1],10):1,errorType:X||"tool",details:T?.slice(0,200)}}if(X!=="bash")continue;let U=Q.content.find((O)=>O.type==="text");if(!U||!("text"in U))continue;let G=U.text,B=G.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);if(B){let O=parseInt(B[1],10);if(O!==0)return{hasError:!0,exitCode:O,errorType:"bash",details:G.slice(0,200)}}let q=[/command not found/i,/permission denied/i,/no such file or directory/i,/segmentation fault/i,/killed|terminated/i,/out of memory/i,/connection refused/i,/timeout/i];for(let O of q)if(O.test(G))return{hasError:!0,exitCode:1,errorType:"bash",details:G.slice(0,200)}}return{hasError:!1}}function w0($){let j=(U,G)=>U.length>G?`${U.slice(0,G-3)}...`:U,J=(U)=>{if(typeof U==="string"&&U.trim().length>0)return U;if(typeof U==="number"||typeof U==="boolean")return String(U);return},Z=(U)=>{if(!Array.isArray(U)||U.length===0)return;let G=J(U[0]);if(!G)return;let B=U.length>1?` (+${U.length-1} more)`:"";return`${G}${B}`};if($.tool&&typeof $.tool==="string"){let U=$.server&&typeof $.server==="string"?`${$.server}/`:"",G=$.args&&typeof $.args==="string"?` ${$.args.slice(0,40)}`:"";return`${U}${$.tool}${G}`}let Q=Z($.queries);if(Q)return j(Q,60);if(typeof $.query==="string"&&$.query.trim().length>0)return j($.query,60);if(typeof $.workflow==="string"&&$.workflow.trim().length>0)return`workflow=${j($.workflow,48)}`;if(typeof $.url==="string"&&$.url.trim().length>0)return j($.url,60);let X=Z($.urls);if(X)return j(X,60);if(typeof $.prompt==="string"&&$.prompt.trim().length>0)return j($.prompt,60);let W=["command","path","file_path","pattern","query","url","task","describe","search"];for(let U of W)if($[U]&&typeof $[U]==="string"){let G=$[U];return j(G,60)}for(let[U,G]of Object.entries($)){let B=Z(G);if(B)return`${U}=${j(B,50)}`;if(typeof G==="string"&&G.length>0){let q=j(G,50);return`${U}=${q}`}}return""}function s$($){if(!$)return"";if(typeof $==="string")return $;if(!Array.isArray($))return"";let j=[];for(let J of $)if(J&&typeof J==="object"){if("type"in J&&J.type==="text"&&"text"in J)j.push(String(J.text));else if("type"in J&&J.type==="tool_result"&&"content"in J){let Z=s$(J.content);if(Z)j.push(Z)}else if("text"in J)j.push(String(J.text))}return j.join(`
20
20
  `)}var N2=1,C2=52428800;function v1($){return $ instanceof Error?$.message:String($)}function Z0($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function T2($){if(!$||typeof $!=="object")return;let j=$,J=j.cost,Z=J&&typeof J==="object"?Z0(J.total)??0:Z0(J)??0;return{input:Z0(j.input)??Z0(j.inputTokens)??0,output:Z0(j.output)??Z0(j.outputTokens)??0,cacheRead:Z0(j.cacheRead)??0,cacheWrite:Z0(j.cacheWrite)??0,cost:Z}}function E2($){return $.args&&typeof $.args==="object"&&!Array.isArray($.args)?$.args:{}}function YJ($){let j=0,J,Z=!1,Q=$.maxBytes??C2,X=(B)=>{let q=Date.now();return{version:N2,recordType:B,source:$.source,runId:$.runId,agent:$.agent,...$.childIndex!==void 0?{childIndex:$.childIndex}:{},cwd:$.cwd,ts:q,timestamp:new Date(q).toISOString()}},W=()=>{Z=!0;let B=`${JSON.stringify({...X("truncated"),maxBytes:Q,message:`Child transcript exceeded ${Q} bytes; further records were omitted.`})}
21
- `,q=Buffer.byteLength(B,"utf-8");if(j+q>Q)return!1;try{return K0.appendFileSync($.transcriptPath,B,"utf-8"),j+=q,!0}catch(O){return J=`Failed to write child transcript '${$.transcriptPath}': ${v1(O)}`,!1}},K=(B)=>{if(J||Z)return;let q=`${JSON.stringify(B)}
21
+ `,q=Buffer.byteLength(B,"utf-8");if(j+q>Q)return!1;try{return U0.appendFileSync($.transcriptPath,B,"utf-8"),j+=q,!0}catch(O){return J=`Failed to write child transcript '${$.transcriptPath}': ${v1(O)}`,!1}},U=(B)=>{if(J||Z)return;let q=`${JSON.stringify(B)}
22
22
  `,O=Buffer.byteLength(q,"utf-8");if(j+O>Q){W();return}let T=`${JSON.stringify({...X("truncated"),maxBytes:Q,message:`Child transcript exceeded ${Q} bytes; further records were omitted.`})}
23
- `;if(j+O+Buffer.byteLength(T,"utf-8")>Q){W();return}try{K0.appendFileSync($.transcriptPath,q,"utf-8"),j+=O}catch(y){J=`Failed to write child transcript '${$.transcriptPath}': ${v1(y)}`}};try{K0.mkdirSync(XJ.dirname($.transcriptPath),{recursive:!0}),K0.writeFileSync($.transcriptPath,"","utf-8")}catch(B){J=`Failed to initialize child transcript '${$.transcriptPath}': ${v1(B)}`}let G=(B,q)=>{let O=s$(q.content);K({...X("message"),sourceEventType:B,role:q.role,...O?{text:O}:{},...q.model?{model:q.model}:{},...q.stopReason?{stopReason:q.stopReason}:{},...q.errorMessage?{errorMessage:q.errorMessage}:{},...q.usage?{usage:T2(q.usage)}:{},message:q})};return{path:$.transcriptPath,writeInitialUserMessage(B){K({...X("message"),sourceEventType:"initial_prompt",role:"user",text:B,message:{role:"user",content:[{type:"text",text:B}]}})},writeChildEvent(B){if((B.type==="message_end"||B.type==="tool_result_end")&&B.message){G(B.type,B.message);return}if(B.type==="tool_execution_start"&&B.toolName){let q=E2(B);K({...X("tool_start"),sourceEventType:B.type,toolName:B.toolName,...Object.keys(q).length>0?{argsPreview:w0(q)}:{}});return}if(B.type==="tool_execution_end")K({...X("tool_end"),sourceEventType:B.type,...B.toolName?{toolName:B.toolName}:{}})},writeStdoutLine(B){if(!B.trim())return;K({...X("stdout"),text:B})},writeStderrLine(B){if(!B.trim())return;K({...X("stderr"),text:B})},writeStderrText(B){for(let q of B.split(/\r?\n/))this.writeStderrLine(q)},getError(){return J}}}import*as z0 from"node:fs";import*as Q0 from"node:path";var S2=process.platform==="win32"?"SIGBREAK":"SIGUSR2",D2="steer-requests",b2="steer-targets";function I0($){return Q0.join($,"control")}function WJ($){return Q0.join(I0($),"interrupt.json")}function HJ($){return Q0.join(I0($),"timeout.json")}function R2($){return Q0.join(I0($),D2)}function y0($,j){return Q0.join(I0($),b2,String(j))}function w2($){return`${String($.ts).padStart(13,"0")}-${Buffer.from($.id).toString("base64url")}.json`}function I2($,j){let J=Q0.join($,w2(j));return D$(J,j),J}function y2($,j={},J={}){let Z=WJ($),Q={...j,ts:j.ts??J.now?.()??Date.now(),type:"interrupt"};return D$(Z,Q),Z}function k2($,j={},J={}){let Z=HJ($),Q={...j,ts:j.ts??J.now?.()??Date.now(),type:"timeout"};return D$(Z,Q),Z}function UJ($,j,J){if(!Number.isInteger(j)||j<0)throw Error("steer child index must be a non-negative integer.");return I2(y0($,j),{...J,targetIndex:j,type:"steer"})}function f2($){if(!$||typeof $!=="object"||Array.isArray($))return;let j=$;if(j.type!=="steer")return;if(typeof j.id!=="string"||!j.id.trim())return;if(typeof j.ts!=="number"||!Number.isFinite(j.ts))return;if(typeof j.message!=="string"||!j.message.trim())return;if(j.targetIndex!==void 0&&(!Number.isInteger(j.targetIndex)||j.targetIndex<0))return;return{type:"steer",id:j.id.trim(),ts:j.ts,message:j.message.trim(),...j.targetIndex!==void 0?{targetIndex:j.targetIndex}:{},...typeof j.source==="string"&&j.source.trim()?{source:j.source}:{}}}function P2($,j=z0){if(!j.existsSync($))return[];let J=[];for(let Z of j.readdirSync($).filter((Q)=>Q.endsWith(".json")).sort()){let Q=Q0.join($,Z),X;try{X=f2(JSON.parse(j.readFileSync(Q,"utf-8")))}catch{X=void 0}try{j.rmSync(Q,{recursive:!0})}catch{continue}if(X)J.push(X)}return J.sort((Z,Q)=>Z.ts-Q.ts||Z.id.localeCompare(Q.id))}function x2($,j=z0){return P2(R2($),j)}function g1($,j=z0){let J=WJ($);if(!j.existsSync(J))return!1;try{j.rmSync(J,{force:!0,recursive:!0})}catch{}return!0}function h2($,j=z0){let J=HJ($);if(!j.existsSync(J))return!1;try{j.rmSync(J,{force:!0,recursive:!0})}catch{}return!0}function VJ($){let j=y2($.asyncDir,$.source?{source:$.source}:{},{now:$.now});if(typeof $.pid==="number"&&$.pid>0)try{($.kill??process.kill)($.pid,$.signal??S2)}catch(J){if(J?.code==="ENOSYS")return;try{z0.rmSync(j,{force:!0})}catch{}throw J}}function m1($){k2($.asyncDir,$.source?{source:$.source}:{},{now:$.now})}function KJ($,j){let J=j.fs??z0,Z=j.timers??{setInterval,clearInterval},Q=I0($);try{J.mkdirSync(Q,{recursive:!0})}catch{}let X=!1,W=()=>{if(X)return;try{if(h2($,J))j.onTimeout?.();if(g1($,J))j.onInterrupt();for(let B of x2($,J))j.onSteer?.(B)}catch{}};W();let K;try{K=J.watch(Q,()=>W()),K.on?.("error",()=>{})}catch{K=void 0}let G=Z.setInterval(W,j.pollIntervalMs??ij);return G.unref?.(),()=>{if(X)return;X=!0;try{K?.close()}catch{}Z.clearInterval(G)}}import*as X0 from"node:fs";import*as G0 from"node:path";function c1($,j,J,Z){let Q=Z!==void 0?`_${Z}`:"",X=J.replace(/[^\w.-]/g,"_"),W=`${j}_${X}${Q}`;return{inputPath:G0.join($,`${W}_input.md`),outputPath:G0.join($,`${W}_output.md`),jsonlPath:G0.join($,`${W}.jsonl`),transcriptPath:G0.join($,`${W}_transcript.jsonl`),metadataPath:G0.join($,`${W}_meta.json`)}}function d1($,j){X0.appendFileSync($,`${j}
24
- `)}import*as Y0 from"node:fs";import*as C$ from"node:path";import{fileURLToPath as v2}from"node:url";var k0="@duckmind/dm-coding-agent",g2="DM_SUBAGENT_PI_BINARY";function o1($){let j=C$.dirname($);while(j!==C$.dirname(j)){let J=C$.join(j,"package.json");if(Y0.existsSync(J)){if(JSON.parse(Y0.readFileSync(J,"utf-8")).name===k0)return j}j=C$.dirname(j)}return}function u1(){return o1(v2(import.meta.resolve(k0)))}function m2(){try{let $=process.argv[1];return $?o1(Y0.realpathSync($)):void 0}catch{return}}function zJ($,j){if(!j($))return!1;return/\.(?:mjs|cjs|js)$/i.test($)}function c2($){return C$.isAbsolute($)?$:C$.resolve($)}function d2($={}){let j=$.existsSync??Y0.existsSync,J=$.readFileSync??((Q,X)=>Y0.readFileSync(Q,X)),Z=$.argv1??process.argv[1];if(Z){let Q=c2(Z);if(zJ(Q,j))return Q}try{let X=($.resolvePackageJson??(()=>{let q=$.piPackageRoot??m2();if(q)return C$.join(q,"package.json");let O=$.resolvePackageEntry?o1($.resolvePackageEntry()):u1();if(!O)throw Error(`Could not resolve ${k0} package root`);return C$.join(O,"package.json")}))(),K=JSON.parse(J(X,"utf-8")).bin,G=typeof K==="string"?K:K?.pi??Object.values(K??{})[0];if(!G)return;let B=C$.resolve(C$.dirname(X),G);if(zJ(B,j))return B}catch{return}return}function GJ($,j={}){let Z=(j.env??process.env)[g2]?.trim();if(Z)return{command:Z,args:$};if((j.platform??process.platform)==="win32"){let X=d2(j);if(X)return{command:j.execPath??process.execPath,args:[X,...$]}}return{command:"dm",args:$}}import*as a$ from"node:fs";import*as f0 from"node:path";function o2($){if(!$)return 0;return($.match(/\r\n|\r|\n/g)?.length??0)+(/[\r\n]$/.test($)?0:1)}function u2($){if($<1024)return`${$} B`;let j=["KB","MB","GB","TB"],J=$/1024,Z=0;while(J>=1024&&Z<j.length-1)J/=1024,Z++;return`${J.toFixed(1)} ${j[Z]}`}function l1($,j){let J=f0.resolve($),Z=Buffer.byteLength(j,"utf-8"),Q=o2(j);return{path:J,bytes:Z,lines:Q,message:`Output saved to: ${J} (${u2(Z)}, ${Q} ${Q===1?"line":"lines"}). Read this file if needed.`}}function BJ($){if(!$)return;try{let j=a$.statSync($);return{exists:!0,mtimeMs:j.mtimeMs,size:j.size}}catch{return{exists:!1}}}function l2($,j){if(!$)return{};try{return a$.mkdirSync(f0.dirname($),{recursive:!0}),a$.writeFileSync($,j,"utf-8"),{savedPath:$}}catch(J){return{error:J instanceof Error?J.message:String(J)}}}function _J($,j,J){if(!$)return{fullOutput:j};let Z=!1;try{let X=a$.statSync($);Z=!J?.exists||X.mtimeMs!==J.mtimeMs||X.size!==J.size}catch(X){let W=X&&typeof X==="object"&&"code"in X?X.code:void 0;if(W!=="ENOENT"&&W!=="ENOTDIR")return{fullOutput:j,saveError:`Failed to inspect output file: ${X instanceof Error?X.message:String(X)}`}}if(Z)try{return{fullOutput:a$.readFileSync($,"utf-8"),savedPath:$}}catch(X){return{fullOutput:j,saveError:`Failed to read changed output file: ${X instanceof Error?X.message:String(X)}`}}let Q=l2($,j);if(Q.savedPath)return{fullOutput:j,savedPath:Q.savedPath};return{fullOutput:j,saveError:Q.error}}function MJ($){let j=$.truncatedOutput||$.fullOutput;if($.exitCode===0&&$.savedPath){let J=$.outputReference??l1($.savedPath,$.fullOutput);if($.outputMode==="file-only")return{displayOutput:J.message,savedPath:$.savedPath,outputReference:J};return j+=`
23
+ `;if(j+O+Buffer.byteLength(T,"utf-8")>Q){W();return}try{U0.appendFileSync($.transcriptPath,q,"utf-8"),j+=O}catch(y){J=`Failed to write child transcript '${$.transcriptPath}': ${v1(y)}`}};try{U0.mkdirSync(XJ.dirname($.transcriptPath),{recursive:!0}),U0.writeFileSync($.transcriptPath,"","utf-8")}catch(B){J=`Failed to initialize child transcript '${$.transcriptPath}': ${v1(B)}`}let G=(B,q)=>{let O=s$(q.content);U({...X("message"),sourceEventType:B,role:q.role,...O?{text:O}:{},...q.model?{model:q.model}:{},...q.stopReason?{stopReason:q.stopReason}:{},...q.errorMessage?{errorMessage:q.errorMessage}:{},...q.usage?{usage:T2(q.usage)}:{},message:q})};return{path:$.transcriptPath,writeInitialUserMessage(B){U({...X("message"),sourceEventType:"initial_prompt",role:"user",text:B,message:{role:"user",content:[{type:"text",text:B}]}})},writeChildEvent(B){if((B.type==="message_end"||B.type==="tool_result_end")&&B.message){G(B.type,B.message);return}if(B.type==="tool_execution_start"&&B.toolName){let q=E2(B);U({...X("tool_start"),sourceEventType:B.type,toolName:B.toolName,...Object.keys(q).length>0?{argsPreview:w0(q)}:{}});return}if(B.type==="tool_execution_end")U({...X("tool_end"),sourceEventType:B.type,...B.toolName?{toolName:B.toolName}:{}})},writeStdoutLine(B){if(!B.trim())return;U({...X("stdout"),text:B})},writeStderrLine(B){if(!B.trim())return;U({...X("stderr"),text:B})},writeStderrText(B){for(let q of B.split(/\r?\n/))this.writeStderrLine(q)},getError(){return J}}}import*as z0 from"node:fs";import*as Q0 from"node:path";var S2=process.platform==="win32"?"SIGBREAK":"SIGUSR2",D2="steer-requests",b2="steer-targets";function I0($){return Q0.join($,"control")}function WJ($){return Q0.join(I0($),"interrupt.json")}function HJ($){return Q0.join(I0($),"timeout.json")}function R2($){return Q0.join(I0($),D2)}function y0($,j){return Q0.join(I0($),b2,String(j))}function w2($){return`${String($.ts).padStart(13,"0")}-${Buffer.from($.id).toString("base64url")}.json`}function I2($,j){let J=Q0.join($,w2(j));return b$(J,j),J}function y2($,j={},J={}){let Z=WJ($),Q={...j,ts:j.ts??J.now?.()??Date.now(),type:"interrupt"};return b$(Z,Q),Z}function k2($,j={},J={}){let Z=HJ($),Q={...j,ts:j.ts??J.now?.()??Date.now(),type:"timeout"};return b$(Z,Q),Z}function VJ($,j,J){if(!Number.isInteger(j)||j<0)throw Error("steer child index must be a non-negative integer.");return I2(y0($,j),{...J,targetIndex:j,type:"steer"})}function f2($){if(!$||typeof $!=="object"||Array.isArray($))return;let j=$;if(j.type!=="steer")return;if(typeof j.id!=="string"||!j.id.trim())return;if(typeof j.ts!=="number"||!Number.isFinite(j.ts))return;if(typeof j.message!=="string"||!j.message.trim())return;if(j.targetIndex!==void 0&&(!Number.isInteger(j.targetIndex)||j.targetIndex<0))return;return{type:"steer",id:j.id.trim(),ts:j.ts,message:j.message.trim(),...j.targetIndex!==void 0?{targetIndex:j.targetIndex}:{},...typeof j.source==="string"&&j.source.trim()?{source:j.source}:{}}}function P2($,j=z0){if(!j.existsSync($))return[];let J=[];for(let Z of j.readdirSync($).filter((Q)=>Q.endsWith(".json")).sort()){let Q=Q0.join($,Z),X;try{X=f2(JSON.parse(j.readFileSync(Q,"utf-8")))}catch{X=void 0}try{j.rmSync(Q,{recursive:!0})}catch{continue}if(X)J.push(X)}return J.sort((Z,Q)=>Z.ts-Q.ts||Z.id.localeCompare(Q.id))}function x2($,j=z0){return P2(R2($),j)}function g1($,j=z0){let J=WJ($);if(!j.existsSync(J))return!1;try{j.rmSync(J,{force:!0,recursive:!0})}catch{}return!0}function h2($,j=z0){let J=HJ($);if(!j.existsSync(J))return!1;try{j.rmSync(J,{force:!0,recursive:!0})}catch{}return!0}function KJ($){let j=y2($.asyncDir,$.source?{source:$.source}:{},{now:$.now});if(typeof $.pid==="number"&&$.pid>0)try{($.kill??process.kill)($.pid,$.signal??S2)}catch(J){if(J?.code==="ENOSYS")return;try{z0.rmSync(j,{force:!0})}catch{}throw J}}function m1($){k2($.asyncDir,$.source?{source:$.source}:{},{now:$.now})}function UJ($,j){let J=j.fs??z0,Z=j.timers??{setInterval,clearInterval},Q=I0($);try{J.mkdirSync(Q,{recursive:!0})}catch{}let X=!1,W=()=>{if(X)return;try{if(h2($,J))j.onTimeout?.();if(g1($,J))j.onInterrupt();for(let B of x2($,J))j.onSteer?.(B)}catch{}};W();let U;try{U=J.watch(Q,()=>W()),U.on?.("error",()=>{})}catch{U=void 0}let G=Z.setInterval(W,j.pollIntervalMs??ij);return G.unref?.(),()=>{if(X)return;X=!0;try{U?.close()}catch{}Z.clearInterval(G)}}import*as X0 from"node:fs";import*as G0 from"node:path";function c1($,j,J,Z){let Q=Z!==void 0?`_${Z}`:"",X=J.replace(/[^\w.-]/g,"_"),W=`${j}_${X}${Q}`;return{inputPath:G0.join($,`${W}_input.md`),outputPath:G0.join($,`${W}_output.md`),jsonlPath:G0.join($,`${W}.jsonl`),transcriptPath:G0.join($,`${W}_transcript.jsonl`),metadataPath:G0.join($,`${W}_meta.json`)}}function d1($,j){X0.appendFileSync($,`${j}
24
+ `)}import*as Y0 from"node:fs";import*as E$ from"node:path";import{fileURLToPath as v2}from"node:url";var k0="@duckmind/dm-coding-agent",g2="DM_SUBAGENT_PI_BINARY";function o1($){let j=E$.dirname($);while(j!==E$.dirname(j)){let J=E$.join(j,"package.json");if(Y0.existsSync(J)){if(JSON.parse(Y0.readFileSync(J,"utf-8")).name===k0)return j}j=E$.dirname(j)}return}function u1(){return o1(v2(import.meta.resolve(k0)))}function m2(){try{let $=process.argv[1];return $?o1(Y0.realpathSync($)):void 0}catch{return}}function zJ($,j){if(!j($))return!1;return/\.(?:mjs|cjs|js)$/i.test($)}function c2($){return E$.isAbsolute($)?$:E$.resolve($)}function d2($={}){let j=$.existsSync??Y0.existsSync,J=$.readFileSync??((Q,X)=>Y0.readFileSync(Q,X)),Z=$.argv1??process.argv[1];if(Z){let Q=c2(Z);if(zJ(Q,j))return Q}try{let X=($.resolvePackageJson??(()=>{let q=$.piPackageRoot??m2();if(q)return E$.join(q,"package.json");let O=$.resolvePackageEntry?o1($.resolvePackageEntry()):u1();if(!O)throw Error(`Could not resolve ${k0} package root`);return E$.join(O,"package.json")}))(),U=JSON.parse(J(X,"utf-8")).bin,G=typeof U==="string"?U:U?.pi??Object.values(U??{})[0];if(!G)return;let B=E$.resolve(E$.dirname(X),G);if(zJ(B,j))return B}catch{return}return}function GJ($,j={}){let Z=(j.env??process.env)[g2]?.trim();if(Z)return{command:Z,args:$};if((j.platform??process.platform)==="win32"){let X=d2(j);if(X)return{command:j.execPath??process.execPath,args:[X,...$]}}return{command:"dm",args:$}}import*as a$ from"node:fs";import*as f0 from"node:path";function o2($){if(!$)return 0;return($.match(/\r\n|\r|\n/g)?.length??0)+(/[\r\n]$/.test($)?0:1)}function u2($){if($<1024)return`${$} B`;let j=["KB","MB","GB","TB"],J=$/1024,Z=0;while(J>=1024&&Z<j.length-1)J/=1024,Z++;return`${J.toFixed(1)} ${j[Z]}`}function l1($,j){let J=f0.resolve($),Z=Buffer.byteLength(j,"utf-8"),Q=o2(j);return{path:J,bytes:Z,lines:Q,message:`Output saved to: ${J} (${u2(Z)}, ${Q} ${Q===1?"line":"lines"}). Read this file if needed.`}}function BJ($){if(!$)return;try{let j=a$.statSync($);return{exists:!0,mtimeMs:j.mtimeMs,size:j.size}}catch{return{exists:!1}}}function l2($,j){if(!$)return{};try{return a$.mkdirSync(f0.dirname($),{recursive:!0}),a$.writeFileSync($,j,"utf-8"),{savedPath:$}}catch(J){return{error:J instanceof Error?J.message:String(J)}}}function _J($,j,J){if(!$)return{fullOutput:j};let Z=!1;try{let X=a$.statSync($);Z=!J?.exists||X.mtimeMs!==J.mtimeMs||X.size!==J.size}catch(X){let W=X&&typeof X==="object"&&"code"in X?X.code:void 0;if(W!=="ENOENT"&&W!=="ENOTDIR")return{fullOutput:j,saveError:`Failed to inspect output file: ${X instanceof Error?X.message:String(X)}`}}if(Z)try{return{fullOutput:a$.readFileSync($,"utf-8"),savedPath:$}}catch(X){return{fullOutput:j,saveError:`Failed to read changed output file: ${X instanceof Error?X.message:String(X)}`}}let Q=l2($,j);if(Q.savedPath)return{fullOutput:j,savedPath:Q.savedPath};return{fullOutput:j,saveError:Q.error}}function MJ($){let j=$.truncatedOutput||$.fullOutput;if($.exitCode===0&&$.savedPath){let J=$.outputReference??l1($.savedPath,$.fullOutput);if($.outputMode==="file-only")return{displayOutput:J.message,savedPath:$.savedPath,outputReference:J};return j+=`
25
25
 
26
26
  ${J.message}`,{displayOutput:j,savedPath:$.savedPath,outputReference:J}}if($.exitCode===0&&$.saveError&&$.outputPath)return j+=`
27
27
 
@@ -30,49 +30,49 @@ ${$.saveError}`,{displayOutput:j,saveError:$.saveError};return{displayOutput:j}}
30
30
  `);let Z="What are you blocked on? Reply with the smallest next step or ask for a decision.",Q=`subagent({ action: "resume", id: "${J}", ${$.index!==void 0?`index: ${$.index}, `:""}message: "${Z}" })`;if($.type==="active_long_running"){let X=s2($);return[`Subagent active but long-running: ${$.agent}`,`Run: ${J}${$.index!==void 0?` step ${$.index+1}`:""}`,`Signal: ${$.message}`,X?`Facts: ${X}`:void 0,"Hint: Inspect status, then nudge if the work seems stuck. Live async nudges interrupt the child before sending the follow-up.",`Nudge: ${Q}`,j?`Direct intercom target: ${j}`:void 0,`Status: subagent({ action: "status", id: "${J}" })`,`Interrupt: subagent({ action: "interrupt", id: "${J}" })`].filter((W)=>Boolean(W)).join(`
31
31
  `)}return[`Subagent needs attention: ${$.agent}`,`Run: ${J}${$.index!==void 0?` step ${$.index+1}`:""}`,`Signal: ${$.message}`,$.recentFailureSummary?`Recent failures: ${$.recentFailureSummary}`:void 0,"Hint: Inspect status first unless the run is clearly blocked. Live async nudges interrupt the child before sending the follow-up.",`Nudge: ${Q}`,j?`Direct intercom target: ${j}`:void 0,`Status: subagent({ action: "status", id: "${J}" })`,`Interrupt: subagent({ action: "interrupt", id: "${J}" })`].filter((X)=>Boolean(X)).join(`
32
32
  `)}function OJ($,j){return[$.reason==="completion_guard"?"subagent failed":$.type==="active_long_running"?"subagent active but long-running":"subagent needs attention","",$.reason==="completion_guard"?`${$.agent} failed in run ${$.runId}.`:$.type==="active_long_running"?`${$.agent} is still active but long-running in run ${$.runId}.`:`${$.agent} needs attention in run ${$.runId}.`,"",p1($,j)].join(`
33
- `)}import*as b$ from"node:fs";import*as t1 from"node:os";import*as T$ from"node:path";import{fileURLToPath as dJ}from"node:url";import*as CJ from"node:path";var a2=128,t2=4;function n1($){return typeof $==="string"&&$.length>0&&$.length<=a2&&!CJ.isAbsolute($)&&!$.includes("/")&&!$.includes("\\")&&!$.includes("..")}function AJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function NJ($,j){return typeof $==="string"&&$.length>0?$.slice(0,j):void 0}function J1($){if(!Array.isArray($))return[];return $.map((j)=>{if(!j||typeof j!=="object")return;let J=j;if(!n1(J.runId))return;return{runId:J.runId,...AJ(J.stepIndex)!==void 0?{stepIndex:AJ(J.stepIndex)}:{},...NJ(J.agent,128)?{agent:NJ(J.agent,128)}:{}}}).filter((j)=>Boolean(j)).slice(0,t2)}function i1($){if(!$)return[];try{return J1(JSON.parse($))}catch{return[]}}function TJ($){let j=J1($);return j.length?JSON.stringify(j):""}import{createHash as e2}from"node:crypto";import*as N0 from"node:fs";import*as m$ from"node:os";import*as F$ from"node:path";var $6=1,j6=604800000,EJ=new Set(["read","bash","edit","write","grep","find","ls","mcp"]),SJ=F$.join(m$.homedir(),".config","mcp","mcp.json"),RJ={cursor:[F$.join(m$.homedir(),".cursor","mcp.json")],"claude-code":[F$.join(m$.homedir(),".claude","mcp.json"),F$.join(m$.homedir(),".claude.json"),F$.join(m$.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[F$.join(m$.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[F$.join(m$.homedir(),".codex","config.json")],windsurf:[F$.join(m$.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};function wJ($,j=process.cwd()){if(!$?.length)return[];try{let J=Z6(j),Z=J6();if(!Z)return[];return K6(J,Z,_6(J.settings?.toolPrefix),$)}catch{return[]}}function J6(){let $=F$.join(L0(),"mcp-cache.json"),j;try{j=JSON.parse(N0.readFileSync($,"utf-8"))}catch{return null}if(!j||typeof j!=="object")return null;let J=j;if(J.version!==$6||!J.servers||typeof J.servers!=="object"||Array.isArray(J.servers))return null;return J}function Z6($){let j={mcpServers:{}};for(let J of Q6($)){let Z=X6(J);if(!Z)continue;j=W6(j,H6(Z,$))}return j}function Q6($){let j=F$.join(L0(),"mcp.json"),J=F$.resolve($,".mcp.json"),Z=F$.resolve(w1($),"mcp.json"),Q=[];if(SJ!==j)Q.push(SJ);if(Q.push(j),J!==j)Q.push(J);if(Z!==j&&Z!==J)Q.push(Z);return Q}function X6($){let j;try{j=JSON.parse(N0.readFileSync($,"utf-8"))}catch{return null}return Y6(j)}function Y6($){if(!$||typeof $!=="object"||Array.isArray($))return{mcpServers:{}};let j=$,J=j.mcpServers??j["mcp-servers"]??{};return{mcpServers:J&&typeof J==="object"&&!Array.isArray(J)?J:{},imports:Array.isArray(j.imports)?j.imports.filter((Z)=>M6(Z)):void 0,settings:j.settings&&typeof j.settings==="object"&&!Array.isArray(j.settings)?j.settings:void 0}}function W6($,j){let J=[...$.imports??[],...j.imports??[]];return{mcpServers:{...$.mcpServers,...j.mcpServers},imports:J.length?[...new Set(J)]:void 0,settings:j.settings?{...$.settings,...j.settings}:$.settings}}function H6($,j){if(!$.imports?.length)return $;let J={};for(let Z of $.imports){let Q=U6(Z,j);if(!Q)continue;let X;try{X=JSON.parse(N0.readFileSync(Q,"utf-8"))}catch{continue}for(let[W,K]of Object.entries(V6(X,Z)))if(!J[W])J[W]=K}return{imports:$.imports,settings:$.settings,mcpServers:{...J,...$.mcpServers}}}function U6($,j){for(let J of RJ[$]){let Z=J.startsWith(".")?F$.resolve(j,J):J;if(N0.existsSync(Z))return Z}return null}function V6($,j){if(!$||typeof $!=="object"||Array.isArray($))return{};let J=$,Z=j==="cursor"||j==="windsurf"||j==="vscode"?J.mcpServers??J["mcp-servers"]:J.mcpServers;return Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:{}}function K6($,j,J,Z){let Q=[],X=new Set,{servers:W,tools:K}=z6(Z);for(let[G,B]of Object.entries($.mcpServers)){let q=j.servers[G];if(!G6(q,B))continue;let O=W.has(G)?!0:K.get(G);if(!O)continue;for(let T of Array.isArray(q.tools)?q.tools:[]){if(typeof T?.name!=="string"||!T.name)continue;if(O!==!0&&!O.has(T.name))continue;if(DJ(T.name,G,J,B.excludeTools))continue;let y=x0(T.name,G,J);if(EJ.has(y)||X.has(y))continue;X.add(y),Q.push(y)}if(B.exposeResources===!1)continue;for(let T of Array.isArray(q.resources)?q.resources:[]){if(typeof T?.name!=="string"||!T.name||typeof T.uri!=="string"||!T.uri)continue;let y=`get_${q6(T.name)}`;if(O!==!0&&!O.has(y))continue;if(DJ(y,G,J,B.excludeTools))continue;let h=x0(y,G,J);if(EJ.has(h)||X.has(h))continue;X.add(h),Q.push(h)}}return Q}function z6($){let j=new Set,J=new Map;for(let Z of $)if(Z=Z.replace(/\/+$/,""),Z.includes("/")){let[Q,X]=Z.split("/",2);if(Q&&X){if(!J.has(Q))J.set(Q,new Set);J.get(Q).add(X)}else if(Q)j.add(Q)}else if(Z)j.add(Z);return{servers:j,tools:J}}function G6($,j){if(!$||$.configHash!==B6(j))return!1;if(!$.cachedAt||typeof $.cachedAt!=="number")return!1;return Date.now()-$.cachedAt<=j6}function B6($){let j={command:$.command,args:$.args,env:bJ($.env),cwd:F6($.cwd),url:$.url,headers:bJ($.headers),auth:$.auth,bearerToken:O6($),bearerTokenEnv:$.bearerTokenEnv,exposeResources:$.exposeResources,excludeTools:$.excludeTools};return e2("sha256").update(r1(j)).digest("hex")}function _6($){return $==="none"||$==="short"||$==="server"?$:"server"}function M6($){return typeof $==="string"&&Object.hasOwn(RJ,$)}function L6($,j){if(j==="none")return"";if(j==="short")return $.replace(/-?mcp$/i,"").replace(/-/g,"_")||"mcp";return $.replace(/-/g,"_")}function x0($,j,J){let Z=L6(j,J);return Z?`${Z}_${$}`:$}function DJ($,j,J,Z){if(!Array.isArray(Z)||Z.length===0)return!1;let Q=new Set([P0($),P0(x0($,j,J)),P0(x0($,j,"server")),P0(x0($,j,"short"))]);return Z.some((X)=>typeof X==="string"&&Q.has(P0(X)))}function P0($){return $.replace(/-/g,"_")}function q6($){let j=$.replace(/[^a-zA-Z0-9]/g,"_").replace(/_+/g,"_").replace(/^_+/,"").replace(/_+$/,"").toLowerCase();if(!j||/^\d/.test(j))j=`resource${j?`_${j}`:""}`;return j}function bJ($){if(!$||typeof $!=="object"||Array.isArray($))return;let j={};for(let[J,Z]of Object.entries($))if(typeof Z==="string")j[J]=s1(Z);return j}function s1($){return $.replace(/\$\{(\w+)\}/g,(j,J)=>process.env[J]??"").replace(/\$env:(\w+)/g,(j,J)=>process.env[J]??"")}function F6($){if(typeof $!=="string")return;let j=s1($);if(j==="~")return m$.homedir();if(j.startsWith("~/")||j.startsWith("~\\"))return F$.join(m$.homedir(),j.slice(2));return j}function O6($){if(typeof $.bearerToken==="string")return s1($.bearerToken);return typeof $.bearerTokenEnv==="string"?process.env[$.bearerTokenEnv]:void 0}function r1($){if($===null||$===void 0||typeof $!=="object"){let J=JSON.stringify($);return J===void 0?"undefined":J}if(Array.isArray($))return`[${$.map((J)=>r1(J)).join(",")}]`;let j=$;return`{${Object.keys(j).sort().map((J)=>`${JSON.stringify(J)}:${r1(j[J])}`).join(",")}}`}import*as c$ from"node:fs";import*as IJ from"node:os";import*as h0 from"node:path";import{Compile as A6}from"typebox/compile";var yJ="DM_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA",kJ="DM_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";function N6($,j="outputSchema"){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`${j} must be a JSON Schema object.`)}function fJ($,j){N6($);let J=j??IJ.tmpdir();c$.mkdirSync(J,{recursive:!0});let Z=c$.mkdtempSync(h0.join(J,"dm-subagent-structured-")),Q=h0.join(Z,"schema.json"),X=h0.join(Z,"output.json");return c$.writeFileSync(Q,JSON.stringify($),{mode:384}),{schema:$,schemaPath:Q,outputPath:X}}function a1($,j){let J;try{J=A6($)}catch(Q){return{status:"invalid",message:`invalid outputSchema: ${Q instanceof Error?Q.message:String(Q)}`}}if(J.Check(j))return{status:"valid"};return{status:"invalid",message:[...J.Errors(j)].slice(0,8).map((Q)=>{return`${Q.instancePath?Q.instancePath.replace(/^\//,"").replace(/\//g,"."):"root"}: ${Q.message}`}).join("; ")||"schema validation failed"}}function PJ($){if(!c$.existsSync($.outputPath))return{error:"Missing structured_output call; this step has outputSchema and must finish by calling structured_output."};let j;try{j=JSON.parse(c$.readFileSync($.outputPath,"utf-8"))}catch(Z){return{error:`Failed to read structured output: ${Z instanceof Error?Z.message:String(Z)}`}}let J=a1($.schema,j);if(J.status==="invalid")return{error:`Structured output validation failed: ${J.message}`};return{value:j}}var xJ="DM_SUBAGENT_TOOL_BUDGET";function C0($){return{...$,toolCount:0,outcome:"within-budget"}}function Z1($,j,J){let Z=j>$.hard,Q=$.soft!==void 0&&j>=$.soft;return{...$,toolCount:j,outcome:Z?"hard-blocked":Q?"soft-reached":"within-budget",...Q?{softReachedAt:$.soft}:{},...Z?{hardReachedAt:$.hard,blockedTool:J}:{}}}function hJ($){return $?JSON.stringify($):void 0}var C6=["off","minimal","low","medium","high","xhigh"],T6=8000,vJ=T$.join(T$.dirname(dJ(import.meta.url)),"subagent-prompt-runtime.ts"),E6=T$.join(T$.dirname(dJ(import.meta.url)),"..","..","extension","fanout-child.ts"),S6="DM_SUBAGENT_CHILD",D6="DM_SUBAGENT_ORCHESTRATOR_TARGET",b6="DM_SUBAGENT_ORCHESTRATOR_SESSION_ID",R6="DM_SUBAGENT_SUPERVISOR_CHANNEL_DIR",gJ="DM_SUBAGENT_RUN_ID",w6="DM_SUBAGENT_CHILD_AGENT",I6="DM_SUBAGENT_CHILD_INDEX",y6="DM_SUBAGENT_FANOUT_CHILD",Q1="DM_SUBAGENT_PARENT_EVENT_SINK",e1="DM_SUBAGENT_PARENT_CONTROL_INBOX",X1="DM_SUBAGENT_PARENT_ROOT_RUN_ID",$j="DM_SUBAGENT_PARENT_RUN_ID",jj="DM_SUBAGENT_PARENT_CHILD_INDEX",Jj="DM_SUBAGENT_PARENT_DEPTH",Zj="DM_SUBAGENT_PARENT_PATH",Y1="DM_SUBAGENT_PARENT_CAPABILITY_TOKEN",mJ="DM_SUBAGENT_PARENT_SESSION",k6="DM_SUBAGENT_STEER_INBOX";function cJ($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function f6($,j,J){return T$.join(r$,"supervisor-channels",`${cJ($)}-${cJ(j)}-${J}`)}function W1($,j,J=!1){if(!$||!j)return $;let Z=$.lastIndexOf(":");if(Z!==-1&&C6.includes($.substring(Z+1)))return J?`${$.slice(0,Z)}:${j}`:$;return`${$}:${j}`}function oJ($){let j=[...$.baseArgs];if($.sessionFile)b$.mkdirSync(T$.dirname($.sessionFile),{recursive:!0}),j.push("--session",$.sessionFile);else{if(!$.sessionEnabled)j.push("--no-session");if($.sessionDir)b$.mkdirSync($.sessionDir,{recursive:!0}),j.push("--session-dir",$.sessionDir)}let J=W1($.model,$.thinking);if(J)j.push("--model",J);let Z=$.tools?.filter((k)=>!(k.includes("/")||k.endsWith(".ts")||k.endsWith(".js")))??[],Q=$.requireReadTool&&$.tools?.length&&!Z.includes("read")?["read",...Z]:Z,X=Q.includes("subagent"),W=[];if($.tools?.length){let k=[...Q];for(let f of $.tools)if(!Q.includes(f)&&(f.includes("/")||f.endsWith(".ts")||f.endsWith(".js")))W.push(f);if(k.length>0){if($.mcpDirectTools?.length)k.push(...wJ($.mcpDirectTools,$.cwd));j.push("--tools",k.join(","))}}let K=X?[vJ,E6]:[vJ];if($.extensions!==void 0){j.push("--no-extensions");for(let k of[...new Set([...K,...W,...$.extensions,...$.subagentOnlyExtensions??[]])])j.push("--extension",k)}else for(let k of[...new Set([...K,...W,...$.subagentOnlyExtensions??[]])])j.push("--extension",k);if(!$.inheritSkills)j.push("--no-skills");let G;if($.systemPrompt!==void 0&&$.systemPrompt!==null){G=b$.mkdtempSync(T$.join(t1.tmpdir(),"dm-subagent-"));let k=($.promptFileStem??"prompt").replace(/[^\w.-]/g,"_"),f=T$.join(G,`${k}.md`);b$.writeFileSync(f,$.systemPrompt,{mode:384}),j.push($.systemPromptMode==="replace"?"--system-prompt":"--append-system-prompt",f)}if($.task.length>T6){if(!G)G=b$.mkdtempSync(T$.join(t1.tmpdir(),"dm-subagent-"));let k=T$.join(G,"task.md");b$.writeFileSync(k,`Task: ${$.task}`,{mode:384}),j.push(`@${k}`)}else j.push(`Task: ${$.task}`);let B={};B[S6]="1",B[y6]=X?"1":"0";let q=Boolean(process.env[Q1]&&process.env[X1]&&process.env[Y1]),O=$.parentRunId??$.runId??(q?process.env[gJ]:void 0)??process.env[$j]??"",T=$.parentChildIndex!==void 0?String($.parentChildIndex):$.childIndex!==void 0?String($.childIndex):process.env[jj]??"",y=Number(process.env[Jj]),h=$.parentDepth??(q&&Number.isFinite(y)?y+1:1),S=$.parentPath??[...i1(process.env[Zj]),...O?[{runId:O,...T&&/^\d+$/.test(T)?{stepIndex:Number(T)}:{},...$.childAgentName?{agent:$.childAgentName}:{}}]:[]];if(B[Q1]=X?$.parentEventSink??process.env[Q1]??"":"",B[e1]=X?$.parentControlInbox??process.env[e1]??"":"",B[X1]=X?$.parentRootRunId??process.env[X1]??$.runId??"":"",B[$j]=X?O:"",B[jj]=X?T:"",B[Jj]=X?String(h):"",B[Zj]=X?TJ(S):"",B[Y1]=X?$.parentCapabilityToken??process.env[Y1]??"":"",B.DM_SUBAGENT_INHERIT_PROJECT_CONTEXT=$.inheritProjectContext?"1":"0",B.DM_SUBAGENT_INHERIT_SKILLS=$.inheritSkills?"1":"0",$.intercomSessionName)B.DM_SUBAGENT_INTERCOM_SESSION_NAME=$.intercomSessionName;if($.orchestratorIntercomTarget)B[D6]=$.orchestratorIntercomTarget;if($.parentSessionId)B[b6]=$.parentSessionId;if($.orchestratorIntercomTarget&&$.parentSessionId&&$.runId&&$.childAgentName){let k=$.childIndex??0,f=f6($.runId,$.childAgentName,k);b$.mkdirSync(T$.join(f,"requests"),{recursive:!0}),b$.mkdirSync(T$.join(f,"replies"),{recursive:!0}),B[R6]=f}if($.runId)B[gJ]=$.runId;if($.childAgentName)B[w6]=$.childAgentName;if($.childIndex!==void 0)B[I6]=String($.childIndex);if($.mcpDirectTools?.length)B.MCP_DIRECT_TOOLS=$.mcpDirectTools.join(",");else B.MCP_DIRECT_TOOLS="__none__";if($.structuredOutput)B[kJ]=$.structuredOutput.outputPath,B[yJ]=$.structuredOutput.schemaPath;if($.steerInboxDir)B[k6]=$.steerInboxDir;let v$=hJ($.toolBudget);if(v$)B[xJ]=v$;return B[mJ]=$.parentSessionId??process.env[mJ]??"",{args:j,env:B,tempDir:G}}function uJ($){if(!$)return;try{b$.rmSync($,{recursive:!0,force:!0})}catch{}}class x extends Error{}var P6=/^[A-Za-z_][A-Za-z0-9_]*$/,x6=/^[A-Za-z_][A-Za-z0-9_]*$/,g0=/\{([A-Za-z_][A-Za-z0-9_]*)(?:\.([^{}]+))?\}/g,h6=new Set(["task","previous","chain_dir","outputs"]),nJ=new Set(["expand","parallel","collect","concurrency","failFast","phase","label","acceptance"]),v6=new Set([...nJ,"effectiveAcceptance","sessionFiles","thinkingOverrides"]),g6=new Set(["from","item","key","maxItems","onEmpty"]),m6=new Set(["output","path"]),iJ=new Set(["agent","task","phase","label","outputSchema","cwd","output","outputMode","reads","progress","skill","model","toolBudget","acceptance"]),c6=new Set([...iJ,"outputName","structured","inheritProjectContext","inheritSkills","skills","outputPath","maxSubagentDepth","structuredOutput","structuredOutputSchema","tools","extensions","subagentOnlyExtensions","mcpDirectTools","completionGuard","systemPrompt","systemPromptMode","thinking","modelCandidates","sessionFile","effectiveAcceptance","parentSessionId"]),d6=new Set(["as","outputSchema"]);function lJ($){return P6.test($)}function Qj($,j){if($==="")return;if(!$.startsWith("/"))throw new x(`${j} must be a JSON Pointer starting with '/'.`);for(let J of $.slice(1).split("/"))if(/~(?![01])/.test(J))throw new x(`${j} contains invalid JSON Pointer escape.`)}function o6($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}function Xj($,j,J){if(Qj(j,J),j==="")return $;let Z=$;for(let Q of j.slice(1).split("/")){let X=o6(Q);if(Array.isArray(Z)){if(!/^(0|[1-9][0-9]*)$/.test(X))throw new x(`${J} segment '${X}' does not address an array index.`);let K=Number(X);if(K>=Z.length)throw new x(`${J} does not exist.`);Z=Z[K];continue}if(!Z||typeof Z!=="object")throw new x(`${J} does not exist.`);let W=Z;if(!Object.prototype.hasOwnProperty.call(W,X))throw new x(`${J} does not exist.`);Z=W[X]}return Z}function u6($,j){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"){let J=String($);if(!J.trim())throw new x(`${j} resolved to an empty key.`);if(/[\u0000-\u001F\u007F]/.test(J))throw new x(`${j} resolved to an unsafe key.`);if(J.length>200)throw new x(`${j} resolved to a key longer than 200 characters.`);return J}throw new x(`${j} must resolve to a string, number, or boolean.`)}function l6($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"item"}function p6($,j){if($===void 0)throw new x(`Unresolved item reference '${j}'.`);if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean"||$===null)return String($);return JSON.stringify($)}function n6($,j,J){if(!j)return $;let Z=`/${j.split(".").map((Q)=>Q.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`;return Xj($,Z,J)}function pJ($,j,J){return $.replace(g0,(Z,Q,X)=>{if(Q!==j)return Z;if(X!==void 0&&(!X.trim()||X.includes("..")))throw new x(`Invalid item reference '${Z}'.`);return p6(n6(J,X,Z),Z)})}function v0($,j,J){if(!$||typeof $!=="object"||Array.isArray($))throw new x(`${J} must be an object.`);for(let Z of Object.keys($))if(!j.has(Z))throw new x(`${J} does not support field '${Z}'.`)}function i6($,j,J){for(let Z of $.matchAll(/\{([^{}]*)\}/g)){let Q=Z[0],X=Z[1];if(X===j||X.startsWith(`${j}.`)){if(!g0.test(Q)||X===`${j}.`||X.includes(".."))throw new x(`Invalid item reference '${Q}' in ${J}.`);g0.lastIndex=0;continue}g0.lastIndex=0;let W=X.match(/^[A-Za-z_][A-Za-z0-9_]*/)?.[0];if(W===j)throw new x(`Invalid item reference '${Q}' in ${J}.`);if(W&&h6.has(W))continue;if(W)throw new x(`Unsupported template reference '${Q}' in ${J}.`)}if(g0.lastIndex=0,$.includes(`{${j}.}`)||new RegExp(`\\{${j}(?:\\.|$)[^}]*$`).test($))throw new x(`Invalid item reference in ${J}.`)}function rJ($,j,J={}){let Z=`Dynamic chain step ${j+1}`;if(v0($,J.allowRunnerFields?v6:nJ,Z),!$.expand||!$.expand.from)throw new x(`${Z} requires expand.from.`);if(v0($.expand,g6,`${Z} expand`),v0($.expand.from,m6,`${Z} expand.from`),!lJ($.expand.from.output))throw new x(`${Z} has invalid expand.from.output '${$.expand.from.output}'.`);if(Qj($.expand.from.path,`${Z} expand.from.path`),$.expand.key!==void 0)Qj($.expand.key,`${Z} expand.key`);let Q=$.expand.item??"item";if(!x6.test(Q))throw new x(`${Z} has invalid expand.item '${Q}'.`);if($.expand.maxItems===void 0&&J.maxItems===void 0)throw new x(`${Z} requires expand.maxItems or config.chain.dynamicFanout.maxItems.`);if($.expand.maxItems!==void 0&&(!Number.isInteger($.expand.maxItems)||$.expand.maxItems<0))throw new x(`${Z} expand.maxItems must be an integer >= 0.`);if(J.maxItems!==void 0&&(!Number.isInteger(J.maxItems)||J.maxItems<0))throw new x("config.chain.dynamicFanout.maxItems must be an integer >= 0.");if(!$.parallel||Array.isArray($.parallel))throw new x(`${Z} requires a single parallel template object and cannot mix dynamic expand/collect with static parallel arrays.`);if(v0($.parallel,J.allowRunnerFields?c6:iJ,`${Z} parallel`),"expand"in $.parallel)throw new x(`${Z} does not support nested dynamic fanout.`);if(!$.parallel.agent)throw new x(`${Z} parallel.agent is required.`);if(!$.collect?.as||!lJ($.collect.as))throw new x(`${Z} requires collect.as with a safe output name.`);v0($.collect,d6,`${Z} collect`);for(let[X,W]of[["parallel.task",$.parallel.task],["parallel.label",$.parallel.label]])if(W)i6(W,Q,`${Z} ${X}`)}function r6($,j,J,Z={}){rJ($,J,Z);let Q=$.expand.from.output,X=j[Q];if(!X)throw new x(`Dynamic chain step ${J+1} references unknown output '${Q}'.`);if(X.structured===void 0)throw new x(`Dynamic chain step ${J+1} requires structured output '${Q}'.`);let W=Xj(X.structured,$.expand.from.path,`Dynamic chain step ${J+1} expand.from.path`);if(!Array.isArray(W))throw new x(`Dynamic chain step ${J+1} expand.from.path must resolve to an array.`);let K=$.expand.maxItems??Z.maxItems;if(K===void 0)throw new x(`Dynamic chain step ${J+1} requires an effective maxItems.`);if(W.length>K)throw new x(`Dynamic chain step ${J+1} resolved ${W.length} items, exceeding maxItems ${K}.`);let G=new Set,B=new Set;return W.map((q,O)=>{let T=$.expand.key===void 0?String(O):u6(Xj(q,$.expand.key,`Dynamic chain step ${J+1} expand.key`),`Dynamic chain step ${J+1} expand.key`);if(G.has(T))throw new x(`Dynamic chain step ${J+1} produced duplicate item key '${T}'.`);G.add(T);let y=l6(T);if(B.has(y))throw new x(`Dynamic chain step ${J+1} produced colliding item id '${y}'.`);return B.add(y),{index:O,key:T,idKey:y,item:q}})}function sJ($,j,J,Z={}){let Q=r6($,j,J,Z);if(Q.length===0){if(($.expand.onEmpty??"skip")==="fail")throw new x(`Dynamic chain step ${J+1} source array is empty.`);return{items:Q,parallel:[],collectedOnEmpty:[]}}let X=$.expand.item??"item",W=Q.map((K)=>{let G=pJ($.parallel.task??"{previous}",X,K.item),B=$.parallel.label?pJ($.parallel.label,X,K.item):void 0;return{...$.parallel,task:G,...B!==void 0?{label:B}:{}}});return{items:Q,parallel:W}}function aJ($,j,J){return j.map((Z,Q)=>{let X=J[Q],W=X?"output"in X&&typeof X.output==="string"?X.output:h1(X):"";return{key:Z.key,index:Z.index,item:Z.item,agent:X?.agent??$.parallel.agent,exitCode:X?.exitCode??null,text:W,...X?.structuredOutput!==void 0?{structured:X.structuredOutput}:{},...X?.error?{error:X.error}:{},...X?.timedOut?{timedOut:!0}:{},...X?.savedOutputPath?{outputPath:X.savedOutputPath}:{},...X?.artifactPaths?{artifactPaths:X.artifactPaths}:{}}})}function Yj($,j){if(!$)return;let J=a1($,j);if(J.status==="invalid")throw new x(`Collected output validation failed: ${J.message}`)}var s6=/\{outputs\.([^}]*)\}/g,a6=/^[A-Za-z_][A-Za-z0-9_]*$/;class Wj extends Error{}function tJ($,j){return $.replace(s6,(J,Z)=>{if(!a6.test(Z))throw new Wj(`Invalid chain output reference '${J}'. Use {outputs.name} with /^[A-Za-z_][A-Za-z0-9_]*$/ names.`);let Q=j[Z];if(!Q)throw new Wj(`Unknown chain output reference '${J}'.`);return Q.text})}function t6($){return JSON.stringify($)}function Hj($,j){return{text:$.structuredOutput!==void 0?t6($.structuredOutput):$.output,...$.structuredOutput!==void 0?{structured:$.structuredOutput}:{},agent:$.agent,stepIndex:j}}import{randomUUID as e6}from"node:crypto";import*as R$ from"node:fs";import*as Q$ from"node:path";var eJ=Q$.join(r$,"nested-subagent-events");var $4="registry.json",Gj=65536,Uj=12,U1=16,Vj=3;function V1($){return n1($)}function j4($,j){if(!V1(j))throw Error(`${$} must be a non-empty safe id token.`)}function $8($,j){j4($,j)}function Kj($,j){let J=Q$.resolve($),Z=Q$.resolve(j);return Z===J||Z.startsWith(`${J}${Q$.sep}`)}function J8($){return Q$.dirname(Q$.resolve($.eventSink))}function Bj($){if($8("rootRunId",$.rootRunId),$8("capabilityToken",$.capabilityToken),!Kj(eJ,$.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!Kj(eJ,$.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(J8($)!==Q$.dirname(Q$.resolve($.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function _j($,j){if(!j.asyncDir)return;let J=Q$.resolve(j.asyncDir),Z=Q$.resolve(r$,"nested-subagent-runs",$,j.id),Q=Q$.relative(Z,J);return J===Z||!Q.startsWith("..")&&!Q$.isAbsolute(Q)?J:void 0}function b($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function m($,j=512){return typeof $==="string"&&$.length>0?$.slice(0,j):void 0}function J4($){if(!$||typeof $!=="object")return;let j=$,J=b(j.input),Z=b(j.output),Q=b(j.total);return J!==void 0&&Z!==void 0&&Q!==void 0?{input:J,output:Z,total:Q}:void 0}function Z4($){if(!$||typeof $!=="object")return;let j=$,J=b(j.inputTokens),Z=b(j.outputTokens),Q=b(j.costUsd);return J!==void 0&&Z!==void 0&&Q!==void 0?{inputTokens:J,outputTokens:Z,costUsd:Q}:void 0}function K1($){if(!$||typeof $!=="object")return;let j=$,J=b(j.maxTurns),Z=b(j.graceTurns),Q=b(j.turnCount),X=j.outcome==="within-budget"||j.outcome==="wrap-up-requested"||j.outcome==="exceeded"?j.outcome:void 0;if(J===void 0||Z===void 0||Q===void 0||!X)return;return{maxTurns:J,graceTurns:Z,turnCount:Q,outcome:X,...b(j.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:b(j.wrapUpRequestedAtTurn)}:{},...b(j.exceededAtTurn)!==void 0?{exceededAtTurn:b(j.exceededAtTurn)}:{}}}function Q4($,j){return $==="queued"||$==="running"||$==="complete"||$==="failed"||$==="paused"?$:j}function X4($,j){if(!$||typeof $!=="object")return;let J=$,Z=m(J.agent,128);if(!Z)return;let Q=J.status==="pending"||J.status==="running"||J.status==="complete"||J.status==="completed"||J.status==="failed"||J.status==="paused"?J.status:"pending";return{agent:Z,status:Q,...m(J.sessionFile,2048)?{sessionFile:m(J.sessionFile,2048)}:{},...J.activityState==="active_long_running"||J.activityState==="needs_attention"?{activityState:J.activityState}:{},...b(J.lastActivityAt)!==void 0?{lastActivityAt:b(J.lastActivityAt)}:{},...m(J.currentTool,128)?{currentTool:m(J.currentTool,128)}:{},...b(J.currentToolStartedAt)!==void 0?{currentToolStartedAt:b(J.currentToolStartedAt)}:{},...m(J.currentPath,2048)?{currentPath:m(J.currentPath,2048)}:{},...b(J.turnCount)!==void 0?{turnCount:b(J.turnCount)}:{},...b(J.toolCount)!==void 0?{toolCount:b(J.toolCount)}:{},...b(J.startedAt)!==void 0?{startedAt:b(J.startedAt)}:{},...b(J.endedAt)!==void 0?{endedAt:b(J.endedAt)}:{},...m(J.error,1024)?{error:m(J.error,1024)}:{},...J.timedOut===!0?{timedOut:!0}:{},...K1(J.turnBudget)?{turnBudget:K1(J.turnBudget)}:{},...J.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...J.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...j<Vj&&Array.isArray(J.children)?{children:J.children.map((X)=>z1(X,j+1)).filter((X)=>Boolean(X)).slice(0,U1)}:{}}}function z1($,j=0){if(!$||typeof $!=="object")return;let J=$;if(!V1(J.id)||!V1(J.parentRunId))return;let Z=J1(J.path),Q=Array.isArray(J.steps)?J.steps.map((K)=>X4(K,j+1)).filter((K)=>Boolean(K)).slice(0,Uj):void 0,X=J4(J.totalTokens),W=Z4(J.totalCost);return{id:J.id,parentRunId:J.parentRunId,...b(J.parentStepIndex)!==void 0?{parentStepIndex:b(J.parentStepIndex)}:{},...m(J.parentAgent,128)?{parentAgent:m(J.parentAgent,128)}:{},depth:Math.min(Math.max(0,b(J.depth)??0),Vj),path:Z,state:Q4(J.state,"running"),...m(J.asyncDir,2048)?{asyncDir:m(J.asyncDir,2048)}:{},...b(J.pid)!==void 0&&b(J.pid)>0&&Number.isInteger(b(J.pid))?{pid:b(J.pid)}:{},...m(J.sessionId,256)?{sessionId:m(J.sessionId,256)}:{},...m(J.sessionFile,2048)?{sessionFile:m(J.sessionFile,2048)}:{},...m(J.intercomTarget,256)?{intercomTarget:m(J.intercomTarget,256)}:{},...m(J.ownerIntercomTarget,256)?{ownerIntercomTarget:m(J.ownerIntercomTarget,256)}:{},...m(J.leafIntercomTarget,256)?{leafIntercomTarget:m(J.leafIntercomTarget,256)}:{},...J.ownerState==="live"||J.ownerState==="gone"||J.ownerState==="unknown"?{ownerState:J.ownerState}:{},...m(J.controlInbox,2048)?{controlInbox:m(J.controlInbox,2048)}:{},...m(J.capabilityToken,128)?{capabilityToken:m(J.capabilityToken,128)}:{},...J.mode==="single"||J.mode==="parallel"||J.mode==="chain"?{mode:J.mode}:{},...m(J.agent,128)?{agent:m(J.agent,128)}:{},...Array.isArray(J.agents)?{agents:J.agents.map((K)=>m(K,128)).filter((K)=>Boolean(K)).slice(0,Uj)}:{},...b(J.currentStep)!==void 0?{currentStep:b(J.currentStep)}:{},...b(J.chainStepCount)!==void 0?{chainStepCount:b(J.chainStepCount)}:{},...J.activityState==="active_long_running"||J.activityState==="needs_attention"?{activityState:J.activityState}:{},...b(J.lastActivityAt)!==void 0?{lastActivityAt:b(J.lastActivityAt)}:{},...m(J.currentTool,128)?{currentTool:m(J.currentTool,128)}:{},...b(J.currentToolStartedAt)!==void 0?{currentToolStartedAt:b(J.currentToolStartedAt)}:{},...m(J.currentPath,2048)?{currentPath:m(J.currentPath,2048)}:{},...b(J.turnCount)!==void 0?{turnCount:b(J.turnCount)}:{},...b(J.toolCount)!==void 0?{toolCount:b(J.toolCount)}:{},...X?{totalTokens:X}:{},...W?{totalCost:W}:{},...b(J.startedAt)!==void 0?{startedAt:b(J.startedAt)}:{},...b(J.endedAt)!==void 0?{endedAt:b(J.endedAt)}:{},...b(J.lastUpdate)!==void 0?{lastUpdate:b(J.lastUpdate)}:{},...b(J.timeoutMs)!==void 0?{timeoutMs:b(J.timeoutMs)}:{},...b(J.deadlineAt)!==void 0?{deadlineAt:b(J.deadlineAt)}:{},...J.timedOut===!0?{timedOut:!0}:{},...K1(J.turnBudget)?{turnBudget:K1(J.turnBudget)}:{},...J.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...J.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...m(J.error,1024)?{error:m(J.error,1024)}:{},...Q&&Q.length>0?{steps:Q}:{},...j<Vj&&Array.isArray(J.children)?{children:J.children.map((K)=>z1(K,j+1)).filter((K)=>Boolean(K)).slice(0,U1)}:{}}}function zj($,j){if(Buffer.byteLength($,"utf-8")>Gj)return;let J;try{J=JSON.parse($)}catch{return}if(!J||typeof J!=="object")return;let Z=J;if(Z.type!=="subagent.nested.started"&&Z.type!=="subagent.nested.updated"&&Z.type!=="subagent.nested.completed")return;if(Z.rootRunId!==j.rootRunId||Z.capabilityToken!==j.capabilityToken)return;if(!V1(Z.parentRunId))return;let Q=b(Z.ts);if(Q===void 0)return;let X=z1(Z.child);if(!X||X.id===j.rootRunId)return;let W={...X,controlInbox:j.controlInbox,capabilityToken:j.capabilityToken,ownerState:X.ownerState??"unknown"};return{type:Z.type,ts:Q,rootRunId:j.rootRunId,parentRunId:Z.parentRunId,...b(Z.parentStepIndex)!==void 0?{parentStepIndex:b(Z.parentStepIndex)}:{},capabilityToken:j.capabilityToken,child:W}}function Y4($,j){if(!$.includes(`
33
+ `)}import*as C$ from"node:fs";import*as t1 from"node:os";import*as B$ from"node:path";import{fileURLToPath as C6}from"node:url";import*as CJ from"node:path";var a2=128,t2=4;function n1($){return typeof $==="string"&&$.length>0&&$.length<=a2&&!CJ.isAbsolute($)&&!$.includes("/")&&!$.includes("\\")&&!$.includes("..")}function AJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function NJ($,j){return typeof $==="string"&&$.length>0?$.slice(0,j):void 0}function J1($){if(!Array.isArray($))return[];return $.map((j)=>{if(!j||typeof j!=="object")return;let J=j;if(!n1(J.runId))return;return{runId:J.runId,...AJ(J.stepIndex)!==void 0?{stepIndex:AJ(J.stepIndex)}:{},...NJ(J.agent,128)?{agent:NJ(J.agent,128)}:{}}}).filter((j)=>Boolean(j)).slice(0,t2)}function i1($){if(!$)return[];try{return J1(JSON.parse($))}catch{return[]}}function TJ($){let j=J1($);return j.length?JSON.stringify(j):""}import{createHash as e2}from"node:crypto";import*as N0 from"node:fs";import*as m$ from"node:os";import*as O$ from"node:path";var $6=1,j6=604800000,EJ=new Set(["read","bash","edit","write","grep","find","ls","mcp"]),SJ=O$.join(m$.homedir(),".config","mcp","mcp.json"),RJ={cursor:[O$.join(m$.homedir(),".cursor","mcp.json")],"claude-code":[O$.join(m$.homedir(),".claude","mcp.json"),O$.join(m$.homedir(),".claude.json"),O$.join(m$.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[O$.join(m$.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[O$.join(m$.homedir(),".codex","config.json")],windsurf:[O$.join(m$.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};function wJ($,j=process.cwd()){if(!$?.length)return[];try{let J=Z6(j),Z=J6();if(!Z)return[];return U6(J,Z,_6(J.settings?.toolPrefix),$)}catch{return[]}}function J6(){let $=O$.join(L0(),"mcp-cache.json"),j;try{j=JSON.parse(N0.readFileSync($,"utf-8"))}catch{return null}if(!j||typeof j!=="object")return null;let J=j;if(J.version!==$6||!J.servers||typeof J.servers!=="object"||Array.isArray(J.servers))return null;return J}function Z6($){let j={mcpServers:{}};for(let J of Q6($)){let Z=X6(J);if(!Z)continue;j=W6(j,H6(Z,$))}return j}function Q6($){let j=O$.join(L0(),"mcp.json"),J=O$.resolve($,".mcp.json"),Z=O$.resolve(w1($),"mcp.json"),Q=[];if(SJ!==j)Q.push(SJ);if(Q.push(j),J!==j)Q.push(J);if(Z!==j&&Z!==J)Q.push(Z);return Q}function X6($){let j;try{j=JSON.parse(N0.readFileSync($,"utf-8"))}catch{return null}return Y6(j)}function Y6($){if(!$||typeof $!=="object"||Array.isArray($))return{mcpServers:{}};let j=$,J=j.mcpServers??j["mcp-servers"]??{};return{mcpServers:J&&typeof J==="object"&&!Array.isArray(J)?J:{},imports:Array.isArray(j.imports)?j.imports.filter((Z)=>M6(Z)):void 0,settings:j.settings&&typeof j.settings==="object"&&!Array.isArray(j.settings)?j.settings:void 0}}function W6($,j){let J=[...$.imports??[],...j.imports??[]];return{mcpServers:{...$.mcpServers,...j.mcpServers},imports:J.length?[...new Set(J)]:void 0,settings:j.settings?{...$.settings,...j.settings}:$.settings}}function H6($,j){if(!$.imports?.length)return $;let J={};for(let Z of $.imports){let Q=V6(Z,j);if(!Q)continue;let X;try{X=JSON.parse(N0.readFileSync(Q,"utf-8"))}catch{continue}for(let[W,U]of Object.entries(K6(X,Z)))if(!J[W])J[W]=U}return{imports:$.imports,settings:$.settings,mcpServers:{...J,...$.mcpServers}}}function V6($,j){for(let J of RJ[$]){let Z=J.startsWith(".")?O$.resolve(j,J):J;if(N0.existsSync(Z))return Z}return null}function K6($,j){if(!$||typeof $!=="object"||Array.isArray($))return{};let J=$,Z=j==="cursor"||j==="windsurf"||j==="vscode"?J.mcpServers??J["mcp-servers"]:J.mcpServers;return Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:{}}function U6($,j,J,Z){let Q=[],X=new Set,{servers:W,tools:U}=z6(Z);for(let[G,B]of Object.entries($.mcpServers)){let q=j.servers[G];if(!G6(q,B))continue;let O=W.has(G)?!0:U.get(G);if(!O)continue;for(let T of Array.isArray(q.tools)?q.tools:[]){if(typeof T?.name!=="string"||!T.name)continue;if(O!==!0&&!O.has(T.name))continue;if(DJ(T.name,G,J,B.excludeTools))continue;let y=x0(T.name,G,J);if(EJ.has(y)||X.has(y))continue;X.add(y),Q.push(y)}if(B.exposeResources===!1)continue;for(let T of Array.isArray(q.resources)?q.resources:[]){if(typeof T?.name!=="string"||!T.name||typeof T.uri!=="string"||!T.uri)continue;let y=`get_${q6(T.name)}`;if(O!==!0&&!O.has(y))continue;if(DJ(y,G,J,B.excludeTools))continue;let h=x0(y,G,J);if(EJ.has(h)||X.has(h))continue;X.add(h),Q.push(h)}}return Q}function z6($){let j=new Set,J=new Map;for(let Z of $)if(Z=Z.replace(/\/+$/,""),Z.includes("/")){let[Q,X]=Z.split("/",2);if(Q&&X){if(!J.has(Q))J.set(Q,new Set);J.get(Q).add(X)}else if(Q)j.add(Q)}else if(Z)j.add(Z);return{servers:j,tools:J}}function G6($,j){if(!$||$.configHash!==B6(j))return!1;if(!$.cachedAt||typeof $.cachedAt!=="number")return!1;return Date.now()-$.cachedAt<=j6}function B6($){let j={command:$.command,args:$.args,env:bJ($.env),cwd:F6($.cwd),url:$.url,headers:bJ($.headers),auth:$.auth,bearerToken:O6($),bearerTokenEnv:$.bearerTokenEnv,exposeResources:$.exposeResources,excludeTools:$.excludeTools};return e2("sha256").update(r1(j)).digest("hex")}function _6($){return $==="none"||$==="short"||$==="server"?$:"server"}function M6($){return typeof $==="string"&&Object.hasOwn(RJ,$)}function L6($,j){if(j==="none")return"";if(j==="short")return $.replace(/-?mcp$/i,"").replace(/-/g,"_")||"mcp";return $.replace(/-/g,"_")}function x0($,j,J){let Z=L6(j,J);return Z?`${Z}_${$}`:$}function DJ($,j,J,Z){if(!Array.isArray(Z)||Z.length===0)return!1;let Q=new Set([P0($),P0(x0($,j,J)),P0(x0($,j,"server")),P0(x0($,j,"short"))]);return Z.some((X)=>typeof X==="string"&&Q.has(P0(X)))}function P0($){return $.replace(/-/g,"_")}function q6($){let j=$.replace(/[^a-zA-Z0-9]/g,"_").replace(/_+/g,"_").replace(/^_+/,"").replace(/_+$/,"").toLowerCase();if(!j||/^\d/.test(j))j=`resource${j?`_${j}`:""}`;return j}function bJ($){if(!$||typeof $!=="object"||Array.isArray($))return;let j={};for(let[J,Z]of Object.entries($))if(typeof Z==="string")j[J]=s1(Z);return j}function s1($){return $.replace(/\$\{(\w+)\}/g,(j,J)=>process.env[J]??"").replace(/\$env:(\w+)/g,(j,J)=>process.env[J]??"")}function F6($){if(typeof $!=="string")return;let j=s1($);if(j==="~")return m$.homedir();if(j.startsWith("~/")||j.startsWith("~\\"))return O$.join(m$.homedir(),j.slice(2));return j}function O6($){if(typeof $.bearerToken==="string")return s1($.bearerToken);return typeof $.bearerTokenEnv==="string"?process.env[$.bearerTokenEnv]:void 0}function r1($){if($===null||$===void 0||typeof $!=="object"){let J=JSON.stringify($);return J===void 0?"undefined":J}if(Array.isArray($))return`[${$.map((J)=>r1(J)).join(",")}]`;let j=$;return`{${Object.keys(j).sort().map((J)=>`${JSON.stringify(J)}:${r1(j[J])}`).join(",")}}`}import*as c$ from"node:fs";import*as IJ from"node:os";import*as h0 from"node:path";import{Compile as A6}from"typebox/compile";var yJ="DM_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA",kJ="DM_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";function N6($,j="outputSchema"){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`${j} must be a JSON Schema object.`)}function fJ($,j){N6($);let J=j??IJ.tmpdir();c$.mkdirSync(J,{recursive:!0});let Z=c$.mkdtempSync(h0.join(J,"dm-subagent-structured-")),Q=h0.join(Z,"schema.json"),X=h0.join(Z,"output.json");return c$.writeFileSync(Q,JSON.stringify($),{mode:384}),{schema:$,schemaPath:Q,outputPath:X}}function a1($,j){let J;try{J=A6($)}catch(Q){return{status:"invalid",message:`invalid outputSchema: ${Q instanceof Error?Q.message:String(Q)}`}}if(J.Check(j))return{status:"valid"};return{status:"invalid",message:[...J.Errors(j)].slice(0,8).map((Q)=>{return`${Q.instancePath?Q.instancePath.replace(/^\//,"").replace(/\//g,"."):"root"}: ${Q.message}`}).join("; ")||"schema validation failed"}}function PJ($){if(!c$.existsSync($.outputPath))return{error:"Missing structured_output call; this step has outputSchema and must finish by calling structured_output."};let j;try{j=JSON.parse(c$.readFileSync($.outputPath,"utf-8"))}catch(Z){return{error:`Failed to read structured output: ${Z instanceof Error?Z.message:String(Z)}`}}let J=a1($.schema,j);if(J.status==="invalid")return{error:`Structured output validation failed: ${J.message}`};return{value:j}}var xJ="DM_SUBAGENT_TOOL_BUDGET";function C0($){return{...$,toolCount:0,outcome:"within-budget"}}function Z1($,j,J){let Z=j>$.hard,Q=$.soft!==void 0&&j>=$.soft;return{...$,toolCount:j,outcome:Z?"hard-blocked":Q?"soft-reached":"within-budget",...Q?{softReachedAt:$.soft}:{},...Z?{hardReachedAt:$.hard,blockedTool:J}:{}}}function hJ($){return $?JSON.stringify($):void 0}var T6=["off","minimal","low","medium","high","xhigh"],E6=8000;function dJ($,j){let J=C6($),Z=B$.extname(J),Q=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(Z)?Z:".ts",X=B$.dirname(J);while(!C$.existsSync(B$.join(X,"package.json"))){let W=B$.dirname(X);if(W===X)throw Error(`Unable to resolve dm-subagents package root from ${J}`);X=W}return B$.join(X,`${j}${Q}`)}var vJ=dJ(import.meta.url,B$.join("src","runs","shared","subagent-prompt-runtime")),S6=dJ(import.meta.url,B$.join("src","extension","fanout-child")),D6="DM_SUBAGENT_CHILD",b6="DM_SUBAGENT_ORCHESTRATOR_TARGET",R6="DM_SUBAGENT_ORCHESTRATOR_SESSION_ID",w6="DM_SUBAGENT_SUPERVISOR_CHANNEL_DIR",gJ="DM_SUBAGENT_RUN_ID",I6="DM_SUBAGENT_CHILD_AGENT",y6="DM_SUBAGENT_CHILD_INDEX",k6="DM_SUBAGENT_FANOUT_CHILD",Q1="DM_SUBAGENT_PARENT_EVENT_SINK",e1="DM_SUBAGENT_PARENT_CONTROL_INBOX",X1="DM_SUBAGENT_PARENT_ROOT_RUN_ID",$j="DM_SUBAGENT_PARENT_RUN_ID",jj="DM_SUBAGENT_PARENT_CHILD_INDEX",Jj="DM_SUBAGENT_PARENT_DEPTH",Zj="DM_SUBAGENT_PARENT_PATH",Y1="DM_SUBAGENT_PARENT_CAPABILITY_TOKEN",mJ="DM_SUBAGENT_PARENT_SESSION",f6="DM_SUBAGENT_STEER_INBOX";function cJ($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function P6($,j,J){return B$.join(r$,"supervisor-channels",`${cJ($)}-${cJ(j)}-${J}`)}function W1($,j,J=!1){if(!$||!j)return $;let Z=$.lastIndexOf(":");if(Z!==-1&&T6.includes($.substring(Z+1)))return J?`${$.slice(0,Z)}:${j}`:$;return`${$}:${j}`}function oJ($){let j=[...$.baseArgs];if($.sessionFile)C$.mkdirSync(B$.dirname($.sessionFile),{recursive:!0}),j.push("--session",$.sessionFile);else{if(!$.sessionEnabled)j.push("--no-session");if($.sessionDir)C$.mkdirSync($.sessionDir,{recursive:!0}),j.push("--session-dir",$.sessionDir)}let J=W1($.model,$.thinking);if(J)j.push("--model",J);let Z=$.tools?.filter((k)=>!(k.includes("/")||k.endsWith(".ts")||k.endsWith(".js")))??[],Q=$.requireReadTool&&$.tools?.length&&!Z.includes("read")?["read",...Z]:Z,X=Q.includes("subagent"),W=[];if($.tools?.length){let k=[...Q];for(let f of $.tools)if(!Q.includes(f)&&(f.includes("/")||f.endsWith(".ts")||f.endsWith(".js")))W.push(f);if(k.length>0){if($.mcpDirectTools?.length)k.push(...wJ($.mcpDirectTools,$.cwd));j.push("--tools",k.join(","))}}let U=X?[vJ,S6]:[vJ];if($.extensions!==void 0){j.push("--no-extensions");for(let k of[...new Set([...U,...W,...$.extensions,...$.subagentOnlyExtensions??[]])])j.push("--extension",k)}else for(let k of[...new Set([...U,...W,...$.subagentOnlyExtensions??[]])])j.push("--extension",k);if(!$.inheritSkills)j.push("--no-skills");let G;if($.systemPrompt!==void 0&&$.systemPrompt!==null){G=C$.mkdtempSync(B$.join(t1.tmpdir(),"dm-subagent-"));let k=($.promptFileStem??"prompt").replace(/[^\w.-]/g,"_"),f=B$.join(G,`${k}.md`);C$.writeFileSync(f,$.systemPrompt,{mode:384}),j.push($.systemPromptMode==="replace"?"--system-prompt":"--append-system-prompt",f)}if($.task.length>E6){if(!G)G=C$.mkdtempSync(B$.join(t1.tmpdir(),"dm-subagent-"));let k=B$.join(G,"task.md");C$.writeFileSync(k,`Task: ${$.task}`,{mode:384}),j.push(`@${k}`)}else j.push(`Task: ${$.task}`);let B={};B[D6]="1",B[k6]=X?"1":"0";let q=Boolean(process.env[Q1]&&process.env[X1]&&process.env[Y1]),O=$.parentRunId??$.runId??(q?process.env[gJ]:void 0)??process.env[$j]??"",T=$.parentChildIndex!==void 0?String($.parentChildIndex):$.childIndex!==void 0?String($.childIndex):process.env[jj]??"",y=Number(process.env[Jj]),h=$.parentDepth??(q&&Number.isFinite(y)?y+1:1),S=$.parentPath??[...i1(process.env[Zj]),...O?[{runId:O,...T&&/^\d+$/.test(T)?{stepIndex:Number(T)}:{},...$.childAgentName?{agent:$.childAgentName}:{}}]:[]];if(B[Q1]=X?$.parentEventSink??process.env[Q1]??"":"",B[e1]=X?$.parentControlInbox??process.env[e1]??"":"",B[X1]=X?$.parentRootRunId??process.env[X1]??$.runId??"":"",B[$j]=X?O:"",B[jj]=X?T:"",B[Jj]=X?String(h):"",B[Zj]=X?TJ(S):"",B[Y1]=X?$.parentCapabilityToken??process.env[Y1]??"":"",B.DM_SUBAGENT_INHERIT_PROJECT_CONTEXT=$.inheritProjectContext?"1":"0",B.DM_SUBAGENT_INHERIT_SKILLS=$.inheritSkills?"1":"0",$.intercomSessionName)B.DM_SUBAGENT_INTERCOM_SESSION_NAME=$.intercomSessionName;if($.orchestratorIntercomTarget)B[b6]=$.orchestratorIntercomTarget;if($.parentSessionId)B[R6]=$.parentSessionId;if($.orchestratorIntercomTarget&&$.parentSessionId&&$.runId&&$.childAgentName){let k=$.childIndex??0,f=P6($.runId,$.childAgentName,k);C$.mkdirSync(B$.join(f,"requests"),{recursive:!0}),C$.mkdirSync(B$.join(f,"replies"),{recursive:!0}),B[w6]=f}if($.runId)B[gJ]=$.runId;if($.childAgentName)B[I6]=$.childAgentName;if($.childIndex!==void 0)B[y6]=String($.childIndex);if($.mcpDirectTools?.length)B.MCP_DIRECT_TOOLS=$.mcpDirectTools.join(",");else B.MCP_DIRECT_TOOLS="__none__";if($.structuredOutput)B[kJ]=$.structuredOutput.outputPath,B[yJ]=$.structuredOutput.schemaPath;if($.steerInboxDir)B[f6]=$.steerInboxDir;let v$=hJ($.toolBudget);if(v$)B[xJ]=v$;return B[mJ]=$.parentSessionId??process.env[mJ]??"",{args:j,env:B,tempDir:G}}function uJ($){if(!$)return;try{C$.rmSync($,{recursive:!0,force:!0})}catch{}}class x extends Error{}var x6=/^[A-Za-z_][A-Za-z0-9_]*$/,h6=/^[A-Za-z_][A-Za-z0-9_]*$/,g0=/\{([A-Za-z_][A-Za-z0-9_]*)(?:\.([^{}]+))?\}/g,v6=new Set(["task","previous","chain_dir","outputs"]),nJ=new Set(["expand","parallel","collect","concurrency","failFast","phase","label","acceptance"]),g6=new Set([...nJ,"effectiveAcceptance","sessionFiles","thinkingOverrides"]),m6=new Set(["from","item","key","maxItems","onEmpty"]),c6=new Set(["output","path"]),iJ=new Set(["agent","task","phase","label","outputSchema","cwd","output","outputMode","reads","progress","skill","model","toolBudget","acceptance"]),d6=new Set([...iJ,"outputName","structured","inheritProjectContext","inheritSkills","skills","outputPath","maxSubagentDepth","structuredOutput","structuredOutputSchema","tools","extensions","subagentOnlyExtensions","mcpDirectTools","completionGuard","systemPrompt","systemPromptMode","thinking","modelCandidates","sessionFile","effectiveAcceptance","parentSessionId"]),o6=new Set(["as","outputSchema"]);function lJ($){return x6.test($)}function Qj($,j){if($==="")return;if(!$.startsWith("/"))throw new x(`${j} must be a JSON Pointer starting with '/'.`);for(let J of $.slice(1).split("/"))if(/~(?![01])/.test(J))throw new x(`${j} contains invalid JSON Pointer escape.`)}function u6($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}function Xj($,j,J){if(Qj(j,J),j==="")return $;let Z=$;for(let Q of j.slice(1).split("/")){let X=u6(Q);if(Array.isArray(Z)){if(!/^(0|[1-9][0-9]*)$/.test(X))throw new x(`${J} segment '${X}' does not address an array index.`);let U=Number(X);if(U>=Z.length)throw new x(`${J} does not exist.`);Z=Z[U];continue}if(!Z||typeof Z!=="object")throw new x(`${J} does not exist.`);let W=Z;if(!Object.prototype.hasOwnProperty.call(W,X))throw new x(`${J} does not exist.`);Z=W[X]}return Z}function l6($,j){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"){let J=String($);if(!J.trim())throw new x(`${j} resolved to an empty key.`);if(/[\u0000-\u001F\u007F]/.test(J))throw new x(`${j} resolved to an unsafe key.`);if(J.length>200)throw new x(`${j} resolved to a key longer than 200 characters.`);return J}throw new x(`${j} must resolve to a string, number, or boolean.`)}function p6($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"item"}function n6($,j){if($===void 0)throw new x(`Unresolved item reference '${j}'.`);if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="boolean"||$===null)return String($);return JSON.stringify($)}function i6($,j,J){if(!j)return $;let Z=`/${j.split(".").map((Q)=>Q.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}`;return Xj($,Z,J)}function pJ($,j,J){return $.replace(g0,(Z,Q,X)=>{if(Q!==j)return Z;if(X!==void 0&&(!X.trim()||X.includes("..")))throw new x(`Invalid item reference '${Z}'.`);return n6(i6(J,X,Z),Z)})}function v0($,j,J){if(!$||typeof $!=="object"||Array.isArray($))throw new x(`${J} must be an object.`);for(let Z of Object.keys($))if(!j.has(Z))throw new x(`${J} does not support field '${Z}'.`)}function r6($,j,J){for(let Z of $.matchAll(/\{([^{}]*)\}/g)){let Q=Z[0],X=Z[1];if(X===j||X.startsWith(`${j}.`)){if(!g0.test(Q)||X===`${j}.`||X.includes(".."))throw new x(`Invalid item reference '${Q}' in ${J}.`);g0.lastIndex=0;continue}g0.lastIndex=0;let W=X.match(/^[A-Za-z_][A-Za-z0-9_]*/)?.[0];if(W===j)throw new x(`Invalid item reference '${Q}' in ${J}.`);if(W&&v6.has(W))continue;if(W)throw new x(`Unsupported template reference '${Q}' in ${J}.`)}if(g0.lastIndex=0,$.includes(`{${j}.}`)||new RegExp(`\\{${j}(?:\\.|$)[^}]*$`).test($))throw new x(`Invalid item reference in ${J}.`)}function rJ($,j,J={}){let Z=`Dynamic chain step ${j+1}`;if(v0($,J.allowRunnerFields?g6:nJ,Z),!$.expand||!$.expand.from)throw new x(`${Z} requires expand.from.`);if(v0($.expand,m6,`${Z} expand`),v0($.expand.from,c6,`${Z} expand.from`),!lJ($.expand.from.output))throw new x(`${Z} has invalid expand.from.output '${$.expand.from.output}'.`);if(Qj($.expand.from.path,`${Z} expand.from.path`),$.expand.key!==void 0)Qj($.expand.key,`${Z} expand.key`);let Q=$.expand.item??"item";if(!h6.test(Q))throw new x(`${Z} has invalid expand.item '${Q}'.`);if($.expand.maxItems===void 0&&J.maxItems===void 0)throw new x(`${Z} requires expand.maxItems or config.chain.dynamicFanout.maxItems.`);if($.expand.maxItems!==void 0&&(!Number.isInteger($.expand.maxItems)||$.expand.maxItems<0))throw new x(`${Z} expand.maxItems must be an integer >= 0.`);if(J.maxItems!==void 0&&(!Number.isInteger(J.maxItems)||J.maxItems<0))throw new x("config.chain.dynamicFanout.maxItems must be an integer >= 0.");if(!$.parallel||Array.isArray($.parallel))throw new x(`${Z} requires a single parallel template object and cannot mix dynamic expand/collect with static parallel arrays.`);if(v0($.parallel,J.allowRunnerFields?d6:iJ,`${Z} parallel`),"expand"in $.parallel)throw new x(`${Z} does not support nested dynamic fanout.`);if(!$.parallel.agent)throw new x(`${Z} parallel.agent is required.`);if(!$.collect?.as||!lJ($.collect.as))throw new x(`${Z} requires collect.as with a safe output name.`);v0($.collect,o6,`${Z} collect`);for(let[X,W]of[["parallel.task",$.parallel.task],["parallel.label",$.parallel.label]])if(W)r6(W,Q,`${Z} ${X}`)}function s6($,j,J,Z={}){rJ($,J,Z);let Q=$.expand.from.output,X=j[Q];if(!X)throw new x(`Dynamic chain step ${J+1} references unknown output '${Q}'.`);if(X.structured===void 0)throw new x(`Dynamic chain step ${J+1} requires structured output '${Q}'.`);let W=Xj(X.structured,$.expand.from.path,`Dynamic chain step ${J+1} expand.from.path`);if(!Array.isArray(W))throw new x(`Dynamic chain step ${J+1} expand.from.path must resolve to an array.`);let U=$.expand.maxItems??Z.maxItems;if(U===void 0)throw new x(`Dynamic chain step ${J+1} requires an effective maxItems.`);if(W.length>U)throw new x(`Dynamic chain step ${J+1} resolved ${W.length} items, exceeding maxItems ${U}.`);let G=new Set,B=new Set;return W.map((q,O)=>{let T=$.expand.key===void 0?String(O):l6(Xj(q,$.expand.key,`Dynamic chain step ${J+1} expand.key`),`Dynamic chain step ${J+1} expand.key`);if(G.has(T))throw new x(`Dynamic chain step ${J+1} produced duplicate item key '${T}'.`);G.add(T);let y=p6(T);if(B.has(y))throw new x(`Dynamic chain step ${J+1} produced colliding item id '${y}'.`);return B.add(y),{index:O,key:T,idKey:y,item:q}})}function sJ($,j,J,Z={}){let Q=s6($,j,J,Z);if(Q.length===0){if(($.expand.onEmpty??"skip")==="fail")throw new x(`Dynamic chain step ${J+1} source array is empty.`);return{items:Q,parallel:[],collectedOnEmpty:[]}}let X=$.expand.item??"item",W=Q.map((U)=>{let G=pJ($.parallel.task??"{previous}",X,U.item),B=$.parallel.label?pJ($.parallel.label,X,U.item):void 0;return{...$.parallel,task:G,...B!==void 0?{label:B}:{}}});return{items:Q,parallel:W}}function aJ($,j,J){return j.map((Z,Q)=>{let X=J[Q],W=X?"output"in X&&typeof X.output==="string"?X.output:h1(X):"";return{key:Z.key,index:Z.index,item:Z.item,agent:X?.agent??$.parallel.agent,exitCode:X?.exitCode??null,text:W,...X?.structuredOutput!==void 0?{structured:X.structuredOutput}:{},...X?.error?{error:X.error}:{},...X?.timedOut?{timedOut:!0}:{},...X?.savedOutputPath?{outputPath:X.savedOutputPath}:{},...X?.artifactPaths?{artifactPaths:X.artifactPaths}:{}}})}function Yj($,j){if(!$)return;let J=a1($,j);if(J.status==="invalid")throw new x(`Collected output validation failed: ${J.message}`)}var a6=/\{outputs\.([^}]*)\}/g,t6=/^[A-Za-z_][A-Za-z0-9_]*$/;class Wj extends Error{}function tJ($,j){return $.replace(a6,(J,Z)=>{if(!t6.test(Z))throw new Wj(`Invalid chain output reference '${J}'. Use {outputs.name} with /^[A-Za-z_][A-Za-z0-9_]*$/ names.`);let Q=j[Z];if(!Q)throw new Wj(`Unknown chain output reference '${J}'.`);return Q.text})}function e6($){return JSON.stringify($)}function Hj($,j){return{text:$.structuredOutput!==void 0?e6($.structuredOutput):$.output,...$.structuredOutput!==void 0?{structured:$.structuredOutput}:{},agent:$.agent,stepIndex:j}}import{randomUUID as $4}from"node:crypto";import*as R$ from"node:fs";import*as Q$ from"node:path";var eJ=Q$.join(r$,"nested-subagent-events");var j4="registry.json",Gj=65536,Vj=12,V1=16,Kj=3;function K1($){return n1($)}function J4($,j){if(!K1(j))throw Error(`${$} must be a non-empty safe id token.`)}function $8($,j){J4($,j)}function Uj($,j){let J=Q$.resolve($),Z=Q$.resolve(j);return Z===J||Z.startsWith(`${J}${Q$.sep}`)}function J8($){return Q$.dirname(Q$.resolve($.eventSink))}function Bj($){if($8("rootRunId",$.rootRunId),$8("capabilityToken",$.capabilityToken),!Uj(eJ,$.eventSink))throw Error("Nested event sink is outside the subagent nested event root.");if(!Uj(eJ,$.controlInbox))throw Error("Nested control inbox is outside the subagent nested event root.");if(J8($)!==Q$.dirname(Q$.resolve($.controlInbox)))throw Error("Nested event sink and control inbox must share one route root.")}function _j($,j){if(!j.asyncDir)return;let J=Q$.resolve(j.asyncDir),Z=Q$.resolve(r$,"nested-subagent-runs",$,j.id),Q=Q$.relative(Z,J);return J===Z||!Q.startsWith("..")&&!Q$.isAbsolute(Q)?J:void 0}function b($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function m($,j=512){return typeof $==="string"&&$.length>0?$.slice(0,j):void 0}function Z4($){if(!$||typeof $!=="object")return;let j=$,J=b(j.input),Z=b(j.output),Q=b(j.total);return J!==void 0&&Z!==void 0&&Q!==void 0?{input:J,output:Z,total:Q}:void 0}function Q4($){if(!$||typeof $!=="object")return;let j=$,J=b(j.inputTokens),Z=b(j.outputTokens),Q=b(j.costUsd);return J!==void 0&&Z!==void 0&&Q!==void 0?{inputTokens:J,outputTokens:Z,costUsd:Q}:void 0}function U1($){if(!$||typeof $!=="object")return;let j=$,J=b(j.maxTurns),Z=b(j.graceTurns),Q=b(j.turnCount),X=j.outcome==="within-budget"||j.outcome==="wrap-up-requested"||j.outcome==="exceeded"?j.outcome:void 0;if(J===void 0||Z===void 0||Q===void 0||!X)return;return{maxTurns:J,graceTurns:Z,turnCount:Q,outcome:X,...b(j.wrapUpRequestedAtTurn)!==void 0?{wrapUpRequestedAtTurn:b(j.wrapUpRequestedAtTurn)}:{},...b(j.exceededAtTurn)!==void 0?{exceededAtTurn:b(j.exceededAtTurn)}:{}}}function X4($,j){return $==="queued"||$==="running"||$==="complete"||$==="failed"||$==="paused"?$:j}function Y4($,j){if(!$||typeof $!=="object")return;let J=$,Z=m(J.agent,128);if(!Z)return;let Q=J.status==="pending"||J.status==="running"||J.status==="complete"||J.status==="completed"||J.status==="failed"||J.status==="paused"?J.status:"pending";return{agent:Z,status:Q,...m(J.sessionFile,2048)?{sessionFile:m(J.sessionFile,2048)}:{},...J.activityState==="active_long_running"||J.activityState==="needs_attention"?{activityState:J.activityState}:{},...b(J.lastActivityAt)!==void 0?{lastActivityAt:b(J.lastActivityAt)}:{},...m(J.currentTool,128)?{currentTool:m(J.currentTool,128)}:{},...b(J.currentToolStartedAt)!==void 0?{currentToolStartedAt:b(J.currentToolStartedAt)}:{},...m(J.currentPath,2048)?{currentPath:m(J.currentPath,2048)}:{},...b(J.turnCount)!==void 0?{turnCount:b(J.turnCount)}:{},...b(J.toolCount)!==void 0?{toolCount:b(J.toolCount)}:{},...b(J.startedAt)!==void 0?{startedAt:b(J.startedAt)}:{},...b(J.endedAt)!==void 0?{endedAt:b(J.endedAt)}:{},...m(J.error,1024)?{error:m(J.error,1024)}:{},...J.timedOut===!0?{timedOut:!0}:{},...U1(J.turnBudget)?{turnBudget:U1(J.turnBudget)}:{},...J.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...J.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...j<Kj&&Array.isArray(J.children)?{children:J.children.map((X)=>z1(X,j+1)).filter((X)=>Boolean(X)).slice(0,V1)}:{}}}function z1($,j=0){if(!$||typeof $!=="object")return;let J=$;if(!K1(J.id)||!K1(J.parentRunId))return;let Z=J1(J.path),Q=Array.isArray(J.steps)?J.steps.map((U)=>Y4(U,j+1)).filter((U)=>Boolean(U)).slice(0,Vj):void 0,X=Z4(J.totalTokens),W=Q4(J.totalCost);return{id:J.id,parentRunId:J.parentRunId,...b(J.parentStepIndex)!==void 0?{parentStepIndex:b(J.parentStepIndex)}:{},...m(J.parentAgent,128)?{parentAgent:m(J.parentAgent,128)}:{},depth:Math.min(Math.max(0,b(J.depth)??0),Kj),path:Z,state:X4(J.state,"running"),...m(J.asyncDir,2048)?{asyncDir:m(J.asyncDir,2048)}:{},...b(J.pid)!==void 0&&b(J.pid)>0&&Number.isInteger(b(J.pid))?{pid:b(J.pid)}:{},...m(J.sessionId,256)?{sessionId:m(J.sessionId,256)}:{},...m(J.sessionFile,2048)?{sessionFile:m(J.sessionFile,2048)}:{},...m(J.intercomTarget,256)?{intercomTarget:m(J.intercomTarget,256)}:{},...m(J.ownerIntercomTarget,256)?{ownerIntercomTarget:m(J.ownerIntercomTarget,256)}:{},...m(J.leafIntercomTarget,256)?{leafIntercomTarget:m(J.leafIntercomTarget,256)}:{},...J.ownerState==="live"||J.ownerState==="gone"||J.ownerState==="unknown"?{ownerState:J.ownerState}:{},...m(J.controlInbox,2048)?{controlInbox:m(J.controlInbox,2048)}:{},...m(J.capabilityToken,128)?{capabilityToken:m(J.capabilityToken,128)}:{},...J.mode==="single"||J.mode==="parallel"||J.mode==="chain"?{mode:J.mode}:{},...m(J.agent,128)?{agent:m(J.agent,128)}:{},...Array.isArray(J.agents)?{agents:J.agents.map((U)=>m(U,128)).filter((U)=>Boolean(U)).slice(0,Vj)}:{},...b(J.currentStep)!==void 0?{currentStep:b(J.currentStep)}:{},...b(J.chainStepCount)!==void 0?{chainStepCount:b(J.chainStepCount)}:{},...J.activityState==="active_long_running"||J.activityState==="needs_attention"?{activityState:J.activityState}:{},...b(J.lastActivityAt)!==void 0?{lastActivityAt:b(J.lastActivityAt)}:{},...m(J.currentTool,128)?{currentTool:m(J.currentTool,128)}:{},...b(J.currentToolStartedAt)!==void 0?{currentToolStartedAt:b(J.currentToolStartedAt)}:{},...m(J.currentPath,2048)?{currentPath:m(J.currentPath,2048)}:{},...b(J.turnCount)!==void 0?{turnCount:b(J.turnCount)}:{},...b(J.toolCount)!==void 0?{toolCount:b(J.toolCount)}:{},...X?{totalTokens:X}:{},...W?{totalCost:W}:{},...b(J.startedAt)!==void 0?{startedAt:b(J.startedAt)}:{},...b(J.endedAt)!==void 0?{endedAt:b(J.endedAt)}:{},...b(J.lastUpdate)!==void 0?{lastUpdate:b(J.lastUpdate)}:{},...b(J.timeoutMs)!==void 0?{timeoutMs:b(J.timeoutMs)}:{},...b(J.deadlineAt)!==void 0?{deadlineAt:b(J.deadlineAt)}:{},...J.timedOut===!0?{timedOut:!0}:{},...U1(J.turnBudget)?{turnBudget:U1(J.turnBudget)}:{},...J.turnBudgetExceeded===!0?{turnBudgetExceeded:!0}:{},...J.wrapUpRequested===!0?{wrapUpRequested:!0}:{},...m(J.error,1024)?{error:m(J.error,1024)}:{},...Q&&Q.length>0?{steps:Q}:{},...j<Kj&&Array.isArray(J.children)?{children:J.children.map((U)=>z1(U,j+1)).filter((U)=>Boolean(U)).slice(0,V1)}:{}}}function zj($,j){if(Buffer.byteLength($,"utf-8")>Gj)return;let J;try{J=JSON.parse($)}catch{return}if(!J||typeof J!=="object")return;let Z=J;if(Z.type!=="subagent.nested.started"&&Z.type!=="subagent.nested.updated"&&Z.type!=="subagent.nested.completed")return;if(Z.rootRunId!==j.rootRunId||Z.capabilityToken!==j.capabilityToken)return;if(!K1(Z.parentRunId))return;let Q=b(Z.ts);if(Q===void 0)return;let X=z1(Z.child);if(!X||X.id===j.rootRunId)return;let W={...X,controlInbox:j.controlInbox,capabilityToken:j.capabilityToken,ownerState:X.ownerState??"unknown"};return{type:Z.type,ts:Q,rootRunId:j.rootRunId,parentRunId:Z.parentRunId,...b(Z.parentStepIndex)!==void 0?{parentStepIndex:b(Z.parentStepIndex)}:{},capabilityToken:j.capabilityToken,child:W}}function W4($,j){if(!$.includes(`
34
34
  `)){let J=zj($.trim(),j);return J?[J]:[]}return $.split(`
35
35
  `).slice(0,$.endsWith(`
36
- `)?void 0:-1).map((J)=>J.trim()?zj(J,j):void 0).filter((J)=>Boolean(J))}function H1($){return $==="complete"||$==="failed"||$==="paused"}function j8($,j){let J=j.type==="subagent.nested.completed"&&j.child.state==="running"?"complete":j.child.state,Z={...j.child,state:J,lastUpdate:j.child.lastUpdate??j.ts};if(!$)return Z;let Q=$.lastUpdate??0,X=Z.lastUpdate??j.ts;if(X<Q)return $;if(H1($.state)&&!H1(Z.state))return $;if(H1($.state)&&H1(Z.state)&&X===Q)return $;return{...$,...Z,state:Z.state,lastUpdate:Math.max(Q,X)}}function W4($,j){let J=!1,Z=(K)=>K.map((G)=>{if(G.id===j.parentRunId){let q=G.children??[],O=q.findIndex((h)=>h.id===j.child.id),T=j8(O>=0?q[O]:void 0,j),y=O>=0?q.map((h,S)=>S===O?T:h):[...q,T];return J=!0,{...G,children:y.slice(0,U1),lastUpdate:Math.max(G.lastUpdate??0,j.ts)}}if(!G.children?.length)return G;let B=Z(G.children);return B===G.children?G:{...G,children:B}}),Q=Z($);if(J)return Q;let X=Q.findIndex((K)=>K.id===j.child.id),W=j8(X>=0?Q[X]:void 0,j);return X>=0?Q.map((K,G)=>G===X?W:K):[...Q,W].slice(0,U1)}function H4($,j){return{...$,updatedAt:Math.max($.updatedAt,j.ts),children:W4($.children,j)}}function Z8($){return Q$.join(J8($),$4)}function U4($){Bj($);try{let j=JSON.parse(R$.readFileSync(Z8($),"utf-8"));return{rootRunId:$.rootRunId,updatedAt:typeof j.updatedAt==="number"?j.updatedAt:0,children:Array.isArray(j.children)?j.children.map((J)=>z1(J)).filter((J)=>Boolean(J)):[],processedEvents:Array.isArray(j.processedEvents)?j.processedEvents.filter((J)=>typeof J==="string"):[]}}catch(j){if(j.code!=="ENOENT")throw j;return{rootRunId:$.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function Mj($){Bj($);let j=U4($),J=new Set(j.processedEvents),Z=!1,Q=[];try{Q=R$.readdirSync($.eventSink).filter((X)=>X.endsWith(".json")||X.endsWith(".jsonl")).sort()}catch(X){if(X.code!=="ENOENT")throw X}for(let X of Q){if(J.has(X))continue;let W=Q$.join($.eventSink,X);if(!Kj($.eventSink,W))continue;let K;try{let G=R$.statSync(W);if(!G.isFile()||G.size>Gj)continue;K=R$.readFileSync(W,"utf-8")}catch{continue}for(let G of Y4(K,$))j=H4(j,G),Z=!0;J.add(X),Z=!0}if(Z)j={...j,processedEvents:[...J].slice(-1000)},D$(Z8($),j);return j}function V4($,j,J){let Z=`${JSON.stringify(J)}
37
- `;if(Buffer.byteLength(Z,"utf-8")>Gj)throw Error("Nested route record exceeds the maximum size.");R$.mkdirSync($,{recursive:!0,mode:448});let Q=`${String(j).padStart(13,"0")}-${e6()}.json`,X=Q$.join($,`.${Q}.tmp`),W=Q$.join($,Q);return R$.writeFileSync(X,Z,{mode:384}),R$.renameSync(X,W),W}function Q8($,j){Bj($);let J={...j,rootRunId:$.rootRunId,capabilityToken:$.capabilityToken},Z=zj(JSON.stringify(J),$);if(!Z)throw Error("Nested event record failed validation.");V4($.eventSink,Z.ts,Z)}function X8($,j,J){return{id:$.runId||J.id,parentRunId:J.parentRunId,...J.parentStepIndex!==void 0?{parentStepIndex:J.parentStepIndex}:{},depth:J.depth,path:J.path??[{runId:J.parentRunId,...J.parentStepIndex!==void 0?{stepIndex:J.parentStepIndex}:{}}],asyncDir:j,...$.pid?{pid:$.pid}:{},...$.sessionId?{sessionId:$.sessionId}:{},mode:$.mode??J.mode,state:$.state,...$.currentStep!==void 0?{currentStep:$.currentStep}:{},...$.chainStepCount!==void 0?{chainStepCount:$.chainStepCount}:{},...$.activityState?{activityState:$.activityState}:{},...$.lastActivityAt!==void 0?{lastActivityAt:$.lastActivityAt}:{},...$.currentTool?{currentTool:$.currentTool}:{},...$.currentToolStartedAt!==void 0?{currentToolStartedAt:$.currentToolStartedAt}:{},...$.currentPath?{currentPath:$.currentPath}:{},...$.turnCount!==void 0?{turnCount:$.turnCount}:{},...$.toolCount!==void 0?{toolCount:$.toolCount}:{},...$.totalTokens?{totalTokens:$.totalTokens}:{},...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},...$.deadlineAt!==void 0?{deadlineAt:$.deadlineAt}:{},...$.timedOut!==void 0?{timedOut:$.timedOut}:{},...$.turnBudget?{turnBudget:$.turnBudget}:{},...$.turnBudgetExceeded!==void 0?{turnBudgetExceeded:$.turnBudgetExceeded}:{},...$.wrapUpRequested!==void 0?{wrapUpRequested:$.wrapUpRequested}:{},...$.error?{error:$.error}:{},...$.startedAt!==void 0?{startedAt:$.startedAt}:{startedAt:J.ts},...$.endedAt!==void 0?{endedAt:$.endedAt}:{},lastUpdate:$.lastUpdate??J.ts,...$.sessionFile?{sessionFile:$.sessionFile}:{},...$.steps?.length?{steps:$.steps.map((Z)=>({agent:Z.agent,status:Z.status,...Z.sessionFile?{sessionFile:Z.sessionFile}:{},...Z.activityState?{activityState:Z.activityState}:{},...Z.lastActivityAt!==void 0?{lastActivityAt:Z.lastActivityAt}:{},...Z.currentTool?{currentTool:Z.currentTool}:{},...Z.currentToolStartedAt!==void 0?{currentToolStartedAt:Z.currentToolStartedAt}:{},...Z.currentPath?{currentPath:Z.currentPath}:{},...Z.turnCount!==void 0?{turnCount:Z.turnCount}:{},...Z.toolCount!==void 0?{toolCount:Z.toolCount}:{},...Z.startedAt!==void 0?{startedAt:Z.startedAt}:{},...Z.endedAt!==void 0?{endedAt:Z.endedAt}:{},...Z.error?{error:Z.error}:{},...Z.timedOut!==void 0?{timedOut:Z.timedOut}:{},...Z.turnBudget?{turnBudget:Z.turnBudget}:{},...Z.turnBudgetExceeded!==void 0?{turnBudgetExceeded:Z.turnBudgetExceeded}:{},...Z.wrapUpRequested!==void 0?{wrapUpRequested:Z.wrapUpRequested}:{}})).slice(0,Uj)}:{}}}var K4=[/rate\s*limit/i,/too many requests/i,/\b429\b/,/quota/i,/billing/i,/credit/i,/auth(?:entication)?/i,/unauthori[sz]ed/i,/forbidden/i,/api key/i,/token expired/i,/invalid key/i,/provider.*unavailable/i,/model.*unavailable/i,/model.*disabled/i,/model.*not found/i,/unknown model/i,/overloaded/i,/service unavailable/i,/temporar(?:ily)? unavailable/i,/connection refused/i,/fetch failed/i,/network error/i,/socket hang up/i,/upstream/i,/timed? out/i,/timeout/i,/\b502\b/,/\b503\b/,/\b504\b/,/cold.?start/i,/empty response/i,/no output/i,/model.*(?:load|fail|error)/i];function Y8($){if(!$)return!1;return K4.some((j)=>j.test($))}function W8($,j){let J=$.error?.trim()||`exit ${$.exitCode??1}`;return j?`[fallback] ${$.model} failed: ${J}. Retrying with ${j}.`:`[fallback] ${$.model} failed: ${J}.`}function n$($,j){try{return $.kill(j)}catch{return!1}}function H8($,j){let{idleMs:J,hardMs:Z}=j,Q=!1,X=!1,W=!1,K,G,B=()=>{if(!X)try{$.stdout?.destroy()}catch{}if(!W)try{$.stderr?.destroy()}catch{}},q=()=>{if(K)clearTimeout(K),K=void 0;if(G)clearTimeout(G),G=void 0},O=()=>{if(!Q)return;if(K)clearTimeout(K);K=setTimeout(B,J),K.unref?.()};return $.stdout?.on("data",O),$.stderr?.on("data",O),$.stdout?.on("end",()=>{if(X=!0,X&&W)q()}),$.stderr?.on("end",()=>{if(W=!0,X&&W)q()}),$.on("exit",()=>{if(Q=!0,O(),G)return;G=setTimeout(B,Z),G.unref?.()}),$.on("close",q),$.on("error",q),q}var z4=[/(^|[;&|()\s])rm\s+/,/(^|[;&|()\s])mv\s+/,/(^|[;&|()\s])cp\s+/,/(^|[;&|()\s])mkdir\s+/,/(^|[;&|()\s])touch\s+/,/(^|[;&|()\s])git\s+apply\b/,/(^|[;&|()\s])patch\s+/,/(^|[;&|()\s])sed\s+[^\n;&|]*\s-i\b/,/(^|[;&|()\s])perl\s+[^\n;&|]*\s-pi\b/,/(^|[;&|()]|\n)\s*tee\s+[^|&;]+/,/\b(writeFile|writeFileSync|appendFile|appendFileSync)\b/,/\bwrite_text\s*\(/,/\bopen\s*\([^)]*,\s*["'][wa]/],G4=["failed","error","no exact match","did not match","malformed","rejected","unable","cannot","could not"];function U8($,j){if(!$||!j)return;let J=["path","file","filename","target","cwd"];for(let Z of J){let Q=j[Z];if(typeof Q==="string"&&Q.trim())return Q.trim()}if($==="bash"){let Z=typeof j.command==="string"?j.command:void 0;if(!Z)return;let Q=Z.match(/(?:>|>>|tee\s+)(\S+)/);if(Q?.[1])return Q[1]}return}function B4($){let j=!1,J=!1;for(let Z=0;Z<$.length;Z++){let Q=$[Z];if(Q==="'"&&!J){j=!j;continue}if(Q==='"'&&!j){J=!J;continue}if(j||J)continue;if(Q!==">")continue;if($[Z-1]==="-")continue;let X=$[Z+1]===">",W=Z+(X?2:1);while(W<$.length&&/\s/.test($[W]))W++;if(W>=$.length)continue;let K=$[W];if(K==="&"||K==="|"||K===";")continue;if(K==="("||K===")")continue;return!0}return!1}function Lj($){return B4($)||z4.some((j)=>j.test($))}function qj($,j){if(!$)return!1;if($==="edit"||$==="write")return!0;if($!=="bash")return!1;let J=typeof j?.command==="string"?j.command:"";if(!J.trim())return!1;return Lj(J)}function V8($){let j=$.toLowerCase();return G4.some((J)=>j.includes(J))}function K8($,j){if(j.now-j.startedAt>=$.activeNoticeAfterMs)return"time_threshold";if($.activeNoticeAfterTurns!==void 0&&j.turns>=$.activeNoticeAfterTurns)return"turn_threshold";if($.activeNoticeAfterTokens!==void 0&&j.tokens>=$.activeNoticeAfterTokens)return"token_threshold";return}function z8($){$.consecutiveFailures=0,$.lastFailureAt=void 0,$.recentFailures=[],$.lastMutatingPath=void 0,$.repeatedPathFailures=0}function G1(){return{consecutiveFailures:0,recentFailures:[],repeatedPathFailures:0}}function G8($,j,J){if($.lastFailureAt===void 0||j.ts-$.lastFailureAt>J)$.consecutiveFailures=0,$.recentFailures=[],$.repeatedPathFailures=0,$.lastMutatingPath=void 0;if($.lastFailureAt=j.ts,$.consecutiveFailures+=1,j.path&&$.lastMutatingPath===j.path)$.repeatedPathFailures+=1;else if(j.path)$.lastMutatingPath=j.path,$.repeatedPathFailures=1;if($.recentFailures.push(j),$.recentFailures.length>3)$.recentFailures.shift()}function B8($,j){return $.consecutiveFailures>=j||$.repeatedPathFailures>=j}function _8($){if($.recentFailures.length===0)return;return $.recentFailures.map((j)=>`${j.tool}${j.path?`(${j.path})`:""}: ${j.error}`).join(" | ")}var _4=[/\breview only\b/i,/\bsuggest fixes only\b/i,/\bonly return findings\b/i,/\breturn findings only\b/i],M4=[/\bmust\s+(?:edit|modify|change|fix|patch|apply)\b/i,/\brequired\s+to\s+(?:edit|modify|change|fix|patch|apply)\b/i,/\bregardless\s+of\s+findings\b/i,/\balways\s+(?:edit|modify|change|fix|patch|apply)\b/i,/\bapply\s+(?:the\s+)?fix(?:es)?\s+directly\b/i,/\bmake\s+(?:the\s+)?code\s+changes\b/i],L4=[/\bdo not edit\b/i,/\bdon't edit\b/i,/\bdo not modify\b/i,/\bdo not change files\b/i],q4=[/\bdo not edit files?\s+outside\b/i,/\bdo not edit\s+outside\b/i,/\bdo not edit\s+unrelated files?\b/i,/\bdo not change\s+unrelated files?\b/i,/\bdo not modify\s+unrelated files?\b/i],F4=[/\binvestigate\b/i,/\bscout\b/i,/\bresearch(?:er)?\b/i],O4=[/\b(?:implement|fix|edit|modify|patch|refactor|delete)\b/i,/\b(?:update|add|remove|replace|create)\b(?!\s+(?:(?:a|an|the)\s+)?(?:report|summary|findings?)(?:\b|$))/i,/\bapply\s+(?:the\s+)?(?:changes?|fix(?:es)?|patch)\b/i,/\bmake\s+(?:the\s+)?changes\b/i,/\bdo those fixes\b/i],A4=[/\b(?:implement|fix|edit|modify|patch|refactor)\b/i,/\bapply\s+(?:the\s+)?(?:changes?|fix(?:es)?|patch)\b/i,/\bmake\s+(?:the\s+)?changes\b/i,/\bdo those fixes\b/i,/\b(?:update|add|remove|replace|delete|create)\s+(?:the\s+)?(?:file|files|code|source|implementation|test|tests|component|function|module|class|method|logic|import|imports|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command)\b/i],N4=new Set(["read","grep","find","ls","web_search","fetch_content","get_search_content","intercom","contact_supervisor"]);function C4($){return $.split(`
36
+ `)?void 0:-1).map((J)=>J.trim()?zj(J,j):void 0).filter((J)=>Boolean(J))}function H1($){return $==="complete"||$==="failed"||$==="paused"}function j8($,j){let J=j.type==="subagent.nested.completed"&&j.child.state==="running"?"complete":j.child.state,Z={...j.child,state:J,lastUpdate:j.child.lastUpdate??j.ts};if(!$)return Z;let Q=$.lastUpdate??0,X=Z.lastUpdate??j.ts;if(X<Q)return $;if(H1($.state)&&!H1(Z.state))return $;if(H1($.state)&&H1(Z.state)&&X===Q)return $;return{...$,...Z,state:Z.state,lastUpdate:Math.max(Q,X)}}function H4($,j){let J=!1,Z=(U)=>U.map((G)=>{if(G.id===j.parentRunId){let q=G.children??[],O=q.findIndex((h)=>h.id===j.child.id),T=j8(O>=0?q[O]:void 0,j),y=O>=0?q.map((h,S)=>S===O?T:h):[...q,T];return J=!0,{...G,children:y.slice(0,V1),lastUpdate:Math.max(G.lastUpdate??0,j.ts)}}if(!G.children?.length)return G;let B=Z(G.children);return B===G.children?G:{...G,children:B}}),Q=Z($);if(J)return Q;let X=Q.findIndex((U)=>U.id===j.child.id),W=j8(X>=0?Q[X]:void 0,j);return X>=0?Q.map((U,G)=>G===X?W:U):[...Q,W].slice(0,V1)}function V4($,j){return{...$,updatedAt:Math.max($.updatedAt,j.ts),children:H4($.children,j)}}function Z8($){return Q$.join(J8($),j4)}function K4($){Bj($);try{let j=JSON.parse(R$.readFileSync(Z8($),"utf-8"));return{rootRunId:$.rootRunId,updatedAt:typeof j.updatedAt==="number"?j.updatedAt:0,children:Array.isArray(j.children)?j.children.map((J)=>z1(J)).filter((J)=>Boolean(J)):[],processedEvents:Array.isArray(j.processedEvents)?j.processedEvents.filter((J)=>typeof J==="string"):[]}}catch(j){if(j.code!=="ENOENT")throw j;return{rootRunId:$.rootRunId,updatedAt:0,children:[],processedEvents:[]}}}function Mj($){Bj($);let j=K4($),J=new Set(j.processedEvents),Z=!1,Q=[];try{Q=R$.readdirSync($.eventSink).filter((X)=>X.endsWith(".json")||X.endsWith(".jsonl")).sort()}catch(X){if(X.code!=="ENOENT")throw X}for(let X of Q){if(J.has(X))continue;let W=Q$.join($.eventSink,X);if(!Uj($.eventSink,W))continue;let U;try{let G=R$.statSync(W);if(!G.isFile()||G.size>Gj)continue;U=R$.readFileSync(W,"utf-8")}catch{continue}for(let G of W4(U,$))j=V4(j,G),Z=!0;J.add(X),Z=!0}if(Z)j={...j,processedEvents:[...J].slice(-1000)},b$(Z8($),j);return j}function U4($,j,J){let Z=`${JSON.stringify(J)}
37
+ `;if(Buffer.byteLength(Z,"utf-8")>Gj)throw Error("Nested route record exceeds the maximum size.");R$.mkdirSync($,{recursive:!0,mode:448});let Q=`${String(j).padStart(13,"0")}-${$4()}.json`,X=Q$.join($,`.${Q}.tmp`),W=Q$.join($,Q);return R$.writeFileSync(X,Z,{mode:384}),R$.renameSync(X,W),W}function Q8($,j){Bj($);let J={...j,rootRunId:$.rootRunId,capabilityToken:$.capabilityToken},Z=zj(JSON.stringify(J),$);if(!Z)throw Error("Nested event record failed validation.");U4($.eventSink,Z.ts,Z)}function X8($,j,J){return{id:$.runId||J.id,parentRunId:J.parentRunId,...J.parentStepIndex!==void 0?{parentStepIndex:J.parentStepIndex}:{},depth:J.depth,path:J.path??[{runId:J.parentRunId,...J.parentStepIndex!==void 0?{stepIndex:J.parentStepIndex}:{}}],asyncDir:j,...$.pid?{pid:$.pid}:{},...$.sessionId?{sessionId:$.sessionId}:{},mode:$.mode??J.mode,state:$.state,...$.currentStep!==void 0?{currentStep:$.currentStep}:{},...$.chainStepCount!==void 0?{chainStepCount:$.chainStepCount}:{},...$.activityState?{activityState:$.activityState}:{},...$.lastActivityAt!==void 0?{lastActivityAt:$.lastActivityAt}:{},...$.currentTool?{currentTool:$.currentTool}:{},...$.currentToolStartedAt!==void 0?{currentToolStartedAt:$.currentToolStartedAt}:{},...$.currentPath?{currentPath:$.currentPath}:{},...$.turnCount!==void 0?{turnCount:$.turnCount}:{},...$.toolCount!==void 0?{toolCount:$.toolCount}:{},...$.totalTokens?{totalTokens:$.totalTokens}:{},...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},...$.deadlineAt!==void 0?{deadlineAt:$.deadlineAt}:{},...$.timedOut!==void 0?{timedOut:$.timedOut}:{},...$.turnBudget?{turnBudget:$.turnBudget}:{},...$.turnBudgetExceeded!==void 0?{turnBudgetExceeded:$.turnBudgetExceeded}:{},...$.wrapUpRequested!==void 0?{wrapUpRequested:$.wrapUpRequested}:{},...$.error?{error:$.error}:{},...$.startedAt!==void 0?{startedAt:$.startedAt}:{startedAt:J.ts},...$.endedAt!==void 0?{endedAt:$.endedAt}:{},lastUpdate:$.lastUpdate??J.ts,...$.sessionFile?{sessionFile:$.sessionFile}:{},...$.steps?.length?{steps:$.steps.map((Z)=>({agent:Z.agent,status:Z.status,...Z.sessionFile?{sessionFile:Z.sessionFile}:{},...Z.activityState?{activityState:Z.activityState}:{},...Z.lastActivityAt!==void 0?{lastActivityAt:Z.lastActivityAt}:{},...Z.currentTool?{currentTool:Z.currentTool}:{},...Z.currentToolStartedAt!==void 0?{currentToolStartedAt:Z.currentToolStartedAt}:{},...Z.currentPath?{currentPath:Z.currentPath}:{},...Z.turnCount!==void 0?{turnCount:Z.turnCount}:{},...Z.toolCount!==void 0?{toolCount:Z.toolCount}:{},...Z.startedAt!==void 0?{startedAt:Z.startedAt}:{},...Z.endedAt!==void 0?{endedAt:Z.endedAt}:{},...Z.error?{error:Z.error}:{},...Z.timedOut!==void 0?{timedOut:Z.timedOut}:{},...Z.turnBudget?{turnBudget:Z.turnBudget}:{},...Z.turnBudgetExceeded!==void 0?{turnBudgetExceeded:Z.turnBudgetExceeded}:{},...Z.wrapUpRequested!==void 0?{wrapUpRequested:Z.wrapUpRequested}:{}})).slice(0,Vj)}:{}}}var z4=[/rate\s*limit/i,/too many requests/i,/\b429\b/,/quota/i,/billing/i,/credit/i,/auth(?:entication)?/i,/unauthori[sz]ed/i,/forbidden/i,/api key/i,/token expired/i,/invalid key/i,/provider.*unavailable/i,/model.*unavailable/i,/model.*disabled/i,/model.*not found/i,/unknown model/i,/overloaded/i,/service unavailable/i,/temporar(?:ily)? unavailable/i,/connection refused/i,/fetch failed/i,/network error/i,/socket hang up/i,/upstream/i,/timed? out/i,/timeout/i,/\b502\b/,/\b503\b/,/\b504\b/,/cold.?start/i,/empty response/i,/no output/i,/model.*(?:load|fail|error)/i];function Y8($){if(!$)return!1;return z4.some((j)=>j.test($))}function W8($,j){let J=$.error?.trim()||`exit ${$.exitCode??1}`;return j?`[fallback] ${$.model} failed: ${J}. Retrying with ${j}.`:`[fallback] ${$.model} failed: ${J}.`}function n$($,j){try{return $.kill(j)}catch{return!1}}function H8($,j){let{idleMs:J,hardMs:Z}=j,Q=!1,X=!1,W=!1,U,G,B=()=>{if(!X)try{$.stdout?.destroy()}catch{}if(!W)try{$.stderr?.destroy()}catch{}},q=()=>{if(U)clearTimeout(U),U=void 0;if(G)clearTimeout(G),G=void 0},O=()=>{if(!Q)return;if(U)clearTimeout(U);U=setTimeout(B,J),U.unref?.()};return $.stdout?.on("data",O),$.stderr?.on("data",O),$.stdout?.on("end",()=>{if(X=!0,X&&W)q()}),$.stderr?.on("end",()=>{if(W=!0,X&&W)q()}),$.on("exit",()=>{if(Q=!0,O(),G)return;G=setTimeout(B,Z),G.unref?.()}),$.on("close",q),$.on("error",q),q}var G4=[/(^|[;&|()\s])rm\s+/,/(^|[;&|()\s])mv\s+/,/(^|[;&|()\s])cp\s+/,/(^|[;&|()\s])mkdir\s+/,/(^|[;&|()\s])touch\s+/,/(^|[;&|()\s])git\s+apply\b/,/(^|[;&|()\s])patch\s+/,/(^|[;&|()\s])sed\s+[^\n;&|]*\s-i\b/,/(^|[;&|()\s])perl\s+[^\n;&|]*\s-pi\b/,/(^|[;&|()]|\n)\s*tee\s+[^|&;]+/,/\b(writeFile|writeFileSync|appendFile|appendFileSync)\b/,/\bwrite_text\s*\(/,/\bopen\s*\([^)]*,\s*["'][wa]/],B4=["failed","error","no exact match","did not match","malformed","rejected","unable","cannot","could not"];function V8($,j){if(!$||!j)return;let J=["path","file","filename","target","cwd"];for(let Z of J){let Q=j[Z];if(typeof Q==="string"&&Q.trim())return Q.trim()}if($==="bash"){let Z=typeof j.command==="string"?j.command:void 0;if(!Z)return;let Q=Z.match(/(?:>|>>|tee\s+)(\S+)/);if(Q?.[1])return Q[1]}return}function _4($){let j=!1,J=!1;for(let Z=0;Z<$.length;Z++){let Q=$[Z];if(Q==="'"&&!J){j=!j;continue}if(Q==='"'&&!j){J=!J;continue}if(j||J)continue;if(Q!==">")continue;if($[Z-1]==="-")continue;let X=$[Z+1]===">",W=Z+(X?2:1);while(W<$.length&&/\s/.test($[W]))W++;if(W>=$.length)continue;let U=$[W];if(U==="&"||U==="|"||U===";")continue;if(U==="("||U===")")continue;return!0}return!1}function Lj($){return _4($)||G4.some((j)=>j.test($))}function qj($,j){if(!$)return!1;if($==="edit"||$==="write")return!0;if($!=="bash")return!1;let J=typeof j?.command==="string"?j.command:"";if(!J.trim())return!1;return Lj(J)}function K8($){let j=$.toLowerCase();return B4.some((J)=>j.includes(J))}function U8($,j){if(j.now-j.startedAt>=$.activeNoticeAfterMs)return"time_threshold";if($.activeNoticeAfterTurns!==void 0&&j.turns>=$.activeNoticeAfterTurns)return"turn_threshold";if($.activeNoticeAfterTokens!==void 0&&j.tokens>=$.activeNoticeAfterTokens)return"token_threshold";return}function z8($){$.consecutiveFailures=0,$.lastFailureAt=void 0,$.recentFailures=[],$.lastMutatingPath=void 0,$.repeatedPathFailures=0}function G1(){return{consecutiveFailures:0,recentFailures:[],repeatedPathFailures:0}}function G8($,j,J){if($.lastFailureAt===void 0||j.ts-$.lastFailureAt>J)$.consecutiveFailures=0,$.recentFailures=[],$.repeatedPathFailures=0,$.lastMutatingPath=void 0;if($.lastFailureAt=j.ts,$.consecutiveFailures+=1,j.path&&$.lastMutatingPath===j.path)$.repeatedPathFailures+=1;else if(j.path)$.lastMutatingPath=j.path,$.repeatedPathFailures=1;if($.recentFailures.push(j),$.recentFailures.length>3)$.recentFailures.shift()}function B8($,j){return $.consecutiveFailures>=j||$.repeatedPathFailures>=j}function _8($){if($.recentFailures.length===0)return;return $.recentFailures.map((j)=>`${j.tool}${j.path?`(${j.path})`:""}: ${j.error}`).join(" | ")}var M4=[/\breview only\b/i,/\bsuggest fixes only\b/i,/\bonly return findings\b/i,/\breturn findings only\b/i],L4=[/\bmust\s+(?:edit|modify|change|fix|patch|apply)\b/i,/\brequired\s+to\s+(?:edit|modify|change|fix|patch|apply)\b/i,/\bregardless\s+of\s+findings\b/i,/\balways\s+(?:edit|modify|change|fix|patch|apply)\b/i,/\bapply\s+(?:the\s+)?fix(?:es)?\s+directly\b/i,/\bmake\s+(?:the\s+)?code\s+changes\b/i],q4=[/\bdo not edit\b/i,/\bdon't edit\b/i,/\bdo not modify\b/i,/\bdo not change files\b/i],F4=[/\bdo not edit files?\s+outside\b/i,/\bdo not edit\s+outside\b/i,/\bdo not edit\s+unrelated files?\b/i,/\bdo not change\s+unrelated files?\b/i,/\bdo not modify\s+unrelated files?\b/i],O4=[/\binvestigate\b/i,/\bscout\b/i,/\bresearch(?:er)?\b/i],A4=[/\b(?:implement|fix|edit|modify|patch|refactor|delete)\b/i,/\b(?:update|add|remove|replace|create)\b(?!\s+(?:(?:a|an|the)\s+)?(?:report|summary|findings?)(?:\b|$))/i,/\bapply\s+(?:the\s+)?(?:changes?|fix(?:es)?|patch)\b/i,/\bmake\s+(?:the\s+)?changes\b/i,/\bdo those fixes\b/i],N4=[/\b(?:implement|fix|edit|modify|patch|refactor)\b/i,/\bapply\s+(?:the\s+)?(?:changes?|fix(?:es)?|patch)\b/i,/\bmake\s+(?:the\s+)?changes\b/i,/\bdo those fixes\b/i,/\b(?:update|add|remove|replace|delete|create)\s+(?:the\s+)?(?:file|files|code|source|implementation|test|tests|component|function|module|class|method|logic|import|imports|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command)\b/i],C4=new Set(["read","grep","find","ls","web_search","fetch_content","get_search_content","intercom","contact_supervisor"]);function T4($){return $.split(`
38
38
  `).filter((j)=>!/^\s*\[(?:Write to|Read from):/i.test(j)).filter((j)=>!/^\s*(?:Create and maintain progress at:|Update progress at:|\*\*Output:\*\*|Write your findings to(?: exactly this path)?:|This path is authoritative for this run\.|Ignore any other output filename or output path mentioned elsewhere)/i.test(j)).join(`
39
- `)}function T4($){let j=$;for(let J of q4)j=j.replace(J," ");return j}function E4($,j){return $!==void 0&&$.length>0&&(j?.length??0)===0&&$.every((J)=>N4.has(J))}function S4($,j){let J=C4(j),Z=T4(J);if(_4.some((X)=>X.test(Z)))return!1;if(L4.some((X)=>X.test(Z)))return!1;if(F4.some((X)=>X.test($)))return!1;if(/\breviewer\b/i.test($))return M4.some((X)=>X.test(J));if($==="worker"&&O4.some((X)=>X.test(J)))return!0;return A4.some((X)=>X.test(J))}function D4($){for(let j of $){if(j.role!=="assistant")continue;for(let J of j.content){if(J.type!=="toolCall")continue;if(J.name==="edit"||J.name==="write")return!0;if(J.name!=="bash")continue;let Z=typeof J.arguments==="object"&&J.arguments!==null&&!Array.isArray(J.arguments)?J.arguments:{};if(typeof Z.command==="string"&&Lj(Z.command))return!0}}return!1}function M8($){let j=E4($.tools,$.mcpDirectTools)?!1:S4($.agent,$.task),J=D4($.messages);return{expectedMutation:j,attemptedMutation:J,triggered:j&&!J}}import*as B0 from"node:fs";import*as L8 from"node:path";function b4($){try{let j=B0.readdirSync($).filter((J)=>J.endsWith(".jsonl")).map((J)=>L8.join($,J));if(j.length===0)return null;return j.sort((J,Z)=>B0.statSync(Z).mtimeMs-B0.statSync(J).mtimeMs),j[0]??null}catch{return null}}function Fj($){let j=b4($);if(!j)return null;try{let J=B0.readFileSync(j,"utf-8"),Z=0,Q=0;for(let X of J.split(`
40
- `)){if(!X.trim())continue;try{let W=JSON.parse(X),K=W.usage??W.message?.usage;if(K)Z+=K.inputTokens??K.input??0,Q+=K.outputTokens??K.output??0}catch{}}return{input:Z,output:Q,total:Z+Q}}catch{return null}}import{spawnSync as F8}from"node:child_process";import*as J$ from"node:fs";import*as m0 from"node:os";import*as l from"node:path";var R4=30000;function B1($,j){let J=F8("git",["-C",$,...j],{encoding:"utf-8"});return{stdout:J.stdout??"",stderr:J.stderr??"",status:J.status}}function w$($,j){let J=B1($,j);if(J.status!==0){let Z=`git -C ${$} ${j.join(" ")}`,Q=J.stderr.trim()||J.stdout.trim()||`${Z} failed`;throw Error(Q)}return J.stdout}function w4($){let j=P4($),J=w$($,["rev-parse","--show-toplevel"]).trim();if(w$(J,["status","--porcelain"]).trim().length>0)throw Error("worktree isolation requires a clean git working tree. Commit or stash changes first.");let Q=w$(J,["rev-parse","HEAD"]).trim();return{toplevel:J,cwdRelative:j,baseCommit:Q}}function q8($){let j=l.resolve($);try{return J$.realpathSync(j)}catch{return j}}function O8($,j){let J=q8(j);for(let Z=0;Z<$.length;Z++){let Q=$[Z];if(!Q.cwd)continue;let X=l.isAbsolute(Q.cwd)?Q.cwd:l.resolve(j,Q.cwd);if(q8(X)===J)continue;return{index:Z,agent:Q.agent,cwd:Q.cwd}}return}function A8($,j){return`worktree isolation uses the shared cwd (${j}); task ${$.index+1} (${$.agent}) sets cwd to ${$.cwd}. Remove task-level cwd overrides or disable worktree.`}function I4($){return $.replace(/[^\w.-]/g,"_")}function y4($,j){return`dm-parallel-${$}-${j}`}function k4($,j){let J=$??process.env.DM_SUBAGENTS_WORKTREE_DIR;if(J===void 0)return m0.tmpdir();let Z=J.trim();if(!Z)throw Error("worktree base directory cannot be empty");let Q=Z.startsWith("~/")?l.join(m0.homedir(),Z.slice(2)):Z,X=l.isAbsolute(Q)?Q:l.resolve(j,Q);try{J$.mkdirSync(X,{recursive:!0})}catch(W){let K=W instanceof Error?W.message:String(W);throw Error(`failed to create worktree base directory ${X}: ${K}`)}return X}function f4($,j,J){return l.join($,`dm-worktree-${j}-${J}`)}function P4($){let j=B1($,["rev-parse","--is-inside-work-tree"]);if(j.status!==0||j.stdout.trim()!=="true")throw Error("worktree isolation requires a git repository");let J=w$($,["rev-parse","--show-prefix"]).trim(),Z=J?l.normalize(J.replace(/[\\/]+$/,"")):"";return Z==="."?"":Z}function x4($,j){let J=l.join($,"node_modules"),Z=l.join(j,"node_modules");if(!J$.existsSync(J)||J$.existsSync(Z))return!1;try{return J$.symlinkSync(J,Z),!0}catch{return!1}}function h4($){if($===void 0)return R4;if(!Number.isInteger($)||$<=0)throw Error("worktree setup hook timeout must be an integer greater than 0");return $}function v4($,j){if(!j)return;let J=j.hookPath.trim();if(!J)throw Error("worktree setup hook path cannot be empty");let Z=J.startsWith("~/")?l.join(m0.homedir(),J.slice(2)):J,Q;if(l.isAbsolute(Z))Q=Z;else if(Z.includes("/")||Z.includes("\\"))Q=l.resolve($,Z);else throw Error("worktree setup hook must be an absolute path or a repo-relative path");if(!J$.existsSync(Q))throw Error(`worktree setup hook not found: ${Q}`);if(J$.statSync(Q).isDirectory())throw Error(`worktree setup hook must be a file, got directory: ${Q}`);return{hookPath:Q,timeoutMs:h4(j.timeoutMs)}}function g4($,j){let J=j.trim();if(!J)throw Error("synthetic path cannot be empty");if(l.isAbsolute(J))throw Error(`synthetic path must be relative: ${j}`);let Z=l.resolve($,J),Q=l.relative($,Z);if(!Q||Q===".")throw Error(`synthetic path cannot target the worktree root: ${j}`);if(Q===".."||Q.startsWith(`..${l.sep}`)||l.isAbsolute(Q))throw Error(`synthetic path escapes the worktree root: ${j}`);return l.normalize(Q)}function m4($,j){let J=B1($,["ls-files","--",j]);return J.status===0&&J.stdout.trim().length>0}function c4($){let j=$.trim();if(!j)throw Error("worktree setup hook returned empty stdout; expected JSON object");let J;try{J=JSON.parse(j)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`worktree setup hook returned invalid JSON: ${Q}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error("worktree setup hook stdout must be a JSON object");return J}function d4($,j){let J=F8($.hookPath,[],{cwd:j.worktreePath,encoding:"utf-8",input:JSON.stringify(j),timeout:$.timeoutMs,shell:!1});if(J.error){if(("code"in J.error?J.error.code:void 0)==="ETIMEDOUT")throw Error(`worktree setup hook timed out after ${$.timeoutMs}ms`);throw Error(`worktree setup hook failed: ${J.error.message}`)}if(J.status!==0){let X=J.stderr.trim()||J.stdout.trim()||"no output";throw Error(`worktree setup hook failed with exit code ${J.status}: ${X}`)}let Z=c4(J.stdout);if(Z.syntheticPaths===void 0)return[];if(!Array.isArray(Z.syntheticPaths))throw Error("worktree setup hook output field 'syntheticPaths' must be an array of relative paths");let Q=new Set;for(let X of Z.syntheticPaths){if(typeof X!=="string")throw Error("worktree setup hook output field 'syntheticPaths' must contain only strings");let W=g4(j.worktreePath,X);if(m4(j.worktreePath,W))throw Error(`worktree setup hook cannot mark tracked paths as synthetic: ${W}`);Q.add(W)}return[...Q]}function o4($,j,J,Z,Q,X,W,K){let G=y4(J,Z),B=f4(K,J,Z),q=B1($,["worktree","add",B,"-b",G,"HEAD"]);if(q.status!==0){let T=q.stderr.trim()||q.stdout.trim()||`failed to create worktree ${B}`;throw Error(T)}let O=j?l.join(B,j):B;try{let T=x4($,B),y=T?["node_modules"]:[];if(X){let h=d4(X,{version:1,repoRoot:$,worktreePath:B,agentCwd:O,branch:G,index:Z,runId:J,baseCommit:Q,agent:W});y.push(...h)}return{path:B,agentCwd:O,branch:G,index:Z,nodeModulesLinked:T,syntheticPaths:y}}catch(T){try{w$($,["worktree","remove","--force",B])}catch{}try{w$($,["branch","-D",G])}catch{}throw T}}function u4($,j){let J=l.resolve($.path,j),Z=l.relative($.path,J);if(!Z||Z==="."||Z===".."||Z.startsWith(`..${l.sep}`)||l.isAbsolute(Z))return;let Q;try{Q=J$.lstatSync(J)}catch(X){if((X&&typeof X==="object"&&"code"in X?X.code:void 0)==="ENOENT")return;throw X}if(Q.isSymbolicLink()){J$.unlinkSync(J);return}if(Q.isDirectory()){J$.rmSync(J,{recursive:!0,force:!0});return}J$.rmSync(J,{force:!0})}function l4($){if($.syntheticPaths.length===0)return;let j=new Set;for(let J of $.syntheticPaths){if(j.has(J))continue;j.add(J),u4($,J)}}function N8($,j,J,Z){return{index:$,agent:j,branch:J,diffStat:"",filesChanged:0,insertions:0,deletions:0,patchPath:Z}}function p4($){let j=$.split(`
41
- `).map((X)=>X.trim()).filter(Boolean),J=0,Z=0,Q=0;for(let X of j){let[W,K]=X.split("\t");if(W===void 0||K===void 0)continue;if(J++,/^\d+$/.test(W))Z+=parseInt(W,10);if(/^\d+$/.test(K))Q+=parseInt(K,10)}return{filesChanged:J,insertions:Z,deletions:Q}}function n4($,j,J,Z){l4(j),w$(j.path,["add","-A"]);let Q=w$(j.path,["diff","--cached","--stat",$.baseCommit]).trim(),X=w$(j.path,["diff","--cached",$.baseCommit]),W=w$(j.path,["diff","--cached","--numstat",$.baseCommit]);if(J$.writeFileSync(Z,X,"utf-8"),!X.trim())return N8(j.index,J,j.branch,Z);let K=p4(W);return{index:j.index,agent:J,branch:j.branch,diffStat:Q,filesChanged:K.filesChanged,insertions:K.insertions,deletions:K.deletions,patchPath:Z}}function i4($){try{J$.writeFileSync($,"","utf-8")}catch{}}function r4($,j){try{w$($,["worktree","remove","--force",j.path])}catch{}try{w$($,["branch","-D",j.branch])}catch{}}function s4($){return $.filesChanged>0||$.insertions>0||$.deletions>0||$.diffStat.trim().length>0}function C8($,j,J,Z){let Q=w4($),X=v4(Q.toplevel,Z?.setupHook),W=k4(Z?.baseDir,Q.toplevel),K=[];try{for(let G=0;G<J;G++)K.push(o4(Q.toplevel,Q.cwdRelative,j,G,Q.baseCommit,X,Z?.agents?.[G],W))}catch(G){throw Oj({cwd:Q.toplevel,worktrees:K,baseCommit:Q.baseCommit}),G}return{cwd:Q.toplevel,worktrees:K,baseCommit:Q.baseCommit}}function T8($,j,J){try{J$.mkdirSync(J,{recursive:!0})}catch{return[]}let Z=[];for(let Q=0;Q<$.worktrees.length;Q++){let X=$.worktrees[Q],W=j[Q]??`task-${Q+1}`,K=l.join(J,`task-${Q}-${I4(W)}.patch`);try{Z.push(n4($,X,W,K))}catch{i4(K),Z.push(N8(Q,W,X.branch,K))}}return Z}function Oj($){for(let j=$.worktrees.length-1;j>=0;j--)r4($.cwd,$.worktrees[j]);try{w$($.cwd,["worktree","prune"])}catch{}}function E8($){let j=$.filter(s4);if(j.length===0)return"";let J=["=== Worktree Changes ===",""];for(let Q of j){if(J.push(`--- Task ${Q.index+1} (${Q.agent}): ${Q.filesChanged} files changed, +${Q.insertions} -${Q.deletions} ---`),Q.diffStat.trim().length>0)J.push(Q.diffStat);J.push("")}let Z=l.dirname(j[0].patchPath);return J.push(`Full patches: ${Z}`),J.join(`
42
- `).trimEnd()}function S8($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}function Aj($,j,J){let Z=J!==void 0?`-${J+1}`:"";return`subagent-${S8(j)}-${S8($)}${Z}`}import{spawn as a4}from"node:child_process";import{spawnSync as t4}from"node:child_process";import*as b8 from"node:path";var _1={none:0,attested:1,checked:2,verified:3,reviewed:4};function e4($){return[...new Set($)]}function R8($){if($.level==="none")return"";let j=["","## Acceptance Contract",`Acceptance level: ${$.level}`,"Completion is not accepted from prose alone. End with a structured acceptance report.","","Criteria:",...$.criteria.length?$.criteria.map((J)=>`- ${J.id}: ${J.must}`):["- Return the requested result."],"",`Required evidence: ${$.evidence.join(", ")||"none"}`];if($.verify.length>0){j.push("","Runtime verification commands configured by parent:");for(let J of $.verify)j.push(`- ${J.id}: ${J.command}`)}if($.review&&$.review!==!1){if(j.push("",`Review gate: ${$.review.required===!1?"optional":"required"}${$.review.agent?` by ${$.review.agent}`:""}.`),$.review.focus)j.push(`Review focus: ${$.review.focus}`)}if($.stopRules.length>0)j.push("","Stop rules:",...$.stopRules.map((J)=>`- ${J}`));return j.push("","Finish with a fenced JSON block tagged `acceptance-report` in this shape:","Use empty arrays when no items apply; array fields contain strings unless object entries are shown.","```acceptance-report",JSON.stringify({criteriaSatisfied:[{id:"criterion-1",status:"satisfied",evidence:"specific proof"}],changedFiles:["src/file.ts"],testsAddedOrUpdated:["test/file.test.ts"],commandsRun:[{command:"command",result:"passed",summary:"short result"}],validationOutput:["validation output or concise summary"],residualRisks:["none"],noStagedFiles:!0,diffSummary:"short description of the diff",reviewFindings:["blocker: file.ts:12 - issue found, or no blockers"],manualNotes:"anything else the parent should know"},null,2),"```"),j.join(`
43
- `)}function w8($,j){let J=0,Z=!1,Q=!1;for(let X=j;X<$.length;X++){let W=$[X];if(Z){if(Q)Q=!1;else if(W==="\\")Q=!0;else if(W==='"')Z=!1;continue}if(W==='"'){Z=!0;continue}if(W==="{")J++;if(W==="}"){if(J--,J===0)return $.slice(j,X+1)}}return}function Nj($){if(!$||typeof $!=="object"||Array.isArray($))return $;let j=$;if("acceptance"in j)return j.acceptance;if("acceptance-report"in j)return j["acceptance-report"];return $}function $5($){return Array.isArray($)&&$.every((j)=>{if(!j||typeof j!=="object"||Array.isArray(j))return!1;let J=j;return typeof J.command==="string"&&(J.result==="passed"||J.result==="failed"||J.result==="not-run")&&typeof J.summary==="string"})}function j5($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let j=$;return"criteriaSatisfied"in j&&(i$(j.changedFiles)||i$(j.testsAddedOrUpdated)||$5(j.commandsRun)||i$(j.validationOutput)||i$(j.residualRisks)||typeof j.noStagedFiles==="boolean"||typeof j.diffSummary==="string"||i$(j.reviewFindings)||typeof j.manualNotes==="string")}function I8($){let j=$.trim();try{return JSON.parse(j)}catch(J){let Z=j.indexOf("{");if(Z>0){let Q=w8(j,Z);if(Q)return JSON.parse(Q)}throw J}}function D8($,j){return[...$.matchAll(new RegExp(`\`\`\`${j}\\s*\\n([\\s\\S]*?)\`\`\``,"gi"))].map((J)=>J[1]?.trim()).filter((J)=>Boolean(J))}function y8($){if(!$||typeof $!=="object"||Array.isArray($))return"";let j=$;if("acceptance"in j)return"acceptance";if("acceptance-report"in j)return"acceptance-report";return""}function J5($){let j=I8($),J=Nj(j);return Tj(J,y8(j))}function k8($){let j=I8($),J=Nj(j),Z=Tj(J);if(!Z.report)return;return j5(Z.report)?Z.report:void 0}function Z5($){let j=D8($,"acceptance-report"),J=[];for(let Q of j)try{let X=J5(Q);if(X.report)return{report:X.report};J.push(`Invalid acceptance-report: ${X.errors.join("; ")}`)}catch(X){J.push(X instanceof Error?X.message:String(X))}if(J.length>0)return{error:`Failed to parse acceptance-report: ${J.join("; ")}`};for(let Q of D8($,"(?:json|jsonc|json5)"))try{let X=k8(Q);if(X)return{report:X}}catch{}let Z=$.search(/ACCEPTANCE_REPORT\s*:/i);if(Z!==-1){let Q=$.indexOf("{",Z);if(Q!==-1){let X=w8($,Q);if(X)try{let W=JSON.parse(X),K=Nj(W),G=Tj(K,y8(W));if(G.report)return{report:G.report};return{error:`Failed to parse acceptance-report: Invalid acceptance-report: ${G.errors.join("; ")}`}}catch(W){return{error:W instanceof Error?W.message:String(W)}}}}return{error:"Structured acceptance report not found."}}function Cj($){let j=/\n?```(acceptance-report|json|jsonc|json5)\s*\n([\s\S]*?)```\s*/gi,J;for(let Z of $.matchAll(j)){let Q=(Z.index??0)+Z[0].length;if($.slice(Q).trim().length===0&&Z[1]&&Z[2])J={index:Z.index??0,tag:Z[1].toLowerCase(),body:Z[2]}}if(J){if(J.tag==="acceptance-report")return $.slice(0,J.index).trimEnd();try{if(k8(J.body))return $.slice(0,J.index).trimEnd()}catch{}}return $.replace(/\n?```acceptance-report\s*\n[\s\S]*?```\s*$/i,"").replace(/\n?ACCEPTANCE_REPORT\s*:\s*\{[\s\S]*\}\s*$/i,"").trimEnd()}function i$($){return Array.isArray($)&&$.every((j)=>typeof j==="string")}function I$($,j){return $?`${$}.${j}`:j}function Q5($){if($===void 0)return"missing";if($===null)return"null";if(Array.isArray($))return"array";if(typeof $==="object")return"object";if(typeof $==="string"){let j=$.length>80?`${$.slice(0,77)}...`:$;return JSON.stringify(j)}return`${typeof $} ${String($)}`}function M$($,j,J,Z){$.push(`${j}: expected ${J}; got ${Q5(Z)}`)}function c0($,j,J){if(!Array.isArray(j)){M$($,J,"string[]",j);return}for(let[Z,Q]of j.entries())if(typeof Q!=="string")M$($,`${J}[${Z}]`,"string",Q)}function Tj($,j=""){let J=[];if(!$||typeof $!=="object"||Array.isArray($))return M$(J,j||"acceptance-report","object",$),{errors:J};let Z=$;if(Z.criteriaSatisfied!==void 0)if(!Array.isArray(Z.criteriaSatisfied))M$(J,I$(j,"criteriaSatisfied"),"array",Z.criteriaSatisfied);else for(let[X,W]of Z.criteriaSatisfied.entries()){let K=`${I$(j,"criteriaSatisfied")}[${X}]`;if(!W||typeof W!=="object"||Array.isArray(W)){M$(J,K,"object",W);continue}let G=W;if(G.id!==void 0&&typeof G.id!=="string")M$(J,`${K}.id`,"string",G.id);if(G.status!=="satisfied"&&G.status!=="not-satisfied"&&G.status!=="not-applicable")M$(J,`${K}.status`,'one of "satisfied", "not-satisfied", "not-applicable"',G.status);if(typeof G.evidence!=="string"||!G.evidence.trim())M$(J,`${K}.evidence`,"non-empty string",G.evidence)}if(Z.changedFiles!==void 0)c0(J,Z.changedFiles,I$(j,"changedFiles"));if(Z.testsAddedOrUpdated!==void 0)c0(J,Z.testsAddedOrUpdated,I$(j,"testsAddedOrUpdated"));if(Z.commandsRun!==void 0)if(!Array.isArray(Z.commandsRun))M$(J,I$(j,"commandsRun"),"array",Z.commandsRun);else for(let[X,W]of Z.commandsRun.entries()){let K=`${I$(j,"commandsRun")}[${X}]`;if(!W||typeof W!=="object"||Array.isArray(W)){M$(J,K,"object",W);continue}let G=W;if(typeof G.command!=="string"||!G.command.trim())M$(J,`${K}.command`,"non-empty string",G.command);if(G.result!=="passed"&&G.result!=="failed"&&G.result!=="not-run")M$(J,`${K}.result`,'one of "passed", "failed", "not-run"',G.result);if(typeof G.summary!=="string")M$(J,`${K}.summary`,"string",G.summary)}if(Z.validationOutput!==void 0)c0(J,Z.validationOutput,I$(j,"validationOutput"));if(Z.residualRisks!==void 0)c0(J,Z.residualRisks,I$(j,"residualRisks"));if(Z.noStagedFiles!==void 0&&typeof Z.noStagedFiles!=="boolean")M$(J,I$(j,"noStagedFiles"),"boolean",Z.noStagedFiles);if(Z.diffSummary!==void 0&&typeof Z.diffSummary!=="string")M$(J,I$(j,"diffSummary"),"string",Z.diffSummary);if(Z.reviewFindings!==void 0)c0(J,Z.reviewFindings,I$(j,"reviewFindings"));if(Z.manualNotes!==void 0&&typeof Z.manualNotes!=="string")M$(J,I$(j,"manualNotes"),"string",Z.manualNotes);if(Z.notes!==void 0&&typeof Z.notes!=="string")M$(J,I$(j,"notes"),"string",Z.notes);if(J.length>0)return{errors:J};return Z.criteriaSatisfied!==void 0||Z.changedFiles!==void 0||Z.testsAddedOrUpdated!==void 0||Z.commandsRun!==void 0||Z.validationOutput!==void 0||Z.residualRisks!==void 0||Z.noStagedFiles!==void 0||Z.diffSummary!==void 0||Z.manualNotes!==void 0||Z.notes!==void 0||Z.reviewFindings!==void 0?{report:Z,errors:J}:{errors:[`${j||"acceptance-report"}: expected at least one acceptance report field`]}}function X5($,j){let J=new Map((j.criteriaSatisfied??[]).filter((Z)=>Z.id).map((Z)=>[Z.id,Z]));return $.filter((Z)=>Z.severity!=="recommended").map((Z)=>{let Q=J.get(Z.id);if(!Q)return{id:`criterion:${Z.id}`,status:"failed",message:`Required criterion '${Z.id}' was not reported.`};if(Q.status!=="satisfied")return{id:`criterion:${Z.id}`,status:"failed",message:`Required criterion '${Z.id}' was reported as ${Q.status}.`};return{id:`criterion:${Z.id}`,status:"passed",message:`Required criterion '${Z.id}' satisfied.`}})}function Y5($,j){switch(j){case"changed-files":return i$($.changedFiles)&&$.changedFiles.length>0;case"tests-added":return i$($.testsAddedOrUpdated)&&$.testsAddedOrUpdated.length>0;case"commands-run":return Array.isArray($.commandsRun)&&$.commandsRun.length>0;case"validation-output":return i$($.validationOutput)&&$.validationOutput.length>0;case"residual-risks":return i$($.residualRisks);case"no-staged-files":return $.noStagedFiles===!0;case"diff-summary":return typeof $.diffSummary==="string"&&$.diffSummary.trim().length>0;case"review-findings":return i$($.reviewFindings);case"manual-notes":return Boolean(($.manualNotes??$.notes)?.trim())}}function W5($){let j=t4("git",["status","--short"],{cwd:$,encoding:"utf-8"});if(j.status!==0)return{id:"no-staged-files",status:"not-applicable",message:"git status unavailable; no staged-files check skipped"};let J=j.stdout.split(/\r?\n/).filter((Z)=>Z.length>=2&&Z[0]!==" "&&Z[0]!=="?");return J.length===0?{id:"no-staged-files",status:"passed",message:"No staged files detected."}:{id:"no-staged-files",status:"failed",message:`Staged files present: ${J.join(", ")}`}}function H5($,j,J){let Z=[];for(let Q of $.evidence){let X=Y5(j,Q);Z.push({id:`evidence:${Q}`,status:X?"passed":"failed",message:X?`${Q} evidence present.`:`${Q} evidence missing from child report.`})}if($.evidence.includes("no-staged-files"))Z.push(W5(J));return Z}function d0($){let j=$.trim();if(!j)return;return j.length>12000?`${j.slice(0,12000)}
44
- ...[truncated]`:j}function o0($){return e4($.map((j)=>j?.trim()).filter((j)=>Boolean(j)))}function Ej($){let j=$.results.map((Q)=>Q.acceptance?.childReport).filter((Q)=>Boolean(Q)),J=$.results.filter((Q)=>Q.exitCode!==0||Q.acceptance?.status==="rejected"),Z=$.results.length>0&&J.length===0;return{criteriaSatisfied:[{id:"criterion-1",status:Z?"satisfied":"not-satisfied",evidence:Z?`All ${$.results.length} dynamic child run(s) completed without child or acceptance blockers.`:"Dynamic fanout produced no accepted child evidence."},{id:"criterion-2",status:Z?"satisfied":"not-satisfied",evidence:Z?"Collected child acceptance evidence for aggregate review.":"Dynamic fanout produced no aggregate review evidence."},...$.results.map((Q,X)=>({id:`child-${X+1}`,status:Q.exitCode===0&&Q.acceptance?.status!=="rejected"?"satisfied":"not-satisfied",evidence:`${Q.agent}: acceptance ${Q.acceptance?.status??"unreported"}${Q.error?` (${Q.error})`:""}`}))],changedFiles:o0(j.flatMap((Q)=>Q.changedFiles??[])),testsAddedOrUpdated:o0(j.flatMap((Q)=>Q.testsAddedOrUpdated??[])),commandsRun:j.flatMap((Q)=>Q.commandsRun??[]),validationOutput:o0(j.flatMap((Q)=>Q.validationOutput??[])),residualRisks:o0([...j.flatMap((Q)=>Q.residualRisks??[]),...J.map((Q)=>`${Q.agent}: ${Q.error??"child or acceptance gate failed"}`)]),noStagedFiles:j.length>0&&j.every((Q)=>Q.noStagedFiles===!0),reviewFindings:o0(j.flatMap((Q)=>Q.reviewFindings??[])),manualNotes:$.notes??`Aggregated acceptance evidence from ${$.results.length} dynamic fanout child run(s).`,notes:$.notes}}function U5($,j,J={}){return new Promise((Z)=>{let Q=Date.now(),X=$.cwd?b8.resolve(j,$.cwd):j,W="",K="",G=!1,B=!1,q,O=a4($.command,{cwd:X,env:{...process.env,...$.env??{}},shell:!0,stdio:["ignore","pipe","pipe"],windowsHide:!0}),T=(S)=>{if(B)return;if(B=!0,clearTimeout(h),q)clearTimeout(q);J.signal?.removeEventListener("abort",y),Z({id:$.id,command:$.command,cwd:X,durationMs:Date.now()-Q,...S})},y=()=>{if(B||G)return;G=!0,O.kill("SIGTERM"),q=setTimeout(()=>{O.kill("SIGKILL"),T({exitCode:null,status:"timed-out",stdout:d0(W),stderr:d0(K||J.abortMessage||"Acceptance verification timed out.")})},1000),q.unref?.()},h=setTimeout(y,$.timeoutMs??120000);if(h.unref?.(),J.signal?.aborted)y();else J.signal?.addEventListener("abort",y,{once:!0});O.stdout.on("data",(S)=>{W+=S.toString()}),O.stderr.on("data",(S)=>{K+=S.toString()}),O.on("close",(S)=>{T({exitCode:S,status:G?"timed-out":S===0&&!G?"passed":$.allowFailure?"allowed-failure":"failed",stdout:d0(W),stderr:d0(K||(G?J.abortMessage??"":""))})}),O.on("error",(S)=>{T({exitCode:G?null:1,status:G?"timed-out":$.allowFailure?"allowed-failure":"failed",stderr:G?d0(K||J.abortMessage||"Acceptance verification timed out."):S instanceof Error?S.message:String(S)})})})}async function M1($){let j=$.acceptance,J={status:j.level==="none"?"not-required":"claimed",explicit:j.explicit,effectiveAcceptance:j,inferredReason:j.inferredReason,criteria:j.criteria,runtimeChecks:[],verifyRuns:[]};if(j.level==="none")return J;let Z=$.report?{report:$.report}:Z5($.output);if(Z.report)J.childReport=Z.report,J.status="attested";else return J.childReportParseError=Z.error,J.runtimeChecks.push({id:"attestation",status:"failed",message:Z.error??"Structured acceptance report missing."}),J.status="rejected",J;if(_1[j.level]>=_1.checked){if(J.runtimeChecks=[...X5(j.criteria,Z.report),...H5(j,Z.report,$.cwd)],J.runtimeChecks.some((Q)=>Q.status==="failed"))return J.status="rejected",J;J.status="checked"}if(_1[j.level]>=_1.verified&&(j.level==="verified"||j.verify.length>0)){if(j.level==="verified"&&j.verify.length===0)return J.runtimeChecks.push({id:"verification-config",status:"failed",message:"verified acceptance requires runtime verify commands."}),J.status="rejected",J;J.verifyRuns=[];for(let Q of j.verify)if(J.verifyRuns.push(await U5(Q,$.cwd,{signal:$.signal,abortMessage:$.abortMessage})),$.signal?.aborted)break;if(J.verifyRuns.some((Q)=>Q.status==="failed"||Q.status==="timed-out"))return J.status="rejected",J;J.status="verified"}if(j.level==="reviewed")if($.reviewResult)J.reviewResult=$.reviewResult,J.status=$.reviewResult.status==="no-blockers"?"reviewed":"rejected";else{let Q=j.review&&j.review!==!1&&j.review.required===!1;if(J.reviewResult={status:"needs-parent-decision",findings:[{severity:j.explicit&&!Q?"blocker":"non-blocking",issue:"Reviewed acceptance requires an independent reviewer result.",rationale:"The run cannot be marked reviewed from child evidence alone."}]},j.review===!1||j.explicit&&!Q)J.status="rejected"}return J}function L1($){if($.status!=="rejected")return;let j=$.runtimeChecks.find((Z)=>Z.status==="failed");if(j)return`Acceptance rejected: ${j.message}`;let J=$.verifyRuns.find((Z)=>Z.status==="failed"||Z.status==="timed-out");if(J)return`Acceptance verification '${J.id}' ${J.status}.`;if($.reviewResult?.status==="needs-parent-decision")return"Acceptance review required but no automatic reviewer result is available.";if($.reviewResult?.status==="blockers")return"Acceptance review found blockers.";return"Acceptance rejected."}import*as q1 from"node:fs";var V5=new Set(["complete","failed","paused"]),K5=new Set(["complete","completed","failed","paused"]);function z5($){try{return JSON.parse(q1.readFileSync($,"utf-8"))}catch(j){if(typeof j==="object"&&j!==null&&"code"in j&&j.code==="ENOENT")return;throw j}}function F1($,j){return $?.steps?.[j]}function G5($,j){if(!$)return!1;let J=F1($,j);if(J&&K5.has(J.status))return!0;return V5.has($.state)}function B5($,j){if(!$)return;if(j?.success===!0)return"complete";if(j?.success===!1)return $.state==="paused"?"paused":"failed";if($.state==="complete"||$.state==="failed"||$.state==="paused")return $.state;if($.success===!0)return"complete";if($.success===!1)return"failed";return}function _5($,j,J){let Z=J?.agent??j.steps?.[$.index]?.agent??"subagent",Q=J?.timedOut===!0||j.timedOut===!0,X=J?.error??j.error??`Attached async root ${$.runId} ended without a result file at ${$.resultPath}.`;return{agent:Z,output:X,success:!1,exitCode:1,error:X,...Q?{timedOut:!0}:{},...J?.sessionFile??j.sessionFile?{sessionFile:J?.sessionFile??j.sessionFile}:{},...J?.model?{model:J.model}:{},...J?.attemptedModels?{attemptedModels:J.attemptedModels}:{},...J?.modelAttempts?{modelAttempts:J.modelAttempts}:{},...J?.totalCost?{totalCost:J.totalCost}:{},...J?.structuredOutput!==void 0?{structuredOutput:J.structuredOutput}:{},...J?.structuredOutputPath?{structuredOutputPath:J.structuredOutputPath}:{},...J?.structuredOutputSchemaPath?{structuredOutputSchemaPath:J.structuredOutputSchemaPath}:{},...J?.acceptance?{acceptance:J.acceptance}:{}}}function M5($,j,J){let Z=F1(j,$.index);return{agent:Z?.agent??j?.steps?.[$.index]?.agent??"subagent",output:J,success:!1,exitCode:1,error:J,timedOut:!0,...Z?.sessionFile??j?.sessionFile?{sessionFile:Z?.sessionFile??j?.sessionFile}:{},...Z?.model?{model:Z.model}:{},...Z?.attemptedModels?{attemptedModels:Z.attemptedModels}:{},...Z?.modelAttempts?{modelAttempts:Z.modelAttempts}:{},...Z?.totalCost?{totalCost:Z.totalCost}:{}}}function L5($,j,J){let Z=J.results?.[$.index],Q=F1(j,$.index),X=B5(J,Z),W=Z?.agent??Q?.agent??j?.steps?.[$.index]?.agent??"subagent",K=Z?.output??J.summary??"",G=Z?.timedOut===!0||Q?.timedOut===!0||J.timedOut===!0||j?.timedOut===!0,B=X==="complete"&&!G,q=Z?.error??(B?void 0:J.error??J.summary??j?.error??`Attached async root ${$.runId} did not complete successfully.`);return{agent:W,output:B?K:K||q||"",success:B,exitCode:B?0:1,...q?{error:q}:{},...G?{timedOut:!0}:{},...Z?.sessionFile??Q?.sessionFile??j?.sessionFile?{sessionFile:Z?.sessionFile??Q?.sessionFile??j?.sessionFile}:{},...Z?.intercomTarget?{intercomTarget:Z.intercomTarget}:{},...Z?.model??Q?.model?{model:Z?.model??Q?.model}:{},...Z?.attemptedModels??Q?.attemptedModels?{attemptedModels:Z?.attemptedModels??Q?.attemptedModels}:{},...Z?.modelAttempts??Q?.modelAttempts?{modelAttempts:Z?.modelAttempts??Q?.modelAttempts}:{},...Z?.totalCost??Q?.totalCost?{totalCost:Z?.totalCost??Q?.totalCost}:{},...Z?.structuredOutput!==void 0?{structuredOutput:Z.structuredOutput}:Q?.structuredOutput!==void 0?{structuredOutput:Q.structuredOutput}:{},...Z?.structuredOutputPath??Q?.structuredOutputPath?{structuredOutputPath:Z?.structuredOutputPath??Q?.structuredOutputPath}:{},...Z?.structuredOutputSchemaPath??Q?.structuredOutputSchemaPath?{structuredOutputSchemaPath:Z?.structuredOutputSchemaPath??Q?.structuredOutputSchemaPath}:{},...Z?.acceptance??Q?.acceptance?{acceptance:Z?.acceptance??Q?.acceptance}:{}}}async function f8($,j={}){let J=j.pollIntervalMs??500,Z=j.terminalResultGraceMs??1000,Q=j.now??Date.now,X;for(;;){let W=R0($.asyncDir);if(j.shouldAbort?.())return M5($,W,j.timeoutMessage??"Subagent timed out.");let K=z5($.resultPath);if(K)return L5($,W,K);if(G5(W,$.index)){if(X??=Q(),Q()-X>=Z)return _5($,W,F1(W,$.index))}else X=void 0;if(!W&&!q1.existsSync($.asyncDir))throw Error(`Attached async root '${$.runId}' directory does not exist: ${$.asyncDir}`);await new Promise((G)=>setTimeout(G,J))}}import*as _0 from"node:fs";import*as Sj from"node:path";var q5="append-requests";function F5($){return Sj.join($,q5)}function x8($){let j=F5($);try{return _0.readdirSync(j).filter((J)=>J.endsWith(".json")).map((J)=>Sj.join(j,J)).sort()}catch(J){if(J.code==="ENOENT")return[];throw J}}function Dj($){return x8($).length}function O5($){let j=JSON.parse(_0.readFileSync($,"utf-8"));if(!j.id||typeof j.id!=="string")return;if(!Number.isFinite(j.createdAt))return;if(!Array.isArray(j.steps)||j.steps.length===0)return;return{id:j.id,createdAt:j.createdAt,steps:j.steps}}function h8($){let j=[];for(let J of x8($)){let Z=O5(J);try{_0.unlinkSync(J)}catch{}if(Z)j.push(Z)}return j.sort((J,Z)=>J.createdAt-Z.createdAt||J.id.localeCompare(Z.id))}function P8($){return{agent:$.agent,phase:$.phase,label:$.label,outputName:$.outputName,structured:$.structured,status:"pending",...$.sessionFile?{sessionFile:$.sessionFile}:{},skills:$.skills,model:$.model,thinking:$.thinking,attemptedModels:$.modelCandidates&&$.modelCandidates.length>0?$.modelCandidates:$.model?[$.model]:void 0,recentTools:[],recentOutput:[]}}function A5($){if($0($))return $.parallel.map(P8);if(j0($))return[{agent:`expand:${$.parallel.agent}`,phase:$.phase??$.parallel.phase,label:$.label??$.parallel.label??`Dynamic fanout (${$.collect.as})`,outputName:$.collect.as,structured:Boolean($.collect.outputSchema),status:"pending",recentTools:[],recentOutput:[]}];return[P8($)]}function v8($,j,J){if(!j)return;let Z=$.phases.find((Q)=>Q.title===j);if(!Z)Z={title:j,nodeIds:[]},$.phases.push(Z);Z.nodeIds.push(J)}function N5($,j,J){return{id:`step-${j}`,kind:"step",agent:$.agent,phase:$.phase,label:$.label?.trim()||$.agent||`Step ${j+1}`,status:"pending",flatIndex:J,stepIndex:j,outputName:$.outputName,structured:$.structured}}function C5($,j,J,Z){let Q=$.parallel.map((X,W)=>{let K=`step-${j}-agent-${W}`;return v8(Z,X.phase,K),{id:K,kind:"agent",agent:X.agent,phase:X.phase,label:X.label?.trim()||X.agent||`Agent ${W+1}`,status:"pending",flatIndex:J+W,stepIndex:j,outputName:X.outputName,structured:X.structured}});return{id:`step-${j}`,kind:"parallel-group",label:$.parallel.length===1?"Parallel task":`Parallel group (${$.parallel.length})`,status:"pending",stepIndex:j,children:Q}}function T5($,j){return{id:`step-${j}`,kind:"dynamic-parallel-group",label:$.label?.trim()||$.parallel.label?.trim()||`Dynamic fanout (${$.collect.as})`,status:"pending",stepIndex:j,outputName:$.collect.as,structured:Boolean($.collect.outputSchema),dynamic:{sourceOutput:$.expand.from.output,sourcePath:$.expand.from.path,itemName:$.expand.item??"item",maxItems:$.expand.maxItems,collectAs:$.collect.as},children:[]}}function E5($,j,J,Z){if(!$)return;if($0(j)){$.nodes.push(C5(j,J,Z,$));return}if(j0(j)){$.nodes.push(T5(j,J));return}let Q=N5(j,J,Z);$.nodes.push(Q),v8($,j.phase,Q.id)}function g8($){let j=0,J=0;for(let Z of $.steps){let Q=$.status.chainStepCount??$.status.steps?.length??0,X=$.status.steps?.length??0,W=A5(Z);if($.status.steps??=[],$.status.steps.push(...W),$0(Z))$.status.parallelGroups??=[],$.status.parallelGroups.push({start:X,count:Z.parallel.length,stepIndex:Q});else if(j0(Z))$.status.parallelGroups??=[],$.status.parallelGroups.push({start:X,count:1,stepIndex:Q});E5($.status.workflowGraph,Z,Q,X),$.status.chainStepCount=Q+1,j++,J+=W.length}return $.status.pendingAppends=$.pendingAppends??0,$.status.lastUpdate=$.now??Date.now(),{addedChainSteps:j,addedFlatSteps:J}}function m8($,j){if(!j)return $;let J=j.graceTurns===1?"1 additional assistant turn":`${j.graceTurns} additional assistant turns`,Z=["## Turn budget",`This child run has a soft budget of ${j.maxTurns} assistant turn${j.maxTurns===1?"":"s"}.`,`After that, ${J} may be allowed only for a final wrap-up.`,"When you approach or reach the soft budget, stop starting new tool work and return the final answer immediately.","This runner uses process-mode execution, so live steering after launch may be unavailable; treat this instruction as the wrap-up request.","If you continue past the soft budget plus grace turns, the supervisor may abort the process and return only partial output."].join(`
39
+ `)}function E4($){let j=$;for(let J of F4)j=j.replace(J," ");return j}function S4($,j){return $!==void 0&&$.length>0&&(j?.length??0)===0&&$.every((J)=>C4.has(J))}function D4($,j){let J=T4(j),Z=E4(J);if(M4.some((X)=>X.test(Z)))return!1;if(q4.some((X)=>X.test(Z)))return!1;if(O4.some((X)=>X.test($)))return!1;if(/\breviewer\b/i.test($))return L4.some((X)=>X.test(J));if($==="worker"&&A4.some((X)=>X.test(J)))return!0;return N4.some((X)=>X.test(J))}function b4($){for(let j of $){if(j.role!=="assistant")continue;for(let J of j.content){if(J.type!=="toolCall")continue;if(J.name==="edit"||J.name==="write")return!0;if(J.name!=="bash")continue;let Z=typeof J.arguments==="object"&&J.arguments!==null&&!Array.isArray(J.arguments)?J.arguments:{};if(typeof Z.command==="string"&&Lj(Z.command))return!0}}return!1}function M8($){let j=S4($.tools,$.mcpDirectTools)?!1:D4($.agent,$.task),J=b4($.messages);return{expectedMutation:j,attemptedMutation:J,triggered:j&&!J}}import*as B0 from"node:fs";import*as L8 from"node:path";function R4($){try{let j=B0.readdirSync($).filter((J)=>J.endsWith(".jsonl")).map((J)=>L8.join($,J));if(j.length===0)return null;return j.sort((J,Z)=>B0.statSync(Z).mtimeMs-B0.statSync(J).mtimeMs),j[0]??null}catch{return null}}function Fj($){let j=R4($);if(!j)return null;try{let J=B0.readFileSync(j,"utf-8"),Z=0,Q=0;for(let X of J.split(`
40
+ `)){if(!X.trim())continue;try{let W=JSON.parse(X),U=W.usage??W.message?.usage;if(U)Z+=U.inputTokens??U.input??0,Q+=U.outputTokens??U.output??0}catch{}}return{input:Z,output:Q,total:Z+Q}}catch{return null}}import{spawnSync as F8}from"node:child_process";import*as J$ from"node:fs";import*as m0 from"node:os";import*as l from"node:path";var w4=30000;function B1($,j){let J=F8("git",["-C",$,...j],{encoding:"utf-8"});return{stdout:J.stdout??"",stderr:J.stderr??"",status:J.status}}function w$($,j){let J=B1($,j);if(J.status!==0){let Z=`git -C ${$} ${j.join(" ")}`,Q=J.stderr.trim()||J.stdout.trim()||`${Z} failed`;throw Error(Q)}return J.stdout}function I4($){let j=x4($),J=w$($,["rev-parse","--show-toplevel"]).trim();if(w$(J,["status","--porcelain"]).trim().length>0)throw Error("worktree isolation requires a clean git working tree. Commit or stash changes first.");let Q=w$(J,["rev-parse","HEAD"]).trim();return{toplevel:J,cwdRelative:j,baseCommit:Q}}function q8($){let j=l.resolve($);try{return J$.realpathSync(j)}catch{return j}}function O8($,j){let J=q8(j);for(let Z=0;Z<$.length;Z++){let Q=$[Z];if(!Q.cwd)continue;let X=l.isAbsolute(Q.cwd)?Q.cwd:l.resolve(j,Q.cwd);if(q8(X)===J)continue;return{index:Z,agent:Q.agent,cwd:Q.cwd}}return}function A8($,j){return`worktree isolation uses the shared cwd (${j}); task ${$.index+1} (${$.agent}) sets cwd to ${$.cwd}. Remove task-level cwd overrides or disable worktree.`}function y4($){return $.replace(/[^\w.-]/g,"_")}function k4($,j){return`dm-parallel-${$}-${j}`}function f4($,j){let J=$??process.env.DM_SUBAGENTS_WORKTREE_DIR;if(J===void 0)return m0.tmpdir();let Z=J.trim();if(!Z)throw Error("worktree base directory cannot be empty");let Q=Z.startsWith("~/")?l.join(m0.homedir(),Z.slice(2)):Z,X=l.isAbsolute(Q)?Q:l.resolve(j,Q);try{J$.mkdirSync(X,{recursive:!0})}catch(W){let U=W instanceof Error?W.message:String(W);throw Error(`failed to create worktree base directory ${X}: ${U}`)}return X}function P4($,j,J){return l.join($,`dm-worktree-${j}-${J}`)}function x4($){let j=B1($,["rev-parse","--is-inside-work-tree"]);if(j.status!==0||j.stdout.trim()!=="true")throw Error("worktree isolation requires a git repository");let J=w$($,["rev-parse","--show-prefix"]).trim(),Z=J?l.normalize(J.replace(/[\\/]+$/,"")):"";return Z==="."?"":Z}function h4($,j){let J=l.join($,"node_modules"),Z=l.join(j,"node_modules");if(!J$.existsSync(J)||J$.existsSync(Z))return!1;try{return J$.symlinkSync(J,Z),!0}catch{return!1}}function v4($){if($===void 0)return w4;if(!Number.isInteger($)||$<=0)throw Error("worktree setup hook timeout must be an integer greater than 0");return $}function g4($,j){if(!j)return;let J=j.hookPath.trim();if(!J)throw Error("worktree setup hook path cannot be empty");let Z=J.startsWith("~/")?l.join(m0.homedir(),J.slice(2)):J,Q;if(l.isAbsolute(Z))Q=Z;else if(Z.includes("/")||Z.includes("\\"))Q=l.resolve($,Z);else throw Error("worktree setup hook must be an absolute path or a repo-relative path");if(!J$.existsSync(Q))throw Error(`worktree setup hook not found: ${Q}`);if(J$.statSync(Q).isDirectory())throw Error(`worktree setup hook must be a file, got directory: ${Q}`);return{hookPath:Q,timeoutMs:v4(j.timeoutMs)}}function m4($,j){let J=j.trim();if(!J)throw Error("synthetic path cannot be empty");if(l.isAbsolute(J))throw Error(`synthetic path must be relative: ${j}`);let Z=l.resolve($,J),Q=l.relative($,Z);if(!Q||Q===".")throw Error(`synthetic path cannot target the worktree root: ${j}`);if(Q===".."||Q.startsWith(`..${l.sep}`)||l.isAbsolute(Q))throw Error(`synthetic path escapes the worktree root: ${j}`);return l.normalize(Q)}function c4($,j){let J=B1($,["ls-files","--",j]);return J.status===0&&J.stdout.trim().length>0}function d4($){let j=$.trim();if(!j)throw Error("worktree setup hook returned empty stdout; expected JSON object");let J;try{J=JSON.parse(j)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`worktree setup hook returned invalid JSON: ${Q}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error("worktree setup hook stdout must be a JSON object");return J}function o4($,j){let J=F8($.hookPath,[],{cwd:j.worktreePath,encoding:"utf-8",input:JSON.stringify(j),timeout:$.timeoutMs,shell:!1});if(J.error){if(("code"in J.error?J.error.code:void 0)==="ETIMEDOUT")throw Error(`worktree setup hook timed out after ${$.timeoutMs}ms`);throw Error(`worktree setup hook failed: ${J.error.message}`)}if(J.status!==0){let X=J.stderr.trim()||J.stdout.trim()||"no output";throw Error(`worktree setup hook failed with exit code ${J.status}: ${X}`)}let Z=d4(J.stdout);if(Z.syntheticPaths===void 0)return[];if(!Array.isArray(Z.syntheticPaths))throw Error("worktree setup hook output field 'syntheticPaths' must be an array of relative paths");let Q=new Set;for(let X of Z.syntheticPaths){if(typeof X!=="string")throw Error("worktree setup hook output field 'syntheticPaths' must contain only strings");let W=m4(j.worktreePath,X);if(c4(j.worktreePath,W))throw Error(`worktree setup hook cannot mark tracked paths as synthetic: ${W}`);Q.add(W)}return[...Q]}function u4($,j,J,Z,Q,X,W,U){let G=k4(J,Z),B=P4(U,J,Z),q=B1($,["worktree","add",B,"-b",G,"HEAD"]);if(q.status!==0){let T=q.stderr.trim()||q.stdout.trim()||`failed to create worktree ${B}`;throw Error(T)}let O=j?l.join(B,j):B;try{let T=h4($,B),y=T?["node_modules"]:[];if(X){let h=o4(X,{version:1,repoRoot:$,worktreePath:B,agentCwd:O,branch:G,index:Z,runId:J,baseCommit:Q,agent:W});y.push(...h)}return{path:B,agentCwd:O,branch:G,index:Z,nodeModulesLinked:T,syntheticPaths:y}}catch(T){try{w$($,["worktree","remove","--force",B])}catch{}try{w$($,["branch","-D",G])}catch{}throw T}}function l4($,j){let J=l.resolve($.path,j),Z=l.relative($.path,J);if(!Z||Z==="."||Z===".."||Z.startsWith(`..${l.sep}`)||l.isAbsolute(Z))return;let Q;try{Q=J$.lstatSync(J)}catch(X){if((X&&typeof X==="object"&&"code"in X?X.code:void 0)==="ENOENT")return;throw X}if(Q.isSymbolicLink()){J$.unlinkSync(J);return}if(Q.isDirectory()){J$.rmSync(J,{recursive:!0,force:!0});return}J$.rmSync(J,{force:!0})}function p4($){if($.syntheticPaths.length===0)return;let j=new Set;for(let J of $.syntheticPaths){if(j.has(J))continue;j.add(J),l4($,J)}}function N8($,j,J,Z){return{index:$,agent:j,branch:J,diffStat:"",filesChanged:0,insertions:0,deletions:0,patchPath:Z}}function n4($){let j=$.split(`
41
+ `).map((X)=>X.trim()).filter(Boolean),J=0,Z=0,Q=0;for(let X of j){let[W,U]=X.split("\t");if(W===void 0||U===void 0)continue;if(J++,/^\d+$/.test(W))Z+=parseInt(W,10);if(/^\d+$/.test(U))Q+=parseInt(U,10)}return{filesChanged:J,insertions:Z,deletions:Q}}function i4($,j,J,Z){p4(j),w$(j.path,["add","-A"]);let Q=w$(j.path,["diff","--cached","--stat",$.baseCommit]).trim(),X=w$(j.path,["diff","--cached",$.baseCommit]),W=w$(j.path,["diff","--cached","--numstat",$.baseCommit]);if(J$.writeFileSync(Z,X,"utf-8"),!X.trim())return N8(j.index,J,j.branch,Z);let U=n4(W);return{index:j.index,agent:J,branch:j.branch,diffStat:Q,filesChanged:U.filesChanged,insertions:U.insertions,deletions:U.deletions,patchPath:Z}}function r4($){try{J$.writeFileSync($,"","utf-8")}catch{}}function s4($,j){try{w$($,["worktree","remove","--force",j.path])}catch{}try{w$($,["branch","-D",j.branch])}catch{}}function a4($){return $.filesChanged>0||$.insertions>0||$.deletions>0||$.diffStat.trim().length>0}function C8($,j,J,Z){let Q=I4($),X=g4(Q.toplevel,Z?.setupHook),W=f4(Z?.baseDir,Q.toplevel),U=[];try{for(let G=0;G<J;G++)U.push(u4(Q.toplevel,Q.cwdRelative,j,G,Q.baseCommit,X,Z?.agents?.[G],W))}catch(G){throw Oj({cwd:Q.toplevel,worktrees:U,baseCommit:Q.baseCommit}),G}return{cwd:Q.toplevel,worktrees:U,baseCommit:Q.baseCommit}}function T8($,j,J){try{J$.mkdirSync(J,{recursive:!0})}catch{return[]}let Z=[];for(let Q=0;Q<$.worktrees.length;Q++){let X=$.worktrees[Q],W=j[Q]??`task-${Q+1}`,U=l.join(J,`task-${Q}-${y4(W)}.patch`);try{Z.push(i4($,X,W,U))}catch{r4(U),Z.push(N8(Q,W,X.branch,U))}}return Z}function Oj($){for(let j=$.worktrees.length-1;j>=0;j--)s4($.cwd,$.worktrees[j]);try{w$($.cwd,["worktree","prune"])}catch{}}function E8($){let j=$.filter(a4);if(j.length===0)return"";let J=["=== Worktree Changes ===",""];for(let Q of j){if(J.push(`--- Task ${Q.index+1} (${Q.agent}): ${Q.filesChanged} files changed, +${Q.insertions} -${Q.deletions} ---`),Q.diffStat.trim().length>0)J.push(Q.diffStat);J.push("")}let Z=l.dirname(j[0].patchPath);return J.push(`Full patches: ${Z}`),J.join(`
42
+ `).trimEnd()}function S8($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}function Aj($,j,J){let Z=J!==void 0?`-${J+1}`:"";return`subagent-${S8(j)}-${S8($)}${Z}`}import{spawn as t4}from"node:child_process";import{spawnSync as e4}from"node:child_process";import*as b8 from"node:path";var _1={none:0,attested:1,checked:2,verified:3,reviewed:4};function $5($){return[...new Set($)]}function R8($){if($.level==="none")return"";let j=["","## Acceptance Contract",`Acceptance level: ${$.level}`,"Completion is not accepted from prose alone. End with a structured acceptance report.","","Criteria:",...$.criteria.length?$.criteria.map((J)=>`- ${J.id}: ${J.must}`):["- Return the requested result."],"",`Required evidence: ${$.evidence.join(", ")||"none"}`];if($.verify.length>0){j.push("","Runtime verification commands configured by parent:");for(let J of $.verify)j.push(`- ${J.id}: ${J.command}`)}if($.review&&$.review!==!1){if(j.push("",`Review gate: ${$.review.required===!1?"optional":"required"}${$.review.agent?` by ${$.review.agent}`:""}.`),$.review.focus)j.push(`Review focus: ${$.review.focus}`)}if($.stopRules.length>0)j.push("","Stop rules:",...$.stopRules.map((J)=>`- ${J}`));return j.push("","Finish with a fenced JSON block tagged `acceptance-report` in this shape:","Use empty arrays when no items apply; array fields contain strings unless object entries are shown.","```acceptance-report",JSON.stringify({criteriaSatisfied:[{id:"criterion-1",status:"satisfied",evidence:"specific proof"}],changedFiles:["src/file.ts"],testsAddedOrUpdated:["test/file.test.ts"],commandsRun:[{command:"command",result:"passed",summary:"short result"}],validationOutput:["validation output or concise summary"],residualRisks:["none"],noStagedFiles:!0,diffSummary:"short description of the diff",reviewFindings:["blocker: file.ts:12 - issue found, or no blockers"],manualNotes:"anything else the parent should know"},null,2),"```"),j.join(`
43
+ `)}function w8($,j){let J=0,Z=!1,Q=!1;for(let X=j;X<$.length;X++){let W=$[X];if(Z){if(Q)Q=!1;else if(W==="\\")Q=!0;else if(W==='"')Z=!1;continue}if(W==='"'){Z=!0;continue}if(W==="{")J++;if(W==="}"){if(J--,J===0)return $.slice(j,X+1)}}return}function Nj($){if(!$||typeof $!=="object"||Array.isArray($))return $;let j=$;if("acceptance"in j)return j.acceptance;if("acceptance-report"in j)return j["acceptance-report"];return $}function j5($){return Array.isArray($)&&$.every((j)=>{if(!j||typeof j!=="object"||Array.isArray(j))return!1;let J=j;return typeof J.command==="string"&&(J.result==="passed"||J.result==="failed"||J.result==="not-run")&&typeof J.summary==="string"})}function J5($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let j=$;return"criteriaSatisfied"in j&&(i$(j.changedFiles)||i$(j.testsAddedOrUpdated)||j5(j.commandsRun)||i$(j.validationOutput)||i$(j.residualRisks)||typeof j.noStagedFiles==="boolean"||typeof j.diffSummary==="string"||i$(j.reviewFindings)||typeof j.manualNotes==="string")}function I8($){let j=$.trim();try{return JSON.parse(j)}catch(J){let Z=j.indexOf("{");if(Z>0){let Q=w8(j,Z);if(Q)return JSON.parse(Q)}throw J}}function D8($,j){return[...$.matchAll(new RegExp(`\`\`\`${j}\\s*\\n([\\s\\S]*?)\`\`\``,"gi"))].map((J)=>J[1]?.trim()).filter((J)=>Boolean(J))}function y8($){if(!$||typeof $!=="object"||Array.isArray($))return"";let j=$;if("acceptance"in j)return"acceptance";if("acceptance-report"in j)return"acceptance-report";return""}function Z5($){let j=I8($),J=Nj(j);return Tj(J,y8(j))}function k8($){let j=I8($),J=Nj(j),Z=Tj(J);if(!Z.report)return;return J5(Z.report)?Z.report:void 0}function Q5($){let j=D8($,"acceptance-report"),J=[];for(let Q of j)try{let X=Z5(Q);if(X.report)return{report:X.report};J.push(`Invalid acceptance-report: ${X.errors.join("; ")}`)}catch(X){J.push(X instanceof Error?X.message:String(X))}if(J.length>0)return{error:`Failed to parse acceptance-report: ${J.join("; ")}`};for(let Q of D8($,"(?:json|jsonc|json5)"))try{let X=k8(Q);if(X)return{report:X}}catch{}let Z=$.search(/ACCEPTANCE_REPORT\s*:/i);if(Z!==-1){let Q=$.indexOf("{",Z);if(Q!==-1){let X=w8($,Q);if(X)try{let W=JSON.parse(X),U=Nj(W),G=Tj(U,y8(W));if(G.report)return{report:G.report};return{error:`Failed to parse acceptance-report: Invalid acceptance-report: ${G.errors.join("; ")}`}}catch(W){return{error:W instanceof Error?W.message:String(W)}}}}return{error:"Structured acceptance report not found."}}function Cj($){let j=/\n?```(acceptance-report|json|jsonc|json5)\s*\n([\s\S]*?)```\s*/gi,J;for(let Z of $.matchAll(j)){let Q=(Z.index??0)+Z[0].length;if($.slice(Q).trim().length===0&&Z[1]&&Z[2])J={index:Z.index??0,tag:Z[1].toLowerCase(),body:Z[2]}}if(J){if(J.tag==="acceptance-report")return $.slice(0,J.index).trimEnd();try{if(k8(J.body))return $.slice(0,J.index).trimEnd()}catch{}}return $.replace(/\n?```acceptance-report\s*\n[\s\S]*?```\s*$/i,"").replace(/\n?ACCEPTANCE_REPORT\s*:\s*\{[\s\S]*\}\s*$/i,"").trimEnd()}function i$($){return Array.isArray($)&&$.every((j)=>typeof j==="string")}function I$($,j){return $?`${$}.${j}`:j}function X5($){if($===void 0)return"missing";if($===null)return"null";if(Array.isArray($))return"array";if(typeof $==="object")return"object";if(typeof $==="string"){let j=$.length>80?`${$.slice(0,77)}...`:$;return JSON.stringify(j)}return`${typeof $} ${String($)}`}function L$($,j,J,Z){$.push(`${j}: expected ${J}; got ${X5(Z)}`)}function c0($,j,J){if(!Array.isArray(j)){L$($,J,"string[]",j);return}for(let[Z,Q]of j.entries())if(typeof Q!=="string")L$($,`${J}[${Z}]`,"string",Q)}function Tj($,j=""){let J=[];if(!$||typeof $!=="object"||Array.isArray($))return L$(J,j||"acceptance-report","object",$),{errors:J};let Z=$;if(Z.criteriaSatisfied!==void 0)if(!Array.isArray(Z.criteriaSatisfied))L$(J,I$(j,"criteriaSatisfied"),"array",Z.criteriaSatisfied);else for(let[X,W]of Z.criteriaSatisfied.entries()){let U=`${I$(j,"criteriaSatisfied")}[${X}]`;if(!W||typeof W!=="object"||Array.isArray(W)){L$(J,U,"object",W);continue}let G=W;if(G.id!==void 0&&typeof G.id!=="string")L$(J,`${U}.id`,"string",G.id);if(G.status!=="satisfied"&&G.status!=="not-satisfied"&&G.status!=="not-applicable")L$(J,`${U}.status`,'one of "satisfied", "not-satisfied", "not-applicable"',G.status);if(typeof G.evidence!=="string"||!G.evidence.trim())L$(J,`${U}.evidence`,"non-empty string",G.evidence)}if(Z.changedFiles!==void 0)c0(J,Z.changedFiles,I$(j,"changedFiles"));if(Z.testsAddedOrUpdated!==void 0)c0(J,Z.testsAddedOrUpdated,I$(j,"testsAddedOrUpdated"));if(Z.commandsRun!==void 0)if(!Array.isArray(Z.commandsRun))L$(J,I$(j,"commandsRun"),"array",Z.commandsRun);else for(let[X,W]of Z.commandsRun.entries()){let U=`${I$(j,"commandsRun")}[${X}]`;if(!W||typeof W!=="object"||Array.isArray(W)){L$(J,U,"object",W);continue}let G=W;if(typeof G.command!=="string"||!G.command.trim())L$(J,`${U}.command`,"non-empty string",G.command);if(G.result!=="passed"&&G.result!=="failed"&&G.result!=="not-run")L$(J,`${U}.result`,'one of "passed", "failed", "not-run"',G.result);if(typeof G.summary!=="string")L$(J,`${U}.summary`,"string",G.summary)}if(Z.validationOutput!==void 0)c0(J,Z.validationOutput,I$(j,"validationOutput"));if(Z.residualRisks!==void 0)c0(J,Z.residualRisks,I$(j,"residualRisks"));if(Z.noStagedFiles!==void 0&&typeof Z.noStagedFiles!=="boolean")L$(J,I$(j,"noStagedFiles"),"boolean",Z.noStagedFiles);if(Z.diffSummary!==void 0&&typeof Z.diffSummary!=="string")L$(J,I$(j,"diffSummary"),"string",Z.diffSummary);if(Z.reviewFindings!==void 0)c0(J,Z.reviewFindings,I$(j,"reviewFindings"));if(Z.manualNotes!==void 0&&typeof Z.manualNotes!=="string")L$(J,I$(j,"manualNotes"),"string",Z.manualNotes);if(Z.notes!==void 0&&typeof Z.notes!=="string")L$(J,I$(j,"notes"),"string",Z.notes);if(J.length>0)return{errors:J};return Z.criteriaSatisfied!==void 0||Z.changedFiles!==void 0||Z.testsAddedOrUpdated!==void 0||Z.commandsRun!==void 0||Z.validationOutput!==void 0||Z.residualRisks!==void 0||Z.noStagedFiles!==void 0||Z.diffSummary!==void 0||Z.manualNotes!==void 0||Z.notes!==void 0||Z.reviewFindings!==void 0?{report:Z,errors:J}:{errors:[`${j||"acceptance-report"}: expected at least one acceptance report field`]}}function Y5($,j){let J=new Map((j.criteriaSatisfied??[]).filter((Z)=>Z.id).map((Z)=>[Z.id,Z]));return $.filter((Z)=>Z.severity!=="recommended").map((Z)=>{let Q=J.get(Z.id);if(!Q)return{id:`criterion:${Z.id}`,status:"failed",message:`Required criterion '${Z.id}' was not reported.`};if(Q.status!=="satisfied")return{id:`criterion:${Z.id}`,status:"failed",message:`Required criterion '${Z.id}' was reported as ${Q.status}.`};return{id:`criterion:${Z.id}`,status:"passed",message:`Required criterion '${Z.id}' satisfied.`}})}function W5($,j){switch(j){case"changed-files":return i$($.changedFiles)&&$.changedFiles.length>0;case"tests-added":return i$($.testsAddedOrUpdated)&&$.testsAddedOrUpdated.length>0;case"commands-run":return Array.isArray($.commandsRun)&&$.commandsRun.length>0;case"validation-output":return i$($.validationOutput)&&$.validationOutput.length>0;case"residual-risks":return i$($.residualRisks);case"no-staged-files":return $.noStagedFiles===!0;case"diff-summary":return typeof $.diffSummary==="string"&&$.diffSummary.trim().length>0;case"review-findings":return i$($.reviewFindings);case"manual-notes":return Boolean(($.manualNotes??$.notes)?.trim())}}function H5($){let j=e4("git",["status","--short"],{cwd:$,encoding:"utf-8"});if(j.status!==0)return{id:"no-staged-files",status:"not-applicable",message:"git status unavailable; no staged-files check skipped"};let J=j.stdout.split(/\r?\n/).filter((Z)=>Z.length>=2&&Z[0]!==" "&&Z[0]!=="?");return J.length===0?{id:"no-staged-files",status:"passed",message:"No staged files detected."}:{id:"no-staged-files",status:"failed",message:`Staged files present: ${J.join(", ")}`}}function V5($,j,J){let Z=[];for(let Q of $.evidence){let X=W5(j,Q);Z.push({id:`evidence:${Q}`,status:X?"passed":"failed",message:X?`${Q} evidence present.`:`${Q} evidence missing from child report.`})}if($.evidence.includes("no-staged-files"))Z.push(H5(J));return Z}function d0($){let j=$.trim();if(!j)return;return j.length>12000?`${j.slice(0,12000)}
44
+ ...[truncated]`:j}function o0($){return $5($.map((j)=>j?.trim()).filter((j)=>Boolean(j)))}function Ej($){let j=$.results.map((Q)=>Q.acceptance?.childReport).filter((Q)=>Boolean(Q)),J=$.results.filter((Q)=>Q.exitCode!==0||Q.acceptance?.status==="rejected"),Z=$.results.length>0&&J.length===0;return{criteriaSatisfied:[{id:"criterion-1",status:Z?"satisfied":"not-satisfied",evidence:Z?`All ${$.results.length} dynamic child run(s) completed without child or acceptance blockers.`:"Dynamic fanout produced no accepted child evidence."},{id:"criterion-2",status:Z?"satisfied":"not-satisfied",evidence:Z?"Collected child acceptance evidence for aggregate review.":"Dynamic fanout produced no aggregate review evidence."},...$.results.map((Q,X)=>({id:`child-${X+1}`,status:Q.exitCode===0&&Q.acceptance?.status!=="rejected"?"satisfied":"not-satisfied",evidence:`${Q.agent}: acceptance ${Q.acceptance?.status??"unreported"}${Q.error?` (${Q.error})`:""}`}))],changedFiles:o0(j.flatMap((Q)=>Q.changedFiles??[])),testsAddedOrUpdated:o0(j.flatMap((Q)=>Q.testsAddedOrUpdated??[])),commandsRun:j.flatMap((Q)=>Q.commandsRun??[]),validationOutput:o0(j.flatMap((Q)=>Q.validationOutput??[])),residualRisks:o0([...j.flatMap((Q)=>Q.residualRisks??[]),...J.map((Q)=>`${Q.agent}: ${Q.error??"child or acceptance gate failed"}`)]),noStagedFiles:j.length>0&&j.every((Q)=>Q.noStagedFiles===!0),reviewFindings:o0(j.flatMap((Q)=>Q.reviewFindings??[])),manualNotes:$.notes??`Aggregated acceptance evidence from ${$.results.length} dynamic fanout child run(s).`,notes:$.notes}}function K5($,j,J={}){return new Promise((Z)=>{let Q=Date.now(),X=$.cwd?b8.resolve(j,$.cwd):j,W="",U="",G=!1,B=!1,q,O=t4($.command,{cwd:X,env:{...process.env,...$.env??{}},shell:!0,stdio:["ignore","pipe","pipe"],windowsHide:!0}),T=(S)=>{if(B)return;if(B=!0,clearTimeout(h),q)clearTimeout(q);J.signal?.removeEventListener("abort",y),Z({id:$.id,command:$.command,cwd:X,durationMs:Date.now()-Q,...S})},y=()=>{if(B||G)return;G=!0,O.kill("SIGTERM"),q=setTimeout(()=>{O.kill("SIGKILL"),T({exitCode:null,status:"timed-out",stdout:d0(W),stderr:d0(U||J.abortMessage||"Acceptance verification timed out.")})},1000),q.unref?.()},h=setTimeout(y,$.timeoutMs??120000);if(h.unref?.(),J.signal?.aborted)y();else J.signal?.addEventListener("abort",y,{once:!0});O.stdout.on("data",(S)=>{W+=S.toString()}),O.stderr.on("data",(S)=>{U+=S.toString()}),O.on("close",(S)=>{T({exitCode:S,status:G?"timed-out":S===0&&!G?"passed":$.allowFailure?"allowed-failure":"failed",stdout:d0(W),stderr:d0(U||(G?J.abortMessage??"":""))})}),O.on("error",(S)=>{T({exitCode:G?null:1,status:G?"timed-out":$.allowFailure?"allowed-failure":"failed",stderr:G?d0(U||J.abortMessage||"Acceptance verification timed out."):S instanceof Error?S.message:String(S)})})})}async function M1($){let j=$.acceptance,J={status:j.level==="none"?"not-required":"claimed",explicit:j.explicit,effectiveAcceptance:j,inferredReason:j.inferredReason,criteria:j.criteria,runtimeChecks:[],verifyRuns:[]};if(j.level==="none")return J;let Z=$.report?{report:$.report}:Q5($.output);if(Z.report)J.childReport=Z.report,J.status="attested";else return J.childReportParseError=Z.error,J.runtimeChecks.push({id:"attestation",status:"failed",message:Z.error??"Structured acceptance report missing."}),J.status="rejected",J;if(_1[j.level]>=_1.checked){if(J.runtimeChecks=[...Y5(j.criteria,Z.report),...V5(j,Z.report,$.cwd)],J.runtimeChecks.some((Q)=>Q.status==="failed"))return J.status="rejected",J;J.status="checked"}if(_1[j.level]>=_1.verified&&(j.level==="verified"||j.verify.length>0)){if(j.level==="verified"&&j.verify.length===0)return J.runtimeChecks.push({id:"verification-config",status:"failed",message:"verified acceptance requires runtime verify commands."}),J.status="rejected",J;J.verifyRuns=[];for(let Q of j.verify)if(J.verifyRuns.push(await K5(Q,$.cwd,{signal:$.signal,abortMessage:$.abortMessage})),$.signal?.aborted)break;if(J.verifyRuns.some((Q)=>Q.status==="failed"||Q.status==="timed-out"))return J.status="rejected",J;J.status="verified"}if(j.level==="reviewed")if($.reviewResult)J.reviewResult=$.reviewResult,J.status=$.reviewResult.status==="no-blockers"?"reviewed":"rejected";else{let Q=j.review&&j.review!==!1&&j.review.required===!1;if(J.reviewResult={status:"needs-parent-decision",findings:[{severity:j.explicit&&!Q?"blocker":"non-blocking",issue:"Reviewed acceptance requires an independent reviewer result.",rationale:"The run cannot be marked reviewed from child evidence alone."}]},j.review===!1||j.explicit&&!Q)J.status="rejected"}return J}function L1($){if($.status!=="rejected")return;let j=$.runtimeChecks.find((Z)=>Z.status==="failed");if(j)return`Acceptance rejected: ${j.message}`;let J=$.verifyRuns.find((Z)=>Z.status==="failed"||Z.status==="timed-out");if(J)return`Acceptance verification '${J.id}' ${J.status}.`;if($.reviewResult?.status==="needs-parent-decision")return"Acceptance review required but no automatic reviewer result is available.";if($.reviewResult?.status==="blockers")return"Acceptance review found blockers.";return"Acceptance rejected."}import*as q1 from"node:fs";var U5=new Set(["complete","failed","paused"]),z5=new Set(["complete","completed","failed","paused"]);function G5($){try{return JSON.parse(q1.readFileSync($,"utf-8"))}catch(j){if(typeof j==="object"&&j!==null&&"code"in j&&j.code==="ENOENT")return;throw j}}function F1($,j){return $?.steps?.[j]}function B5($,j){if(!$)return!1;let J=F1($,j);if(J&&z5.has(J.status))return!0;return U5.has($.state)}function _5($,j){if(!$)return;if(j?.success===!0)return"complete";if(j?.success===!1)return $.state==="paused"?"paused":"failed";if($.state==="complete"||$.state==="failed"||$.state==="paused")return $.state;if($.success===!0)return"complete";if($.success===!1)return"failed";return}function M5($,j,J){let Z=J?.agent??j.steps?.[$.index]?.agent??"subagent",Q=J?.timedOut===!0||j.timedOut===!0,X=J?.error??j.error??`Attached async root ${$.runId} ended without a result file at ${$.resultPath}.`;return{agent:Z,output:X,success:!1,exitCode:1,error:X,...Q?{timedOut:!0}:{},...J?.sessionFile??j.sessionFile?{sessionFile:J?.sessionFile??j.sessionFile}:{},...J?.model?{model:J.model}:{},...J?.attemptedModels?{attemptedModels:J.attemptedModels}:{},...J?.modelAttempts?{modelAttempts:J.modelAttempts}:{},...J?.totalCost?{totalCost:J.totalCost}:{},...J?.structuredOutput!==void 0?{structuredOutput:J.structuredOutput}:{},...J?.structuredOutputPath?{structuredOutputPath:J.structuredOutputPath}:{},...J?.structuredOutputSchemaPath?{structuredOutputSchemaPath:J.structuredOutputSchemaPath}:{},...J?.acceptance?{acceptance:J.acceptance}:{}}}function L5($,j,J){let Z=F1(j,$.index);return{agent:Z?.agent??j?.steps?.[$.index]?.agent??"subagent",output:J,success:!1,exitCode:1,error:J,timedOut:!0,...Z?.sessionFile??j?.sessionFile?{sessionFile:Z?.sessionFile??j?.sessionFile}:{},...Z?.model?{model:Z.model}:{},...Z?.attemptedModels?{attemptedModels:Z.attemptedModels}:{},...Z?.modelAttempts?{modelAttempts:Z.modelAttempts}:{},...Z?.totalCost?{totalCost:Z.totalCost}:{}}}function q5($,j,J){let Z=J.results?.[$.index],Q=F1(j,$.index),X=_5(J,Z),W=Z?.agent??Q?.agent??j?.steps?.[$.index]?.agent??"subagent",U=Z?.output??J.summary??"",G=Z?.timedOut===!0||Q?.timedOut===!0||J.timedOut===!0||j?.timedOut===!0,B=X==="complete"&&!G,q=Z?.error??(B?void 0:J.error??J.summary??j?.error??`Attached async root ${$.runId} did not complete successfully.`);return{agent:W,output:B?U:U||q||"",success:B,exitCode:B?0:1,...q?{error:q}:{},...G?{timedOut:!0}:{},...Z?.sessionFile??Q?.sessionFile??j?.sessionFile?{sessionFile:Z?.sessionFile??Q?.sessionFile??j?.sessionFile}:{},...Z?.intercomTarget?{intercomTarget:Z.intercomTarget}:{},...Z?.model??Q?.model?{model:Z?.model??Q?.model}:{},...Z?.attemptedModels??Q?.attemptedModels?{attemptedModels:Z?.attemptedModels??Q?.attemptedModels}:{},...Z?.modelAttempts??Q?.modelAttempts?{modelAttempts:Z?.modelAttempts??Q?.modelAttempts}:{},...Z?.totalCost??Q?.totalCost?{totalCost:Z?.totalCost??Q?.totalCost}:{},...Z?.structuredOutput!==void 0?{structuredOutput:Z.structuredOutput}:Q?.structuredOutput!==void 0?{structuredOutput:Q.structuredOutput}:{},...Z?.structuredOutputPath??Q?.structuredOutputPath?{structuredOutputPath:Z?.structuredOutputPath??Q?.structuredOutputPath}:{},...Z?.structuredOutputSchemaPath??Q?.structuredOutputSchemaPath?{structuredOutputSchemaPath:Z?.structuredOutputSchemaPath??Q?.structuredOutputSchemaPath}:{},...Z?.acceptance??Q?.acceptance?{acceptance:Z?.acceptance??Q?.acceptance}:{}}}async function f8($,j={}){let J=j.pollIntervalMs??500,Z=j.terminalResultGraceMs??1000,Q=j.now??Date.now,X;for(;;){let W=R0($.asyncDir);if(j.shouldAbort?.())return L5($,W,j.timeoutMessage??"Subagent timed out.");let U=G5($.resultPath);if(U)return q5($,W,U);if(B5(W,$.index)){if(X??=Q(),Q()-X>=Z)return M5($,W,F1(W,$.index))}else X=void 0;if(!W&&!q1.existsSync($.asyncDir))throw Error(`Attached async root '${$.runId}' directory does not exist: ${$.asyncDir}`);await new Promise((G)=>setTimeout(G,J))}}import*as _0 from"node:fs";import*as Sj from"node:path";var F5="append-requests";function O5($){return Sj.join($,F5)}function x8($){let j=O5($);try{return _0.readdirSync(j).filter((J)=>J.endsWith(".json")).map((J)=>Sj.join(j,J)).sort()}catch(J){if(J.code==="ENOENT")return[];throw J}}function Dj($){return x8($).length}function A5($){let j=JSON.parse(_0.readFileSync($,"utf-8"));if(!j.id||typeof j.id!=="string")return;if(!Number.isFinite(j.createdAt))return;if(!Array.isArray(j.steps)||j.steps.length===0)return;return{id:j.id,createdAt:j.createdAt,steps:j.steps}}function h8($){let j=[];for(let J of x8($)){let Z=A5(J);try{_0.unlinkSync(J)}catch{}if(Z)j.push(Z)}return j.sort((J,Z)=>J.createdAt-Z.createdAt||J.id.localeCompare(Z.id))}function P8($){return{agent:$.agent,phase:$.phase,label:$.label,outputName:$.outputName,structured:$.structured,status:"pending",...$.sessionFile?{sessionFile:$.sessionFile}:{},skills:$.skills,model:$.model,thinking:$.thinking,attemptedModels:$.modelCandidates&&$.modelCandidates.length>0?$.modelCandidates:$.model?[$.model]:void 0,recentTools:[],recentOutput:[]}}function N5($){if($0($))return $.parallel.map(P8);if(j0($))return[{agent:`expand:${$.parallel.agent}`,phase:$.phase??$.parallel.phase,label:$.label??$.parallel.label??`Dynamic fanout (${$.collect.as})`,outputName:$.collect.as,structured:Boolean($.collect.outputSchema),status:"pending",recentTools:[],recentOutput:[]}];return[P8($)]}function v8($,j,J){if(!j)return;let Z=$.phases.find((Q)=>Q.title===j);if(!Z)Z={title:j,nodeIds:[]},$.phases.push(Z);Z.nodeIds.push(J)}function C5($,j,J){return{id:`step-${j}`,kind:"step",agent:$.agent,phase:$.phase,label:$.label?.trim()||$.agent||`Step ${j+1}`,status:"pending",flatIndex:J,stepIndex:j,outputName:$.outputName,structured:$.structured}}function T5($,j,J,Z){let Q=$.parallel.map((X,W)=>{let U=`step-${j}-agent-${W}`;return v8(Z,X.phase,U),{id:U,kind:"agent",agent:X.agent,phase:X.phase,label:X.label?.trim()||X.agent||`Agent ${W+1}`,status:"pending",flatIndex:J+W,stepIndex:j,outputName:X.outputName,structured:X.structured}});return{id:`step-${j}`,kind:"parallel-group",label:$.parallel.length===1?"Parallel task":`Parallel group (${$.parallel.length})`,status:"pending",stepIndex:j,children:Q}}function E5($,j){return{id:`step-${j}`,kind:"dynamic-parallel-group",label:$.label?.trim()||$.parallel.label?.trim()||`Dynamic fanout (${$.collect.as})`,status:"pending",stepIndex:j,outputName:$.collect.as,structured:Boolean($.collect.outputSchema),dynamic:{sourceOutput:$.expand.from.output,sourcePath:$.expand.from.path,itemName:$.expand.item??"item",maxItems:$.expand.maxItems,collectAs:$.collect.as},children:[]}}function S5($,j,J,Z){if(!$)return;if($0(j)){$.nodes.push(T5(j,J,Z,$));return}if(j0(j)){$.nodes.push(E5(j,J));return}let Q=C5(j,J,Z);$.nodes.push(Q),v8($,j.phase,Q.id)}function g8($){let j=0,J=0;for(let Z of $.steps){let Q=$.status.chainStepCount??$.status.steps?.length??0,X=$.status.steps?.length??0,W=N5(Z);if($.status.steps??=[],$.status.steps.push(...W),$0(Z))$.status.parallelGroups??=[],$.status.parallelGroups.push({start:X,count:Z.parallel.length,stepIndex:Q});else if(j0(Z))$.status.parallelGroups??=[],$.status.parallelGroups.push({start:X,count:1,stepIndex:Q});S5($.status.workflowGraph,Z,Q,X),$.status.chainStepCount=Q+1,j++,J+=W.length}return $.status.pendingAppends=$.pendingAppends??0,$.status.lastUpdate=$.now??Date.now(),{addedChainSteps:j,addedFlatSteps:J}}function m8($,j){if(!j)return $;let J=j.graceTurns===1?"1 additional assistant turn":`${j.graceTurns} additional assistant turns`,Z=["## Turn budget",`This child run has a soft budget of ${j.maxTurns} assistant turn${j.maxTurns===1?"":"s"}.`,`After that, ${J} may be allowed only for a final wrap-up.`,"When you approach or reach the soft budget, stop starting new tool work and return the final answer immediately.","This runner uses process-mode execution, so live steering after launch may be unavailable; treat this instruction as the wrap-up request.","If you continue past the soft budget plus grace turns, the supervisor may abort the process and return only partial output."].join(`
45
45
  `);return $.trim()?`${$.trim()}
46
46
 
47
47
  ${Z}`:Z}function bj($,j){return`Turn budget wrap-up was requested after ${j} assistant turn${j===1?"":"s"} (soft limit ${$.maxTurns}, grace ${$.graceTurns}). Process-mode live steering is unavailable, so the child was warned at launch to wrap up by this budget. Output may be partial.`}function u0($,j){return`Subagent exceeded turn budget after ${j} assistant turn${j===1?"":"s"} (soft limit ${$.maxTurns} + grace ${$.graceTurns}).`}function c8($,j){return j.trim()?`${$}
48
48
 
49
49
  Partial output before turn-budget abort:
50
- ${j}`:$}function Rj($){return{...$,outcome:"within-budget",turnCount:0}}function O1($,j,J){return{...$,turnCount:j,outcome:J?"exceeded":"wrap-up-requested",wrapUpRequestedAtTurn:$.maxTurns,...J?{exceededAtTurn:j}:{}}}function wj($,j,J){let Z=$.maxTurns+$.graceTurns;if(j<Z)return!1;if(j>Z)return!0;return!J}var b5=process.platform==="win32"?"SIGBREAK":"SIGUSR2",o8=52428800,R5="DM_SUBAGENT_ASYNC_EVENTS_MAX_BYTES",w5="subagent.events.truncated",I5=512,xj=new Map;function y5(){let $=process.env[R5];if(!$)return o8;let j=Number($);if(!Number.isFinite(j)||j<0)return o8;return Math.floor(j)}function k5($){let j=xj.get($);if(j)return j;let J=0;try{J=e.statSync($).size}catch(Z){if(Z.code!=="ENOENT");}return j={bytes:J,diagnosticsTruncated:!1},xj.set($,j),j}function $$($,j){try{d1($,j);let J=xj.get($);if(J)J.bytes+=Buffer.byteLength(`${j}
51
- `,"utf-8")}catch{}}function f5($,j,J){if(!j.trim())return;let Z=k5($);if(Z.diagnosticsTruncated)return;let Q=y5(),X=Buffer.byteLength(`${j}
52
- `,"utf-8"),W=Math.max(0,Q-I5);if(Z.bytes+X<=W){$$($,j);return}let K=JSON.stringify({type:w5,ts:Date.now(),maxBytes:Q,droppedEventType:J});if(Z.bytes+Buffer.byteLength(`${K}
53
- `,"utf-8")<=Q)$$($,K);Z.diagnosticsTruncated=!0}function P5($){return $.type!=="message_update"}function x5($){try{let j=e.readdirSync($).filter((J)=>J.endsWith(".jsonl")).map((J)=>r.join($,J));if(j.length===0)return null;return j.sort((J,Z)=>e.statSync(Z).mtimeMs-e.statSync(J).mtimeMs),j[0]??null}catch{return null}}function h5(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,turns:0}}function u8($){if(!$||$.length===0)return null;let j=0,J=0;for(let Q of $)j+=Q.usage?.input??0,J+=Q.usage?.output??0;let Z=j+J;return Z>0?{input:j,output:J,total:Z}:null}function v5($){if(!$||$.length===0)return;let j=0,J=0,Z=0;for(let Q of $)j+=Q.usage?.input??0,J+=Q.usage?.output??0,Z+=Q.usage?.cost??0;return j>0||J>0||Z>0?{inputTokens:j,outputTokens:J,costUsd:Z}:void 0}function Ij($,j){let J=j.filter((Z)=>Z.trim());if(J.length===0)return;if($.recentOutput??=[],$.recentOutput.push(...J),$.recentOutput.length>50)$.recentOutput.splice(0,$.recentOutput.length-50)}function hj($){let j=$.stopReason,J=Array.isArray($.content)&&$.content.some((Z)=>Z.type==="toolCall");return j==="stop"&&!J}function yj($){$.currentTool=void 0,$.currentToolArgs=void 0,$.currentToolStartedAt=void 0,$.currentPath=void 0,$.recentTools=[],$.recentOutput=[]}function g5($,j,J,Z,Q,X,W,K,G,B,q,O,T,y){return new Promise((h)=>{let S=e.createWriteStream(J,{flags:"w"}),v$={...process.env,...Z??{},...rj(W)},k=GJ($,{...Q?{piPackageRoot:Q}:{},...X?{argv1:X}:{}}),f=S5(k.command,k.args,{cwd:j,stdio:["ignore","pipe","pipe"],env:v$,windowsHide:!0}),n="",d$="",W$="",y$=[],V$=h5(),g$,O$,s,E$=!1,X$=!1,B$=!1,E,t,p=!1,L$=[],Y$=(P)=>{if(!P.trim())return;S.write(`${P}
50
+ ${j}`:$}function Rj($){return{...$,outcome:"within-budget",turnCount:0}}function O1($,j,J){return{...$,turnCount:j,outcome:J?"exceeded":"wrap-up-requested",wrapUpRequestedAtTurn:$.maxTurns,...J?{exceededAtTurn:j}:{}}}function wj($,j,J){let Z=$.maxTurns+$.graceTurns;if(j<Z)return!1;if(j>Z)return!0;return!J}var R5=process.platform==="win32"?"SIGBREAK":"SIGUSR2",o8=52428800,w5="DM_SUBAGENT_ASYNC_EVENTS_MAX_BYTES",I5="subagent.events.truncated",y5=512,xj=new Map;function k5(){let $=process.env[w5];if(!$)return o8;let j=Number($);if(!Number.isFinite(j)||j<0)return o8;return Math.floor(j)}function f5($){let j=xj.get($);if(j)return j;let J=0;try{J=e.statSync($).size}catch(Z){if(Z.code!=="ENOENT");}return j={bytes:J,diagnosticsTruncated:!1},xj.set($,j),j}function $$($,j){try{d1($,j);let J=xj.get($);if(J)J.bytes+=Buffer.byteLength(`${j}
51
+ `,"utf-8")}catch{}}function P5($,j,J){if(!j.trim())return;let Z=f5($);if(Z.diagnosticsTruncated)return;let Q=k5(),X=Buffer.byteLength(`${j}
52
+ `,"utf-8"),W=Math.max(0,Q-y5);if(Z.bytes+X<=W){$$($,j);return}let U=JSON.stringify({type:I5,ts:Date.now(),maxBytes:Q,droppedEventType:J});if(Z.bytes+Buffer.byteLength(`${U}
53
+ `,"utf-8")<=Q)$$($,U);Z.diagnosticsTruncated=!0}function x5($){return $.type!=="message_update"}function h5($){try{let j=e.readdirSync($).filter((J)=>J.endsWith(".jsonl")).map((J)=>r.join($,J));if(j.length===0)return null;return j.sort((J,Z)=>e.statSync(Z).mtimeMs-e.statSync(J).mtimeMs),j[0]??null}catch{return null}}function v5(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,turns:0}}function u8($){if(!$||$.length===0)return null;let j=0,J=0;for(let Q of $)j+=Q.usage?.input??0,J+=Q.usage?.output??0;let Z=j+J;return Z>0?{input:j,output:J,total:Z}:null}function g5($){if(!$||$.length===0)return;let j=0,J=0,Z=0;for(let Q of $)j+=Q.usage?.input??0,J+=Q.usage?.output??0,Z+=Q.usage?.cost??0;return j>0||J>0||Z>0?{inputTokens:j,outputTokens:J,costUsd:Z}:void 0}function Ij($,j){let J=j.filter((Z)=>Z.trim());if(J.length===0)return;if($.recentOutput??=[],$.recentOutput.push(...J),$.recentOutput.length>50)$.recentOutput.splice(0,$.recentOutput.length-50)}function hj($){let j=$.stopReason,J=Array.isArray($.content)&&$.content.some((Z)=>Z.type==="toolCall");return j==="stop"&&!J}function yj($){$.currentTool=void 0,$.currentToolArgs=void 0,$.currentToolStartedAt=void 0,$.currentPath=void 0,$.recentTools=[],$.recentOutput=[]}function m5($,j,J,Z,Q,X,W,U,G,B,q,O,T,y){return new Promise((h)=>{let S=e.createWriteStream(J,{flags:"w"}),v$={...process.env,...Z??{},...rj(W)},k=GJ($,{...Q?{piPackageRoot:Q}:{},...X?{argv1:X}:{}}),f=D5(k.command,k.args,{cwd:j,stdio:["ignore","pipe","pipe"],env:v$,windowsHide:!0}),n="",d$="",W$="",y$=[],K$=v5(),g$,A$,s,S$=!1,X$=!1,_$=!1,E,t,p=!1,q$=[],Y$=(P)=>{if(!P.trim())return;S.write(`${P}
54
54
  `)},o$=(P)=>{for(let D of P.split(`
55
- `))Y$(D)},u$=(P)=>{if(!K)return;if(!P5(P))return;f5(K.eventsPath,JSON.stringify({...P,subagentSource:"child",subagentRunId:K.runId,subagentStepIndex:K.stepIndex,subagentAgent:K.agent,observedAt:Date.now()}),typeof P.type==="string"?P.type:void 0)},j$=(P,D)=>{if(u$({type:P,line:D}),P==="subagent.child.stdout")q?.writeStdoutLine(D);else q?.writeStderrLine(D)},c=(P)=>{if(!P.trim())return;let D;try{D=JSON.parse(P)}catch{L$.push(P),Y$(P),j$("subagent.child.stdout",P);return}if(u$(D),q?.writeChildEvent(D),B?.(D),D.type==="tool_execution_start"&&D.toolName){p=p||qj(D.toolName,D.args);let i=w0(D.args??{});Y$(i?`${D.toolName}: ${i}`:D.toolName);return}if((D.type==="message_end"||D.type==="tool_result_end")&&D.message){y$.push(D.message);let i=s$(D.message.content);if(i)o$(i);if(D.type!=="message_end"||D.message.role!=="assistant")return;if(D.message.model)g$=D.message.model;if(D.message.errorMessage)s=D.message.errorMessage;let _$=D.message.usage;if(_$)V$.turns++,V$.input+=_$.input??_$.inputTokens??0,V$.output+=_$.output??_$.outputTokens??0,V$.cacheRead+=_$.cacheRead??0,V$.cacheWrite+=_$.cacheWrite??0,V$.cost+=_$.cost?.total??0;if(hj(D.message)){if(!D.message.errorMessage&&s$(D.message.content).trim())s=void 0;a||=!D.message.errorMessage,e$()}}},H$=(P)=>{if(n+=P,W$+=P,S.write(P),!K)return;let D=W$.split(`
56
- `);W$=D.pop()||"";for(let i of D){if(!i.trim())continue;j$("subagent.child.stderr",i)}},k$=1000,W0=3000,Y=3000,u=!1,K$=!1,a=!1,A$,f$,S$,t$,P$,U$=!1,l$=H8(f,{idleMs:2000,hardMs:8000});f.stdout.on("data",(P)=>{let D=P.toString();d$+=D;let i=d$.split(`
57
- `);d$=i.pop()||"";for(let _$ of i)c(_$)}),f.stderr.on("data",(P)=>{H$(P.toString())}),G?.(()=>{if(U$||X$)return;if(E$=!0,!O$)O$="Interrupted. Waiting for explicit next action.";n$(f,"SIGINT"),setTimeout(()=>{if(!U$&&!X$)n$(f,"SIGTERM")},1000).unref?.()}),O?.(()=>{if(U$||X$)return;X$=!0,E$=!1,O$=T??"Subagent timed out.",n$(f,"SIGTERM"),S$=setTimeout(()=>{if(!U$)n$(f,"SIGKILL")},Y),S$.unref?.()}),y?.((P,D)=>{if(U$||X$||B$)return;B$=!0,E=P,t=D,E$=!1,O$=P,n$(f,"SIGINT"),t$=setTimeout(()=>{if(!U$&&!X$)n$(f,"SIGTERM")},1000),t$.unref?.(),P$=setTimeout(()=>{if(!U$&&!X$)n$(f,"SIGKILL")},4000),P$.unref?.()});let p$=()=>{if(A$)clearTimeout(A$),A$=void 0;if(f$)clearTimeout(f$),f$=void 0;if(S$)clearTimeout(S$),S$=void 0;if(t$)clearTimeout(t$),t$=void 0;if(P$)clearTimeout(P$),P$=void 0};function e$(){if(u||A$||U$)return;A$=setTimeout(()=>{if(U$)return;if(!n$(f,"SIGTERM"))return;if(K$=!0,!a&&!O$&&!s)O$=`Subagent process did not exit within ${k$}ms after its final message. Forcing termination.`;f$=setTimeout(()=>{if(U$)return;K$=n$(f,"SIGKILL")||K$},W0),f$.unref?.()},k$),A$.unref?.()}f.on("exit",()=>{u=!0,p$()}),f.on("close",(P,D)=>{if(U$=!0,G?.(void 0),O?.(void 0),y?.(void 0),p$(),l$(),d$.trim())c(d$);if(W$.trim())j$("subagent.child.stderr",W$);S.end();let i=j1(y$)||L$.join(`
58
- `).trim(),_$=O$??s,l0=K$&&a&&!_$;h({stderr:n,exitCode:X$?1:B$?1:E$||l0?0:K$||D?P??1:P,messages:y$,usage:V$,model:g$,error:X$?T??"Subagent timed out.":B$?E:E$||l0?void 0:_$,finalOutput:X$&&!i.trim()?T??"Subagent timed out.":i,interrupted:E$,timedOut:X$,turnBudget:t,turnBudgetExceeded:B$,wrapUpRequested:t?.outcome==="wrap-up-requested"||B$||void 0,observedMutationAttempt:p})}),f.on("error",(P)=>{U$=!0,G?.(void 0),O?.(void 0),y?.(void 0),p$(),l$(),S.end();let D=j1(y$)||L$.join(`
59
- `).trim(),i=P instanceof Error?P.message:String(P);h({stderr:n,exitCode:1,messages:y$,usage:V$,model:g$,error:X$?T??"Subagent timed out.":B$?E:O$??s??i,finalOutput:X$&&!D.trim()?T??"Subagent timed out.":D,timedOut:X$,turnBudget:t,turnBudgetExceeded:B$,wrapUpRequested:t?.outcome==="wrap-up-requested"||B$||void 0,observedMutationAttempt:p})})})}function m5(){let $=u1();if($)return $;throw Error(`Could not resolve ${k0} package root`)}async function c5($,j,J){let Z=J??m5(),Q=r.join(Z,"dist","core","export-html","index.js"),K=(await import(D5(Q).href)).exportFromFile;if(typeof K!=="function")throw Error("exportFromFile not available");let G=r.join(j,`${r.basename($,".jsonl")}.html`);return K($,{outputPath:G})}function d5($){try{if(d8("gh",["auth","status"],{encoding:"utf-8"}).status!==0)return{error:"GitHub CLI is not logged in. Run 'gh auth login' first."}}catch{return{error:"GitHub CLI (gh) is not installed."}}try{let j=d8("gh",["gist","create",$],{encoding:"utf-8"});if(j.status!==0)return{error:(j.stderr||"").trim()||"Failed to create gist."};let J=(j.stdout||"").trim(),Z=J.split("/").pop();if(!Z)return{error:"Failed to parse gist ID."};return{shareUrl:`https://shittycodingagent.ai/session/?${Z}`,gistUrl:J}}catch(j){return{error:String(j)}}}function l8($){if($<1000)return`${$}ms`;if($<60000)return`${($/1000).toFixed(1)}s`;let j=Math.floor($/60000),J=Math.floor($%60000/1000);return`${j}m${J}s`}function o5($,j){let J=[];if(J.push(`# Subagent run ${j.id}`),J.push(""),J.push(`- **Mode:** ${j.mode}`),J.push(`- **CWD:** ${j.cwd}`),J.push(`- **Started:** ${new Date(j.startedAt).toISOString()}`),J.push(`- **Ended:** ${new Date(j.endedAt).toISOString()}`),J.push(`- **Duration:** ${l8(j.endedAt-j.startedAt)}`),j.sessionFile)J.push(`- **Session:** ${j.sessionFile}`);if(j.shareUrl)J.push(`- **Share:** ${j.shareUrl}`);if(j.shareError)J.push(`- **Share error:** ${j.shareError}`);if(j.artifactsDir)J.push(`- **Artifacts:** ${j.artifactsDir}`);if(J.push(""),J.push("## Steps"),J.push("| Step | Agent | Status | Duration |"),J.push("| --- | --- | --- | --- |"),j.steps.forEach((Z,Q)=>{let X=Z.durationMs!==void 0?l8(Z.durationMs):"-";J.push(`| ${Q+1} | ${Z.agent} | ${Z.status} | ${X} |`)}),J.push(""),J.push("## Summary"),j.truncated)J.push("_Output truncated_"),J.push("");J.push(j.summary.trim()||"(no output)"),J.push(""),e.writeFileSync($,J.join(`
55
+ `))Y$(D)},u$=(P)=>{if(!U)return;if(!x5(P))return;P5(U.eventsPath,JSON.stringify({...P,subagentSource:"child",subagentRunId:U.runId,subagentStepIndex:U.stepIndex,subagentAgent:U.agent,observedAt:Date.now()}),typeof P.type==="string"?P.type:void 0)},j$=(P,D)=>{if(u$({type:P,line:D}),P==="subagent.child.stdout")q?.writeStdoutLine(D);else q?.writeStderrLine(D)},c=(P)=>{if(!P.trim())return;let D;try{D=JSON.parse(P)}catch{q$.push(P),Y$(P),j$("subagent.child.stdout",P);return}if(u$(D),q?.writeChildEvent(D),B?.(D),D.type==="tool_execution_start"&&D.toolName){p=p||qj(D.toolName,D.args);let i=w0(D.args??{});Y$(i?`${D.toolName}: ${i}`:D.toolName);return}if((D.type==="message_end"||D.type==="tool_result_end")&&D.message){y$.push(D.message);let i=s$(D.message.content);if(i)o$(i);if(D.type!=="message_end"||D.message.role!=="assistant")return;if(D.message.model)g$=D.message.model;if(D.message.errorMessage)s=D.message.errorMessage;let M$=D.message.usage;if(M$)K$.turns++,K$.input+=M$.input??M$.inputTokens??0,K$.output+=M$.output??M$.outputTokens??0,K$.cacheRead+=M$.cacheRead??0,K$.cacheWrite+=M$.cacheWrite??0,K$.cost+=M$.cost?.total??0;if(hj(D.message)){if(!D.message.errorMessage&&s$(D.message.content).trim())s=void 0;a||=!D.message.errorMessage,e$()}}},H$=(P)=>{if(n+=P,W$+=P,S.write(P),!U)return;let D=W$.split(`
56
+ `);W$=D.pop()||"";for(let i of D){if(!i.trim())continue;j$("subagent.child.stderr",i)}},k$=1000,W0=3000,Y=3000,u=!1,U$=!1,a=!1,N$,f$,D$,t$,P$,V$=!1,l$=H8(f,{idleMs:2000,hardMs:8000});f.stdout.on("data",(P)=>{let D=P.toString();d$+=D;let i=d$.split(`
57
+ `);d$=i.pop()||"";for(let M$ of i)c(M$)}),f.stderr.on("data",(P)=>{H$(P.toString())}),G?.(()=>{if(V$||X$)return;if(S$=!0,!A$)A$="Interrupted. Waiting for explicit next action.";n$(f,"SIGINT"),setTimeout(()=>{if(!V$&&!X$)n$(f,"SIGTERM")},1000).unref?.()}),O?.(()=>{if(V$||X$)return;X$=!0,S$=!1,A$=T??"Subagent timed out.",n$(f,"SIGTERM"),D$=setTimeout(()=>{if(!V$)n$(f,"SIGKILL")},Y),D$.unref?.()}),y?.((P,D)=>{if(V$||X$||_$)return;_$=!0,E=P,t=D,S$=!1,A$=P,n$(f,"SIGINT"),t$=setTimeout(()=>{if(!V$&&!X$)n$(f,"SIGTERM")},1000),t$.unref?.(),P$=setTimeout(()=>{if(!V$&&!X$)n$(f,"SIGKILL")},4000),P$.unref?.()});let p$=()=>{if(N$)clearTimeout(N$),N$=void 0;if(f$)clearTimeout(f$),f$=void 0;if(D$)clearTimeout(D$),D$=void 0;if(t$)clearTimeout(t$),t$=void 0;if(P$)clearTimeout(P$),P$=void 0};function e$(){if(u||N$||V$)return;N$=setTimeout(()=>{if(V$)return;if(!n$(f,"SIGTERM"))return;if(U$=!0,!a&&!A$&&!s)A$=`Subagent process did not exit within ${k$}ms after its final message. Forcing termination.`;f$=setTimeout(()=>{if(V$)return;U$=n$(f,"SIGKILL")||U$},W0),f$.unref?.()},k$),N$.unref?.()}f.on("exit",()=>{u=!0,p$()}),f.on("close",(P,D)=>{if(V$=!0,G?.(void 0),O?.(void 0),y?.(void 0),p$(),l$(),d$.trim())c(d$);if(W$.trim())j$("subagent.child.stderr",W$);S.end();let i=j1(y$)||q$.join(`
58
+ `).trim(),M$=A$??s,l0=U$&&a&&!M$;h({stderr:n,exitCode:X$?1:_$?1:S$||l0?0:U$||D?P??1:P,messages:y$,usage:K$,model:g$,error:X$?T??"Subagent timed out.":_$?E:S$||l0?void 0:M$,finalOutput:X$&&!i.trim()?T??"Subagent timed out.":i,interrupted:S$,timedOut:X$,turnBudget:t,turnBudgetExceeded:_$,wrapUpRequested:t?.outcome==="wrap-up-requested"||_$||void 0,observedMutationAttempt:p})}),f.on("error",(P)=>{V$=!0,G?.(void 0),O?.(void 0),y?.(void 0),p$(),l$(),S.end();let D=j1(y$)||q$.join(`
59
+ `).trim(),i=P instanceof Error?P.message:String(P);h({stderr:n,exitCode:1,messages:y$,usage:K$,model:g$,error:X$?T??"Subagent timed out.":_$?E:A$??s??i,finalOutput:X$&&!D.trim()?T??"Subagent timed out.":D,timedOut:X$,turnBudget:t,turnBudgetExceeded:_$,wrapUpRequested:t?.outcome==="wrap-up-requested"||_$||void 0,observedMutationAttempt:p})})})}function c5(){let $=u1();if($)return $;throw Error(`Could not resolve ${k0} package root`)}async function d5($,j,J){let Z=J??c5(),Q=r.join(Z,"dist","core","export-html","index.js"),U=(await import(b5(Q).href)).exportFromFile;if(typeof U!=="function")throw Error("exportFromFile not available");let G=r.join(j,`${r.basename($,".jsonl")}.html`);return U($,{outputPath:G})}function o5($){try{if(d8("gh",["auth","status"],{encoding:"utf-8"}).status!==0)return{error:"GitHub CLI is not logged in. Run 'gh auth login' first."}}catch{return{error:"GitHub CLI (gh) is not installed."}}try{let j=d8("gh",["gist","create",$],{encoding:"utf-8"});if(j.status!==0)return{error:(j.stderr||"").trim()||"Failed to create gist."};let J=(j.stdout||"").trim(),Z=J.split("/").pop();if(!Z)return{error:"Failed to parse gist ID."};return{shareUrl:`https://shittycodingagent.ai/session/?${Z}`,gistUrl:J}}catch(j){return{error:String(j)}}}function l8($){if($<1000)return`${$}ms`;if($<60000)return`${($/1000).toFixed(1)}s`;let j=Math.floor($/60000),J=Math.floor($%60000/1000);return`${j}m${J}s`}function u5($,j){let J=[];if(J.push(`# Subagent run ${j.id}`),J.push(""),J.push(`- **Mode:** ${j.mode}`),J.push(`- **CWD:** ${j.cwd}`),J.push(`- **Started:** ${new Date(j.startedAt).toISOString()}`),J.push(`- **Ended:** ${new Date(j.endedAt).toISOString()}`),J.push(`- **Duration:** ${l8(j.endedAt-j.startedAt)}`),j.sessionFile)J.push(`- **Session:** ${j.sessionFile}`);if(j.shareUrl)J.push(`- **Share:** ${j.shareUrl}`);if(j.shareError)J.push(`- **Share error:** ${j.shareError}`);if(j.artifactsDir)J.push(`- **Artifacts:** ${j.artifactsDir}`);if(J.push(""),J.push("## Steps"),J.push("| Step | Agent | Status | Duration |"),J.push("| --- | --- | --- | --- |"),j.steps.forEach((Z,Q)=>{let X=Z.durationMs!==void 0?l8(Z.durationMs):"-";J.push(`| ${Q+1} | ${Z.agent} | ${Z.status} | ${X} |`)}),J.push(""),J.push("## Summary"),j.truncated)J.push("_Output truncated_"),J.push("");J.push(j.summary.trim()||"(no output)"),J.push(""),e.writeFileSync($,J.join(`
60
60
  `),"utf-8")}async function kj($,j){if($.importAsyncRoot){let j$=!1;j.registerTimeout?.(()=>{j$=!0;let c;try{c=R0($.importAsyncRoot.asyncDir)?.pid}catch{c=void 0}try{m1({asyncDir:$.importAsyncRoot.asyncDir,pid:c,source:"ancestor-timeout"})}catch{}});try{let c=await f8($.importAsyncRoot,{shouldAbort:()=>j$||j.timeoutSignal?.aborted===!0||j.skipAcceptance?.()===!0,timeoutMessage:j.timeoutMessage});try{e.writeFileSync(j.outputFile,c.output,"utf-8")}catch{}let H$=j$||c.timedOut===!0||j.timeoutSignal?.aborted===!0||j.skipAcceptance?.()===!0;return{agent:c.agent,output:H$?j.timeoutMessage??"Subagent timed out.":c.output,exitCode:H$?1:c.exitCode,error:H$?j.timeoutMessage??"Subagent timed out.":c.error,timedOut:H$?!0:void 0,sessionFile:c.sessionFile,intercomTarget:c.intercomTarget,model:c.model,attemptedModels:c.attemptedModels,modelAttempts:c.modelAttempts,totalCost:c.totalCost,structuredOutput:H$?void 0:c.structuredOutput,structuredOutputPath:H$?void 0:c.structuredOutputPath,structuredOutputSchemaPath:H$?void 0:c.structuredOutputSchemaPath,acceptance:H$?void 0:c.acceptance}}finally{j.registerTimeout?.(void 0)}}let J=$.structuredOutput??($.structuredOutputSchema?fJ($.structuredOutputSchema,r.join(r.dirname(j.outputFile),"structured-output")):void 0),Z=new RegExp(j.placeholder.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),Q=$.task.replace(Z,()=>j.previousOutput);Q=tJ(Q,j.outputs??{});let X=Q;if($.effectiveAcceptance){let j$=R8($.effectiveAcceptance);if(j$)Q=`${Q}
61
- ${j$}`}let W=Boolean($.sessionFile)||j.sessionEnabled,K=$.sessionFile?void 0:j.sessionDir,G,B;if(j.artifactsDir&&j.artifactConfig?.enabled!==!1){let j$=j.flatStepCount>1?j.flatIndex:void 0;if(G=c1(j.artifactsDir,j.id,$.agent,j$),e.mkdirSync(j.artifactsDir,{recursive:!0}),j.artifactConfig?.includeInput!==!1)e.writeFileSync(G.inputPath,`# Task for ${$.agent}
61
+ ${j$}`}let W=Boolean($.sessionFile)||j.sessionEnabled,U=$.sessionFile?void 0:j.sessionDir,G,B;if(j.artifactsDir&&j.artifactConfig?.enabled!==!1){let j$=j.flatStepCount>1?j.flatIndex:void 0;if(G=c1(j.artifactsDir,j.id,$.agent,j$),e.mkdirSync(j.artifactsDir,{recursive:!0}),j.artifactConfig?.includeInput!==!1)e.writeFileSync(G.inputPath,`# Task for ${$.agent}
62
62
 
63
- ${Q}`,"utf-8");if(j.artifactConfig?.includeTranscript!==!1)B=YJ({transcriptPath:G.transcriptPath,source:"async",runId:j.id,agent:$.agent,childIndex:j.flatIndex,cwd:$.cwd??j.cwd})}B?.writeInitialUserMessage(Q);let q=$.modelCandidates&&$.modelCandidates.length>0?$.modelCandidates:$.model?[$.model]:[void 0],O=[],T=[],y=[],h=r.join(r.dirname(j.outputFile),"events.jsonl"),S,v$,k=!1,f=j.turnBudget?Rj(j.turnBudget):void 0,n=$.toolBudget?C0($.toolBudget):void 0,d$=!1;for(let j$=0;j$<q.length;j$++){if(j.timeoutSignal?.aborted||j.skipAcceptance?.())break;let c=q[j$];j.onAttemptStart?.({model:c,thinking:O0(c,$.thinking)});let H$=BJ($.outputPath);if(J)try{if(e.existsSync(J.outputPath))e.unlinkSync(J.outputPath)}catch{}let{args:k$,env:W0,tempDir:Y}=oJ({parentSessionId:$.parentSessionId,baseArgs:["--mode","json","-p"],task:Q,sessionEnabled:W,sessionDir:K,sessionFile:$.sessionFile,model:c,inheritProjectContext:$.inheritProjectContext,inheritSkills:$.inheritSkills,requireReadTool:Boolean($.skills?.length),tools:$.tools,extensions:$.extensions,subagentOnlyExtensions:$.subagentOnlyExtensions,systemPrompt:m8($.systemPrompt??"",j.turnBudget),systemPromptMode:$.systemPromptMode,mcpDirectTools:$.mcpDirectTools,cwd:$.cwd??j.cwd,promptFileStem:$.agent,intercomSessionName:j.childIntercomTarget,orchestratorIntercomTarget:j.orchestratorIntercomTarget,runId:j.id,childAgentName:$.agent,childIndex:j.flatIndex,parentEventSink:j.nestedRoute?.eventSink,parentControlInbox:j.nestedRoute?.controlInbox,parentRootRunId:j.nestedRoute?.rootRunId,parentCapabilityToken:j.nestedRoute?.capabilityToken,steerInboxDir:j.steerInboxDir,structuredOutput:J,toolBudget:$.toolBudget}),u=await g5(k$,$.cwd??j.cwd,j.outputFile,W0,j.piPackageRoot,j.piArgv1,$.maxSubagentDepth,{eventsPath:h,runId:j.id,stepIndex:j.flatIndex,agent:$.agent},j.registerInterrupt,j.onChildEvent,B,j.registerTimeout,j.timeoutMessage,j.registerTurnBudgetAbort);if(u.turnBudget)f=u.turnBudget;else if(j.turnBudget){let P=u.messages.filter((_$)=>_$.role==="assistant"),D=P.length,i=P.at(-1);if(D>0&&D<j.turnBudget.maxTurns)f={...j.turnBudget,outcome:"within-budget",turnCount:D};else if(D>=j.turnBudget.maxTurns)f=O1(j.turnBudget,D,wj(j.turnBudget,D,i?hj(i):!1))}uJ(Y);let K$=u.exitCode===0&&!u.error?QJ(u.messages):null,a=J?!e.existsSync(J.outputPath):!1,A$=u.exitCode===0&&!u.error&&!K$?.hasError&&!u.finalOutput.trim()&&(!J||a)?"Subagent produced no output (possible model cold-start or empty response).":void 0,f$,S$;if(J&&u.exitCode===0&&!u.error&&!K$?.hasError&&!A$){let P=PJ({schema:J.schema,schemaPath:J.schemaPath,outputPath:J.outputPath});if(P.error)S$=P.error;else f$=P.value}let P$=(u.exitCode===0&&!u.error&&!K$?.hasError&&!A$&&$.completionGuard!==!1?M8({agent:$.agent,task:X,messages:u.messages,tools:$.tools,mcpDirectTools:$.mcpDirectTools}):void 0)?.triggered===!0&&!u.observedMutationAttempt,U$=P$?`Subagent completed without making edits for an implementation task.
64
- It appears to have returned planning or scratchpad output instead of applying changes.`:void 0,l$=P$?1:S$?1:K$?.hasError?K$.exitCode??1:A$?1:u.error&&u.exitCode===0?1:u.exitCode,p$=U$??S$??(K$?.hasError?K$.details?`${K$.errorType} failed (exit ${l$}): ${K$.details}`:`${K$.errorType} failed with exit code ${l$}`:A$??(u.error||(u.exitCode!==0&&u.stderr.trim()?u.stderr.trim():void 0))),e$={model:c??u.model??$.model??"default",success:l$===0&&!p$,exitCode:l$,error:p$,usage:u.usage};if(T.push(e$),c)O.push(c);if(k=P$,v$=H$,$.toolBudget){let P=u.messages.filter((i)=>i.role==="toolResult"),D=P.find((i)=>s$(i.content).includes("Tool budget hard limit reached"));d$=Boolean(D),n=Z1($.toolBudget,P.length,D?D.toolName:void 0)}if(S={...u,exitCode:l$,model:c??u.model,error:p$,structuredOutput:f$},u.turnBudgetExceeded)break;if(u.timedOut||j.timeoutSignal?.aborted||j.skipAcceptance?.())break;if(e$.success||P$)break;if(!Y8(p$)||j$===q.length-1)break;y.push(W8(e$,q[j$+1]))}let W$=S?.finalOutput??"",y$=Cj(W$),V$=$.outputPath&&S?.exitCode===0?_J($.outputPath,y$,v$):{fullOutput:y$},g$=V$.fullOutput,O$=V$.savedPath?l1(V$.savedPath,g$):void 0,s=g$;if(y.length>0)s=`${y.join(`
63
+ ${Q}`,"utf-8");if(j.artifactConfig?.includeTranscript!==!1)B=YJ({transcriptPath:G.transcriptPath,source:"async",runId:j.id,agent:$.agent,childIndex:j.flatIndex,cwd:$.cwd??j.cwd})}B?.writeInitialUserMessage(Q);let q=$.modelCandidates&&$.modelCandidates.length>0?$.modelCandidates:$.model?[$.model]:[void 0],O=[],T=[],y=[],h=r.join(r.dirname(j.outputFile),"events.jsonl"),S,v$,k=!1,f=j.turnBudget?Rj(j.turnBudget):void 0,n=$.toolBudget?C0($.toolBudget):void 0,d$=!1;for(let j$=0;j$<q.length;j$++){if(j.timeoutSignal?.aborted||j.skipAcceptance?.())break;let c=q[j$];j.onAttemptStart?.({model:c,thinking:O0(c,$.thinking)});let H$=BJ($.outputPath);if(J)try{if(e.existsSync(J.outputPath))e.unlinkSync(J.outputPath)}catch{}let{args:k$,env:W0,tempDir:Y}=oJ({parentSessionId:$.parentSessionId,baseArgs:["--mode","json","-p"],task:Q,sessionEnabled:W,sessionDir:U,sessionFile:$.sessionFile,model:c,inheritProjectContext:$.inheritProjectContext,inheritSkills:$.inheritSkills,requireReadTool:Boolean($.skills?.length),tools:$.tools,extensions:$.extensions,subagentOnlyExtensions:$.subagentOnlyExtensions,systemPrompt:m8($.systemPrompt??"",j.turnBudget),systemPromptMode:$.systemPromptMode,mcpDirectTools:$.mcpDirectTools,cwd:$.cwd??j.cwd,promptFileStem:$.agent,intercomSessionName:j.childIntercomTarget,orchestratorIntercomTarget:j.orchestratorIntercomTarget,runId:j.id,childAgentName:$.agent,childIndex:j.flatIndex,parentEventSink:j.nestedRoute?.eventSink,parentControlInbox:j.nestedRoute?.controlInbox,parentRootRunId:j.nestedRoute?.rootRunId,parentCapabilityToken:j.nestedRoute?.capabilityToken,steerInboxDir:j.steerInboxDir,structuredOutput:J,toolBudget:$.toolBudget}),u=await m5(k$,$.cwd??j.cwd,j.outputFile,W0,j.piPackageRoot,j.piArgv1,$.maxSubagentDepth,{eventsPath:h,runId:j.id,stepIndex:j.flatIndex,agent:$.agent},j.registerInterrupt,j.onChildEvent,B,j.registerTimeout,j.timeoutMessage,j.registerTurnBudgetAbort);if(u.turnBudget)f=u.turnBudget;else if(j.turnBudget){let P=u.messages.filter((M$)=>M$.role==="assistant"),D=P.length,i=P.at(-1);if(D>0&&D<j.turnBudget.maxTurns)f={...j.turnBudget,outcome:"within-budget",turnCount:D};else if(D>=j.turnBudget.maxTurns)f=O1(j.turnBudget,D,wj(j.turnBudget,D,i?hj(i):!1))}uJ(Y);let U$=u.exitCode===0&&!u.error?QJ(u.messages):null,a=J?!e.existsSync(J.outputPath):!1,N$=u.exitCode===0&&!u.error&&!U$?.hasError&&!u.finalOutput.trim()&&(!J||a)?"Subagent produced no output (possible model cold-start or empty response).":void 0,f$,D$;if(J&&u.exitCode===0&&!u.error&&!U$?.hasError&&!N$){let P=PJ({schema:J.schema,schemaPath:J.schemaPath,outputPath:J.outputPath});if(P.error)D$=P.error;else f$=P.value}let P$=(u.exitCode===0&&!u.error&&!U$?.hasError&&!N$&&$.completionGuard!==!1?M8({agent:$.agent,task:X,messages:u.messages,tools:$.tools,mcpDirectTools:$.mcpDirectTools}):void 0)?.triggered===!0&&!u.observedMutationAttempt,V$=P$?`Subagent completed without making edits for an implementation task.
64
+ It appears to have returned planning or scratchpad output instead of applying changes.`:void 0,l$=P$?1:D$?1:U$?.hasError?U$.exitCode??1:N$?1:u.error&&u.exitCode===0?1:u.exitCode,p$=V$??D$??(U$?.hasError?U$.details?`${U$.errorType} failed (exit ${l$}): ${U$.details}`:`${U$.errorType} failed with exit code ${l$}`:N$??(u.error||(u.exitCode!==0&&u.stderr.trim()?u.stderr.trim():void 0))),e$={model:c??u.model??$.model??"default",success:l$===0&&!p$,exitCode:l$,error:p$,usage:u.usage};if(T.push(e$),c)O.push(c);if(k=P$,v$=H$,$.toolBudget){let P=u.messages.filter((i)=>i.role==="toolResult"),D=P.find((i)=>s$(i.content).includes("Tool budget hard limit reached"));d$=Boolean(D),n=Z1($.toolBudget,P.length,D?D.toolName:void 0)}if(S={...u,exitCode:l$,model:c??u.model,error:p$,structuredOutput:f$},u.turnBudgetExceeded)break;if(u.timedOut||j.timeoutSignal?.aborted||j.skipAcceptance?.())break;if(e$.success||P$)break;if(!Y8(p$)||j$===q.length-1)break;y.push(W8(e$,q[j$+1]))}let W$=S?.finalOutput??"",y$=Cj(W$),K$=$.outputPath&&S?.exitCode===0?_J($.outputPath,y$,v$):{fullOutput:y$},g$=K$.fullOutput,A$=K$.savedPath?l1(K$.savedPath,g$):void 0,s=g$;if(y.length>0)s=`${y.join(`
65
65
  `)}
66
66
 
67
67
  ${s}`.trim();if(!S?.timedOut&&S?.turnBudgetExceeded&&f)s=c8(u0(f,f.turnCount),s);else if(!S?.timedOut&&f?.outcome==="wrap-up-requested"){let j$=bj(f,f.wrapUpRequestedAtTurn??f.turnCount);s=s.trim()?`${j$}
68
68
 
69
- ${s}`:j$}let E$=W$;s=MJ({fullOutput:s,outputPath:$.outputPath,outputMode:$.outputMode,exitCode:S?.exitCode??1,savedPath:V$.savedPath,outputReference:O$,saveError:V$.saveError}).displayOutput;let B$=$.effectiveAcceptance&&!S?.turnBudgetExceeded&&!j.timeoutSignal?.aborted&&!j.skipAcceptance?.()?await M1({acceptance:$.effectiveAcceptance,output:E$,cwd:$.cwd??j.cwd,signal:j.timeoutSignal,abortMessage:j.timeoutMessage??"Subagent timed out."}):void 0,E=S?.timedOut===!0||j.timeoutSignal?.aborted===!0||j.skipAcceptance?.()===!0,t=S?.turnBudgetExceeded===!0,p=E||t?void 0:B$,L$=p?L1(p):void 0,Y$=L$&&p?.explicit&&(S?.exitCode??1)===0&&!S?.interrupted&&!E&&!t,o$=E||t?1:Y$?1:S?.exitCode??1,u$=E?j.timeoutMessage??"Subagent timed out.":t?S?.error??(f?u0(f,f.turnCount):"Subagent exceeded turn budget."):Y$?S?.error?`${S.error}
70
- ${L$}`:L$:S?.error;if(G&&j.artifactConfig?.enabled!==!1){if(j.artifactConfig?.includeOutput!==!1)e.writeFileSync(G.outputPath,g$,"utf-8");if(j.artifactConfig?.includeMetadata!==!1)e.writeFileSync(G.metadataPath,JSON.stringify({runId:j.id,agent:$.agent,task:Q,exitCode:o$,model:S?.model,attemptedModels:O.length>0?O:void 0,modelAttempts:T,...B?{transcriptPath:G.transcriptPath}:{},transcriptError:B?.getError(),skills:$.skills,timestamp:Date.now()},null,2),"utf-8")}return{agent:$.agent,output:s,exitCode:o$,error:u$,sessionFile:$.sessionFile,intercomTarget:j.childIntercomTarget,model:S?.model,attemptedModels:O.length>0?O:void 0,modelAttempts:T,totalCost:v5(T),artifactPaths:G,transcriptPath:B?G?.transcriptPath:void 0,transcriptError:B?.getError(),interrupted:E||t?!1:S?.interrupted,timedOut:E?!0:S?.timedOut,turnBudget:f,turnBudgetExceeded:t||void 0,wrapUpRequested:S?.wrapUpRequested||f?.outcome==="wrap-up-requested"||t||void 0,toolBudget:n,toolBudgetBlocked:d$||void 0,completionGuardTriggered:k,structuredOutput:E||t?void 0:S?.structuredOutput,structuredOutputPath:E||t?void 0:J?.outputPath,structuredOutputSchemaPath:E||t?void 0:J?.schemaPath,acceptance:p}}function p8($){for(let j=0;j<$.group.parallel.length;j++){let J=$.groupStartFlatIndex+j;$.statusPayload.steps[J].status="failed",$.statusPayload.steps[J].startedAt=$.failedAt,$.statusPayload.steps[J].endedAt=$.failedAt,$.statusPayload.steps[J].durationMs=0,$.statusPayload.steps[J].exitCode=1,$.results.push({agent:$.group.parallel[j].agent,output:$.setupError,success:!1,exitCode:1,sessionFile:$.group.parallel[j].sessionFile})}$.statusPayload.currentStep=$.groupStartFlatIndex,$.statusPayload.lastUpdate=$.failedAt,$.statusPayload.outputFile=r.join($.asyncDir,`output-${$.groupStartFlatIndex}.log`),D$($.statusPath,$.statusPayload),$$($.eventsPath,JSON.stringify({type:"subagent.parallel.completed",ts:$.failedAt,runId:$.runId,stepIndex:$.stepIndex,success:!1}))}function u5($){for(let j=0;j<$.group.parallel.length;j++){let J=$.groupStartFlatIndex+j;$.statusPayload.steps[J].status="pending",$.statusPayload.steps[J].startedAt=void 0,$.statusPayload.steps[J].endedAt=void 0,$.statusPayload.steps[J].durationMs=void 0,$.statusPayload.steps[J].lastActivityAt=void 0,$.statusPayload.steps[J].activityState=void 0,$.statusPayload.steps[J].error=void 0}$.statusPayload.currentStep=$.groupStartFlatIndex,$.statusPayload.activityState=void 0,$.statusPayload.lastActivityAt=$.groupStartTime,$.statusPayload.lastUpdate=$.groupStartTime,$.statusPayload.outputFile=r.join($.asyncDir,`output-${$.groupStartFlatIndex}.log`),D$($.statusPath,$.statusPayload),$$($.eventsPath,JSON.stringify({type:"subagent.parallel.started",ts:$.groupStartTime,runId:$.runId,stepIndex:$.stepIndex,agents:$.group.parallel.map((j)=>j.agent),count:$.group.parallel.length}))}function l5($,j,J,Z){if(!J)return{taskForRun:$,taskCwd:j};return{taskForRun:{...$,cwd:void 0},taskCwd:J.worktrees[Z].agentCwd}}function p5($,j,J,Z,Q){if(!j)return $;let X=r.join(J,"worktree-diffs",`step-${Z}`),W=T8(j,Q.parallel.map((G)=>G.agent),X),K=E8(W);if(!K)return $;return`${$}
69
+ ${s}`:j$}let S$=W$;s=MJ({fullOutput:s,outputPath:$.outputPath,outputMode:$.outputMode,exitCode:S?.exitCode??1,savedPath:K$.savedPath,outputReference:A$,saveError:K$.saveError}).displayOutput;let _$=$.effectiveAcceptance&&!S?.turnBudgetExceeded&&!j.timeoutSignal?.aborted&&!j.skipAcceptance?.()?await M1({acceptance:$.effectiveAcceptance,output:S$,cwd:$.cwd??j.cwd,signal:j.timeoutSignal,abortMessage:j.timeoutMessage??"Subagent timed out."}):void 0,E=S?.timedOut===!0||j.timeoutSignal?.aborted===!0||j.skipAcceptance?.()===!0,t=S?.turnBudgetExceeded===!0,p=E||t?void 0:_$,q$=p?L1(p):void 0,Y$=q$&&p?.explicit&&(S?.exitCode??1)===0&&!S?.interrupted&&!E&&!t,o$=E||t?1:Y$?1:S?.exitCode??1,u$=E?j.timeoutMessage??"Subagent timed out.":t?S?.error??(f?u0(f,f.turnCount):"Subagent exceeded turn budget."):Y$?S?.error?`${S.error}
70
+ ${q$}`:q$:S?.error;if(G&&j.artifactConfig?.enabled!==!1){if(j.artifactConfig?.includeOutput!==!1)e.writeFileSync(G.outputPath,g$,"utf-8");if(j.artifactConfig?.includeMetadata!==!1)e.writeFileSync(G.metadataPath,JSON.stringify({runId:j.id,agent:$.agent,task:Q,exitCode:o$,model:S?.model,attemptedModels:O.length>0?O:void 0,modelAttempts:T,...B?{transcriptPath:G.transcriptPath}:{},transcriptError:B?.getError(),skills:$.skills,timestamp:Date.now()},null,2),"utf-8")}return{agent:$.agent,output:s,exitCode:o$,error:u$,sessionFile:$.sessionFile,intercomTarget:j.childIntercomTarget,model:S?.model,attemptedModels:O.length>0?O:void 0,modelAttempts:T,totalCost:g5(T),artifactPaths:G,transcriptPath:B?G?.transcriptPath:void 0,transcriptError:B?.getError(),interrupted:E||t?!1:S?.interrupted,timedOut:E?!0:S?.timedOut,turnBudget:f,turnBudgetExceeded:t||void 0,wrapUpRequested:S?.wrapUpRequested||f?.outcome==="wrap-up-requested"||t||void 0,toolBudget:n,toolBudgetBlocked:d$||void 0,completionGuardTriggered:k,structuredOutput:E||t?void 0:S?.structuredOutput,structuredOutputPath:E||t?void 0:J?.outputPath,structuredOutputSchemaPath:E||t?void 0:J?.schemaPath,acceptance:p}}function p8($){for(let j=0;j<$.group.parallel.length;j++){let J=$.groupStartFlatIndex+j;$.statusPayload.steps[J].status="failed",$.statusPayload.steps[J].startedAt=$.failedAt,$.statusPayload.steps[J].endedAt=$.failedAt,$.statusPayload.steps[J].durationMs=0,$.statusPayload.steps[J].exitCode=1,$.results.push({agent:$.group.parallel[j].agent,output:$.setupError,success:!1,exitCode:1,sessionFile:$.group.parallel[j].sessionFile})}$.statusPayload.currentStep=$.groupStartFlatIndex,$.statusPayload.lastUpdate=$.failedAt,$.statusPayload.outputFile=r.join($.asyncDir,`output-${$.groupStartFlatIndex}.log`),b$($.statusPath,$.statusPayload),$$($.eventsPath,JSON.stringify({type:"subagent.parallel.completed",ts:$.failedAt,runId:$.runId,stepIndex:$.stepIndex,success:!1}))}function l5($){for(let j=0;j<$.group.parallel.length;j++){let J=$.groupStartFlatIndex+j;$.statusPayload.steps[J].status="pending",$.statusPayload.steps[J].startedAt=void 0,$.statusPayload.steps[J].endedAt=void 0,$.statusPayload.steps[J].durationMs=void 0,$.statusPayload.steps[J].lastActivityAt=void 0,$.statusPayload.steps[J].activityState=void 0,$.statusPayload.steps[J].error=void 0}$.statusPayload.currentStep=$.groupStartFlatIndex,$.statusPayload.activityState=void 0,$.statusPayload.lastActivityAt=$.groupStartTime,$.statusPayload.lastUpdate=$.groupStartTime,$.statusPayload.outputFile=r.join($.asyncDir,`output-${$.groupStartFlatIndex}.log`),b$($.statusPath,$.statusPayload),$$($.eventsPath,JSON.stringify({type:"subagent.parallel.started",ts:$.groupStartTime,runId:$.runId,stepIndex:$.stepIndex,agents:$.group.parallel.map((j)=>j.agent),count:$.group.parallel.length}))}function p5($,j,J,Z){if(!J)return{taskForRun:$,taskCwd:j};return{taskForRun:{...$,cwd:void 0},taskCwd:J.worktrees[Z].agentCwd}}function n5($,j,J,Z,Q){if(!j)return $;let X=r.join(J,"worktree-diffs",`step-${Z}`),W=T8(j,Q.parallel.map((G)=>G.agent),X),U=E8(W);if(!U)return $;return`${$}
71
71
 
72
- ${K}`}function n5($,j){let J=r.join($,"progress.md");if(!j.parallel.some((Z)=>Z.task.includes(`Update progress at: ${J}`)))return;ej($)}function fj($){if(!$.artifactsDir||$.artifactConfig?.enabled===!1||$.artifactConfig?.includeTranscript===!1)return;return c1($.artifactsDir,$.runId,$.agent,$.flatStepCount>1?$.flatIndex:void 0).transcriptPath}async function n8($){let{id:j,steps:J,resultPath:Z,cwd:Q,placeholder:X,taskIndex:W,totalTasks:K,maxOutput:G,artifactsDir:B,artifactConfig:q}=$,O=new y1($.globalConcurrencyLimit??tj),T="",y={},h=[],S=Date.now(),v$=$.share===!0,k=$.asyncDir,f=r.join(k,"status.json"),n=r.join(k,"events.jsonl"),d$=r.join(k,`subagent-log-${j}.md`),W$=$.controlConfig??LJ,y$=new Map,V$=new Map,g$=new Map,O$=[],s=!1,E$,X$,B$,E=!1,t=!1,p=$.timeoutMs!==void 0?`Subagent timed out after ${$.timeoutMs}ms.`:void 0,L$=new AbortController,Y$={input:0,output:0,total:0},o$,u$=aj(J),j$=u$.length,c=[],H$=[],k$=0;for(let H=0;H<J.length;H++){let U=J[H];if($0(U)){c.push({start:k$,count:U.parallel.length,stepIndex:H});for(let V of U.parallel){let _=k$,z=fj({artifactsDir:B,artifactConfig:q,runId:j,agent:V.agent,flatIndex:_,flatStepCount:j$});H$.push({agent:V.agent,phase:V.phase,label:V.label,outputName:V.outputName,structured:V.structured,status:"pending",...V.toolBudget?{toolBudget:C0(V.toolBudget)}:{},...V.sessionFile?{sessionFile:V.sessionFile}:{},...z?{transcriptPath:z}:{},skills:V.skills,model:V.model,thinking:V.thinking,attemptedModels:V.modelCandidates&&V.modelCandidates.length>0?V.modelCandidates:V.model?[V.model]:void 0,recentTools:[],recentOutput:[]}),k$++}}else if(j0(U))c.push({start:k$,count:1,stepIndex:H}),H$.push({agent:`expand:${U.parallel.agent}`,phase:U.phase??U.parallel.phase,label:U.label??U.parallel.label??`Dynamic fanout (${U.collect.as})`,outputName:U.collect.as,structured:Boolean(U.collect.outputSchema),status:"pending",...U.parallel.toolBudget?{toolBudget:C0(U.parallel.toolBudget)}:{},recentTools:[],recentOutput:[]}),k$++;else{let V=k$,_=fj({artifactsDir:B,artifactConfig:q,runId:j,agent:U.agent,flatIndex:V,flatStepCount:j$});H$.push({agent:U.agent,phase:U.phase,label:U.label,outputName:U.outputName,structured:U.structured,status:"pending",...U.toolBudget?{toolBudget:C0(U.toolBudget)}:{},...U.sessionFile?{sessionFile:U.sessionFile}:{},..._?{transcriptPath:_}:{},skills:U.skills,model:U.model,thinking:U.thinking,attemptedModels:U.modelCandidates&&U.modelCandidates.length>0?U.modelCandidates:U.model?[U.model]:void 0,recentTools:[],recentOutput:[]}),k$++}}let W0=Boolean($.sessionDir)||v$||u$.some((H)=>Boolean(H.sessionFile)),Y={lifecycleArtifactVersion:S0,runId:j,...$.sessionId?{sessionId:$.sessionId}:{},mode:$.resultMode??(u$.length>1?"chain":"single"),state:"running",lastActivityAt:S,startedAt:S,lastUpdate:S,...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},...$.deadlineAt!==void 0?{deadlineAt:$.deadlineAt}:{},...$.turnBudget?{turnBudget:Rj($.turnBudget)}:{},...$.toolBudget?{toolBudget:C0($.toolBudget)}:{},pid:process.pid,cwd:Q,currentStep:0,chainStepCount:J.length,parallelGroups:c,workflowGraph:$.workflowGraph,steps:H$,artifactsDir:B,sessionDir:$.sessionDir,outputFile:r.join(k,"output-0.log")};e.mkdirSync(k,{recursive:!0}),D$(f,Y);let u=(H)=>{if(!$.nestedRoute||!$.nestedSelf)return;try{Q8($.nestedRoute,{type:H,ts:Date.now(),parentRunId:$.nestedSelf.parentRunId,parentStepIndex:$.nestedSelf.parentStepIndex,child:X8(Y,k,{id:j,parentRunId:$.nestedSelf.parentRunId,parentStepIndex:$.nestedSelf.parentStepIndex,depth:$.nestedSelf.depth,path:$.nestedSelf.path,mode:Y.mode,ts:Date.now()})})}catch(U){console.error("Failed to emit nested async status event:",U)}},K$=()=>{if(!$.workflowGraph)return;let H=structuredClone(Y.workflowGraph??$.workflowGraph),U=(_)=>{if(_==="complete"||_==="completed")return"completed";if(_==="running"||_==="failed"||_==="paused"||_==="pending")return _;return"pending"},V=(_)=>{if(_.flatIndex!==void 0){let z=Y.steps[_.flatIndex];if(z)_.status=U(z.status),_.error=z.error,_.acceptanceStatus=z.acceptance?.status;if(Y.currentStep===_.flatIndex)H.currentNodeId=_.id}for(let z of _.children??[])V(z);if(_.children?.length){if(_.children.every((z)=>z.status==="completed"))_.status="completed";else if(_.children.some((z)=>z.status==="running"))_.status="running";else if(_.children.some((z)=>z.status==="failed"))_.status="failed";else if(_.children.some((z)=>z.status==="paused"))_.status="paused"}if(_.error)_.status="failed"};for(let _ of H.nodes)V(_);Y.workflowGraph=H},a=()=>{K$(),D$(f,Y),u(Y.state==="running"||Y.state==="queued"?"subagent.nested.updated":"subagent.nested.completed")},A$=(H,U)=>{if(!U){y$.delete(H);return}if(y$.set(H,U),s)U()},f$=(H,U)=>{if(!U){V$.delete(H);return}if(V$.set(H,U),E)U()},S$=(H,U)=>{if(!U){g$.delete(H);return}g$.set(H,U)},t$=()=>{for(let H of[...y$.values()])H()},P$=()=>{for(let H of[...V$.values()])H()},U$=function*(H){for(let U of H??[])yield U,yield*U$(U.children),yield*U$(U.steps?.flatMap((V)=>V.children??[]))},l$=()=>{if(!$.nestedRoute)return;let H;try{H=Mj($.nestedRoute)}catch(U){$$(n,JSON.stringify({type:"subagent.nested.interrupt_failed",ts:Date.now(),runId:j,message:U instanceof Error?U.message:String(U)}));return}for(let U of U$(H.children)){if(U.state!=="running"&&U.state!=="queued")continue;let V=U.asyncDir??_j($.nestedRoute.rootRunId,U);if(!V)continue;try{VJ({asyncDir:V,pid:U.pid,source:"ancestor-interrupt"})}catch(_){$$(n,JSON.stringify({type:"subagent.nested.interrupt_failed",ts:Date.now(),runId:j,targetRunId:U.id,message:_ instanceof Error?_.message:String(_)}))}}},p$=()=>{if(!$.nestedRoute)return;let H;try{H=Mj($.nestedRoute)}catch(U){$$(n,JSON.stringify({type:"subagent.nested.timeout_failed",ts:Date.now(),runId:j,message:U instanceof Error?U.message:String(U)}));return}for(let U of U$(H.children)){if(U.state!=="running"&&U.state!=="queued")continue;let V=U.asyncDir??_j($.nestedRoute.rootRunId,U);if(!V)continue;try{m1({asyncDir:V,pid:U.pid,source:"ancestor-timeout"})}catch(_){$$(n,JSON.stringify({type:"subagent.nested.timeout_failed",ts:Date.now(),runId:j,targetRunId:U.id,message:_ instanceof Error?_.message:String(_)}))}}},e$=(H)=>({agent:H,output:"Paused after interrupt. Waiting for explicit next action.",exitCode:0,interrupted:!0}),P=(H)=>({agent:H,output:p??"Subagent timed out.",error:p??"Subagent timed out.",exitCode:1,timedOut:!0}),D=()=>{if(Y.mode!=="chain"||Y.state!=="running")return;let H=h8(k);if(H.length===0){let N=Dj(k);if((Y.pendingAppends??0)!==N)Y.pendingAppends=N,Y.lastUpdate=Date.now(),a();return}let U=H.flatMap((N)=>N.steps);J.push(...U);let V=Date.now(),_=Dj(k),z=g8({status:Y,steps:U,now:V,pendingAppends:_});if(p0.push(...Array.from({length:z.addedFlatSteps},()=>G1())),T0.push(...Array.from({length:z.addedFlatSteps},()=>{return})),$.childIntercomTargets)$.childIntercomTargets=Y.steps.map((N,w)=>Aj(j,N.agent,w));a();for(let N of H)$$(n,JSON.stringify({type:"subagent.chain.append.accepted",ts:V,runId:j,requestId:N.id,stepCount:N.steps.length,pendingAppends:_}))},i=(H,U,V,_)=>{let z=Y.workflowGraph?.nodes.find((N)=>N.id===`step-${H}`);if(!z)return;z.status=U,z.error=V,z.acceptanceStatus=_?.status??z.acceptanceStatus},_$=(H)=>{let U=Y.steps[H],V=U?.lastActivityAt??U?.startedAt??S,_=r.join(k,`output-${H}.log`);try{V=Math.max(V,e.statSync(_).mtimeMs)}catch(z){if(z.code!=="ENOENT")console.error(`Failed to inspect async output file '${_}':`,z)}return V},l0=new Set,vj=new Set,p0=H$.map(()=>G1()),T0=H$.map(()=>{return}),i8=300000,E0=(H)=>{if(!W$.enabled)return;let U=$.childIntercomTargets?.[H.index??Y.currentStep],V=H.type==="active_long_running"?W$.notifyChannels.filter((_)=>_!=="intercom"):W$.notifyChannels;if(V.length===0||!FJ(W$,H,l0,U))return;$$(n,JSON.stringify({type:"subagent.control",event:H,channels:V,childIntercomTarget:U,noticeText:p1(H,U),...$.controlIntercomTarget&&V.includes("intercom")?{intercom:{to:$.controlIntercomTarget,message:OJ(H,U)}}:{}}))},A1=()=>{let H=Y.steps.filter((U)=>U.status==="running"&&typeof U.currentTool==="string"&&U.currentTool.length>0).sort((U,V)=>(V.currentToolStartedAt??0)-(U.currentToolStartedAt??0))[0];Y.currentTool=H?.currentTool,Y.currentToolStartedAt=H?.currentToolStartedAt,Y.currentPath=H?.currentPath},gj=(H,U)=>{if(!W$.enabled||vj.has(H))return!1;let V=Y.steps[H];if(!V||V.status!=="running"||V.activityState==="needs_attention")return!1;let _=K8(W$,{startedAt:V.startedAt??S,now:U,turns:V.turnCount??0,tokens:V.tokens?.total??0});if(!_)return!1;vj.add(H);let z=V.activityState;V.activityState="active_long_running",Y.activityState=Y.activityState==="needs_attention"?"needs_attention":"active_long_running";let N=A0({type:"active_long_running",from:z,to:"active_long_running",runId:j,agent:V.agent,index:H,ts:U,message:`${V.agent} is still active but long-running`,reason:_,turns:V.turnCount,tokens:V.tokens?.total,toolCount:V.toolCount,currentTool:V.currentTool,currentToolDurationMs:V.currentToolStartedAt?Math.max(0,U-V.currentToolStartedAt):void 0,currentPath:V.currentPath,elapsedMs:U-(V.startedAt??S)});return E0(N),!0},N1=(H)=>{if(Y.state!=="running")return;let U=Y.steps.map((w,d)=>({step:w,index:d})).filter(({step:w})=>w.status==="running").map(({index:w})=>w),V=H.targetIndex!==void 0?[H.targetIndex]:U,_=Date.now(),z=[],N=[];for(let w of V){let d=Y.steps[w];if(!d){N.push({index:w,reason:"child index out of range"});continue}if(d.status!=="running"){N.push({index:w,reason:`child is ${d.status}`});continue}UJ(k,w,H),d.steerCount=(d.steerCount??0)+1,d.lastSteerAt=_,z.push(w)}if(z.length>0)Y.steerCount=(Y.steerCount??0)+z.length,Y.lastSteerAt=_,Y.lastUpdate=_,a();$$(n,JSON.stringify({type:"subagent.steer.requested",ts:_,runId:j,requestId:H.id,message:H.message,...H.source?{source:H.source}:{},...H.targetIndex!==void 0?{targetIndex:H.targetIndex}:{},acceptedIndexes:z,...N.length?{rejected:N}:{}}))},C1=(H)=>{let U=[];for(let V of O$.splice(0))if(V.targetIndex===void 0)N1({...V,targetIndex:H});else if(V.targetIndex===H)N1(V);else U.push(V);O$.push(...U)},T1=(H,U,V,_=Date.now())=>{let z=Y.steps[H];if(!z)return;z.model=U,z.thinking=V,Y.lastUpdate=_,a()},r8=(H,U,V,_)=>{let z=$.turnBudget,N=Y.steps[H];if(!z||!N||E||t||N.turnBudgetExceeded)return;if(U<z.maxTurns){let v={...z,outcome:"within-budget",turnCount:U};N.turnBudget=v,Y.turnBudget=v;return}let w=O1(z,U,!1);if(N.turnBudget=w,Y.turnBudget=w,!N.wrapUpRequested)N.wrapUpRequested=!0,Y.wrapUpRequested=!0,Ij(N,[bj(z,U)]);if(!wj(z,U,_))return;let d=O1(z,U,!0),Z$=u0(z,U);N.turnBudget=d,N.turnBudgetExceeded=!0,N.wrapUpRequested=!0,N.error=Z$,t=!0,Y.turnBudget=d,Y.turnBudgetExceeded=!0,Y.wrapUpRequested=!0,Y.error=Z$,Y.lastUpdate=V,$$(n,JSON.stringify({type:"subagent.step.turn_budget_exceeded",ts:V,runId:j,stepIndex:H,agent:N.agent,turnCount:U,maxTurns:z.maxTurns,graceTurns:z.graceTurns,message:Z$})),g$.get(H)?.(Z$,d)},E1=(H,U)=>{let V=Y.steps[H];if(!V)return;let _=Date.now();if(Y.currentStep=H,U.type==="tool_execution_start"&&U.toolName){let z=qj(U.toolName,U.args),N=U8(U.toolName,U.args);V.toolCount=(V.toolCount??0)+1;let w=u$[H]?.toolBudget;if(w)V.toolBudget=Z1(w,V.toolCount),Y.toolBudget=V.toolBudget;V.currentTool=U.toolName,V.currentToolArgs=w0(U.args??{}),V.currentToolStartedAt=_,V.currentPath=N,T0[H]={tool:U.toolName,path:N,mutates:z,startedAt:_},Y.toolCount=(Y.toolCount??0)+1,A1()}else if(U.type==="tool_execution_end"){if(V.currentTool)V.recentTools??=[],V.recentTools.push({tool:V.currentTool,args:V.currentToolArgs||"",endMs:_});V.currentTool=void 0,V.currentToolArgs=void 0,V.currentToolStartedAt=void 0,V.currentPath=void 0,A1()}else if(U.type==="tool_result_end"&&U.message){let z=T0[H];T0[H]=void 0;let N=s$(U.message.content);if(z&&N.includes("Tool budget hard limit reached")){let w=u$[H]?.toolBudget;if(w)V.toolBudget=Z1(w,V.toolCount??0,z.tool),V.toolBudgetBlocked=!0,Y.toolBudget=V.toolBudget,Y.toolBudgetBlocked=!0}if(Ij(V,N.split(`
73
- `).slice(-10)),z?.mutates&&V8(N)){let w=p0[H];if(G8(w,{tool:z.tool,path:z.path,error:N.split(`
74
- `).find((d)=>d.trim())?.trim().slice(0,180)??"mutating tool failed",ts:_},i8),W$.enabled&&B8(w,W$.failedToolAttemptsBeforeAttention)&&V.activityState!=="needs_attention"){let d=V.activityState;V.activityState="needs_attention",Y.activityState="needs_attention",E0(A0({type:"needs_attention",from:d,to:"needs_attention",runId:j,agent:V.agent,index:H,ts:_,message:`${V.agent} needs attention after repeated mutating tool failures`,reason:"tool_failures",turns:V.turnCount,tokens:V.tokens?.total,toolCount:V.toolCount,currentTool:z.tool,currentToolDurationMs:z.startedAt?Math.max(0,_-z.startedAt):void 0,currentPath:z.path,recentFailureSummary:_8(w)}))}}else if(z?.mutates)z8(p0[H])}else if(U.type==="message_end"&&U.message?.role==="assistant"){Ij(V,Cj(s$(U.message.content)).split(`
75
- `).slice(-10)),V.turnCount=(V.turnCount??0)+1;let z=U.message.usage;if(z){let N=z.input??z.inputTokens??0,w=z.output??z.outputTokens??0,d=V.tokens?.input??0,Z$=V.tokens?.output??0;V.tokens={input:d+N,output:Z$+w,total:d+Z$+N+w};let v=Y.totalTokens?.input??0,F=Y.totalTokens?.output??0;Y.totalTokens={input:v+N,output:F+w,total:v+F+N+w}}Y.turnCount=Math.max(Y.turnCount??0,V.turnCount),r8(H,V.turnCount,_,hj(U.message))}A1(),V.lastActivityAt=_,Y.lastActivityAt=_,Y.lastUpdate=_,gj(H,_),a()},s8=(H)=>{if(!W$.enabled)return!1;let U=!1,V=Y.lastActivityAt??S;for(let z=0;z<Y.steps.length;z++){let N=Y.steps[z];if(N.status!=="running")continue;let w=_$(z);if(V=Math.max(V,w),N.lastActivityAt!==w)N.lastActivityAt=w,U=!0;if(qJ({config:W$,startedAt:N.startedAt??S,lastActivityAt:w,now:H})==="needs_attention"){let Z$=N.activityState;if(N.activityState="needs_attention",Z$!=="needs_attention")E0(A0({from:Z$,to:"needs_attention",runId:j,agent:N.agent,index:z,ts:H,lastActivityAt:w})),U=!0}else if(gj(z,H))U=!0}if(Y.lastActivityAt!==V)Y.lastActivityAt=V,U=!0;let _=Y.steps.some((z)=>z.activityState==="needs_attention")?"needs_attention":Y.steps.some((z)=>z.activityState==="active_long_running")?"active_long_running":void 0;if(_!==E$)E$=_,Y.activityState=_,U=!0;if(Y.lastUpdate=H,U)a();return U};if(W$.enabled)X$=setInterval(()=>{if(Y.state!=="running")return;let H=Date.now();s8(H)},1000),X$.unref?.();let mj=()=>{if(g1(k),s||Y.state!=="running")return;s=!0;let H=Date.now();Y.state="paused",E$=void 0,Y.activityState=void 0,Y.lastUpdate=H;for(let U of Y.steps)if(U.status==="running")U.status="paused",U.activityState=void 0,U.endedAt=H,U.durationMs=U.startedAt?H-U.startedAt:void 0,U.lastActivityAt=H;a(),$$(n,JSON.stringify({type:"subagent.run.paused",ts:H,runId:j})),l$(),t$()},cj=()=>{if(E||s||Y.state!=="running")return;E=!0;let H=Date.now(),U=p??"Subagent timed out.";Y.state="failed",Y.timedOut=!0,Y.error=U,E$=void 0,Y.activityState=void 0,Y.lastUpdate=H;for(let V of Y.steps){if(V.status!=="running"&&V.status!=="pending")continue;V.status="failed",V.error=U,V.exitCode=1,V.timedOut=!0,V.activityState=void 0,V.endedAt=H,V.durationMs=V.startedAt?H-V.startedAt:0,V.lastActivityAt=H}a(),$$(n,JSON.stringify({type:"subagent.run.timed_out",ts:H,runId:j,timeoutMs:$.timeoutMs,deadlineAt:$.deadlineAt,message:U})),L$.abort(),p$(),P$()};process.on(b5,mj);let a8=KJ(k,{onInterrupt:mj,onTimeout:cj,onSteer:(H)=>{if((H.targetIndex!==void 0?Y.steps[H.targetIndex]:void 0)?.status==="pending")O$.push(H);else if(H.targetIndex!==void 0||Y.steps.some((V)=>V.status==="running"))N1(H);else O$.push(H)}});if($.deadlineAt!==void 0){let H=Math.max(0,$.deadlineAt-Date.now());B$=setTimeout(cj,H),B$.unref?.()}$$(n,JSON.stringify({type:"subagent.run.started",lifecycleArtifactVersion:S0,ts:S,runId:j,mode:Y.mode,cwd:Q,pid:process.pid}));let R=0,dj=0;while(!0){if(s||E||t)break;if(D(),dj>=J.length)break;let H=dj++,U=J[H];if(j0(U)){let V=R,_;try{if(_=sJ(U,y,H,{maxItems:$.dynamicFanoutMaxItems,allowRunnerFields:!0}),_.collectedOnEmpty)Yj(U.collect.outputSchema,_.collectedOnEmpty)}catch(M){let o=Date.now(),L=M instanceof x?M.message:M instanceof Error?M.message:String(M);Y.state="failed",Y.error=L,Y.currentStep=R;let A=Y.steps[V];if(A)A.status="failed",A.error=L,A.startedAt=o,A.endedAt=o,A.durationMs=0,A.exitCode=1;Y.lastUpdate=o,i(H,"failed",L),a(),h.push({agent:U.parallel.agent,output:L,error:L,success:!1,exitCode:1});break}if(_.parallel.length===0){let M=Date.now(),o=_.collectedOnEmpty??[];y[U.collect.as]={text:JSON.stringify(o),structured:o,agent:U.parallel.agent,stepIndex:H},Y.outputs=y;let L=Y.steps[V];if(L)L.status="complete",L.startedAt=M,L.endedAt=M,L.durationMs=0;T="Dynamic fanout produced 0 results.";let A=U.effectiveAcceptance?.explicit&&!E?await M1({acceptance:U.effectiveAcceptance,output:"",report:Ej({results:[],notes:"Dynamic fanout produced 0 results."}),cwd:Q,signal:L$.signal,abortMessage:p??"Subagent timed out."}):void 0,I=E||L$.signal.aborted,G$=I?void 0:A;if(L&&G$)L.acceptance=G$;let x$=G$?L1(G$):void 0;if(I||x$){let g=I?p??"Subagent timed out.":x$;if(Y.state="failed",Y.error=g,L)L.status="failed",L.error=g,L.exitCode=1,L.timedOut=I?!0:void 0;i(H,"failed",g,G$),Y.lastUpdate=Date.now(),a(),h.push({agent:U.parallel.agent,output:g,error:g,success:!1,exitCode:1,timedOut:I?!0:void 0,acceptance:G$});break}R++,Y.lastUpdate=M,i(H,"completed",void 0,G$),a();continue}let z=_.parallel.map((M,o)=>{let L=U.thinkingOverrides?.[o],A=L?W1(U.parallel.model,L,!0):U.parallel.model,I=L?O0(A,L):void 0;return{...U.parallel,task:M.task??U.parallel.task,label:M.label??U.parallel.label,...U.sessionFiles?.[o]?{sessionFile:U.sessionFiles[o]}:{},...L?{...A?{model:A}:{},...I?{thinking:I}:{},...U.parallel.modelCandidates?{modelCandidates:U.parallel.modelCandidates.map((G$)=>W1(G$,L,!0))}:{}}:{},structuredOutput:void 0,structuredOutputSchema:U.parallel.structuredOutputSchema??U.parallel.structuredOutput?.schema}}),N=Math.max(Y.steps.length-1+z.length,1),w=z.map((M,o)=>{let L=fj({artifactsDir:B,artifactConfig:q,runId:j,agent:M.agent,flatIndex:V+o,flatStepCount:N});return{agent:M.agent,phase:M.phase??U.phase,label:M.label,outputName:void 0,structured:Boolean(M.structuredOutputSchema),status:"pending",...M.sessionFile?{sessionFile:M.sessionFile}:{},...L?{transcriptPath:L}:{},skills:M.skills,model:M.model,thinking:M.thinking,attemptedModels:M.modelCandidates&&M.modelCandidates.length>0?M.modelCandidates:M.model?[M.model]:void 0,recentTools:[],recentOutput:[]}});if(Y.steps.splice(V,1,...w),$.childIntercomTargets)$.childIntercomTargets=Y.steps.map((M,o)=>Aj(j,M.agent,o));p0.splice(V,1,...w.map(()=>G1())),T0.splice(V,1,...w.map(()=>{return}));let d=w.length-1;for(let M of Y.parallelGroups)if(M.stepIndex===H)M.start=V,M.count=w.length;else if(M.start>V)M.start+=d;if(Y.workflowGraph){let M=(L)=>{for(let A of L){if(A.stepIndex!==void 0&&A.stepIndex>H&&A.flatIndex!==void 0&&A.flatIndex>=V)A.flatIndex+=w.length;if(A.children)M(A.children)}};M(Y.workflowGraph.nodes);let o=Y.workflowGraph.nodes.find((L)=>L.id===`step-${H}`);if(o)o.children=_.items.map((L,A)=>({id:`step-${H}-item-${L.idKey}`,kind:"agent",agent:U.parallel.agent,phase:z[A]?.phase??U.phase,label:z[A]?.label?.trim()||`${U.parallel.agent} ${L.key}`,status:"pending",flatIndex:V+A,stepIndex:H,itemKey:L.key,structured:Boolean(z[A]?.structuredOutputSchema)}))}a();let Z$=U.concurrency??k1,v=U.failFast??!1,F=!1,q$=await t0(z,Z$,async(M,o)=>{let L=V+o;if(E)return P(M.agent);if(s)return e$(M.agent);if(F&&v){let g=Date.now();return Y.steps[L].status="failed",Y.steps[L].error="Skipped due to fail-fast",Y.steps[L].startedAt=g,Y.steps[L].endedAt=g,Y.steps[L].durationMs=0,Y.steps[L].exitCode=-1,Y.lastUpdate=g,a(),{agent:M.agent,output:"(skipped — fail-fast)",exitCode:-1,skipped:!0}}let A=Date.now();Y.currentStep=L,Y.steps[L].status="running",Y.steps[L].error=void 0,Y.steps[L].activityState=void 0,yj(Y.steps[L]),Y.steps[L].startedAt=A,Y.steps[L].lastActivityAt=A,Y.outputFile=r.join(k,`output-${L}.log`),Y.lastActivityAt=A,Y.lastUpdate=A,a(),$$(n,JSON.stringify({type:"subagent.step.started",ts:A,runId:j,stepIndex:L,agent:M.agent})),C1(L);let I=await kj(M,{previousOutput:T,placeholder:X,cwd:Q,sessionEnabled:W0,outputs:y,sessionDir:$.sessionDir?r.join($.sessionDir,`dynamic-${H}-${o}`):void 0,artifactsDir:B,artifactConfig:q,id:j,flatIndex:L,flatStepCount:Math.max(Y.steps.length,1),outputFile:r.join(k,`output-${L}.log`),steerInboxDir:y0(k,L),piPackageRoot:$.piPackageRoot,piArgv1:$.piArgv1,childIntercomTarget:$.childIntercomTargets?.[L],orchestratorIntercomTarget:$.controlIntercomTarget,nestedRoute:$.nestedRoute,registerInterrupt:(g)=>A$(L,g),registerTimeout:(g)=>f$(L,g),registerTurnBudgetAbort:(g)=>S$(L,g),timeoutSignal:L$.signal,timeoutMessage:p,turnBudget:$.turnBudget,onAttemptStart:(g)=>T1(L,g.model,g.thinking),onChildEvent:(g)=>E1(L,g),skipAcceptance:()=>E}),G$=Date.now(),x$=I.interrupted===!0;if(Y.steps[L].status=E?"failed":x$?"paused":I.exitCode===0?"complete":"failed",Y.steps[L].endedAt=G$,Y.steps[L].durationMs=G$-A,Y.steps[L].exitCode=E?1:x$?0:I.exitCode,Y.steps[L].timedOut=E||I.timedOut?!0:void 0,Y.steps[L].turnBudget=I.turnBudget,Y.steps[L].turnBudgetExceeded=I.turnBudgetExceeded,Y.steps[L].wrapUpRequested=I.wrapUpRequested,Y.steps[L].toolBudget=I.toolBudget,Y.steps[L].toolBudgetBlocked=I.toolBudgetBlocked,I.toolBudget)Y.toolBudget=I.toolBudget;if(I.toolBudgetBlocked)Y.toolBudgetBlocked=!0;if(I.turnBudget)Y.turnBudget=I.turnBudget;if(I.turnBudgetExceeded)Y.turnBudgetExceeded=!0;if(I.wrapUpRequested)Y.wrapUpRequested=!0;if(Y.steps[L].model=I.model,Y.steps[L].thinking=O0(I.model,Y.steps[L].thinking),Y.steps[L].attemptedModels=I.attemptedModels,Y.steps[L].modelAttempts=I.modelAttempts,Y.steps[L].totalCost=I.totalCost,Y.steps[L].error=E?p??"Subagent timed out.":I.error,Y.steps[L].transcriptPath=I.transcriptPath??Y.steps[L].transcriptPath,Y.steps[L].transcriptError=I.transcriptError,Y.steps[L].structuredOutput=I.structuredOutput,Y.steps[L].structuredOutputPath=I.structuredOutputPath,Y.steps[L].structuredOutputSchemaPath=I.structuredOutputSchemaPath,Y.steps[L].acceptance=I.acceptance,Y.lastUpdate=G$,a(),$$(n,JSON.stringify({type:E?"subagent.step.failed":x$?"subagent.step.paused":I.exitCode===0?"subagent.step.completed":"subagent.step.failed",ts:G$,runId:j,stepIndex:L,agent:M.agent,exitCode:E?1:x$?0:I.exitCode,durationMs:G$-A})),I.exitCode!==0&&v)F=!0;return E?{...I,output:p??"Subagent timed out.",error:p??"Subagent timed out.",exitCode:1,interrupted:!1,timedOut:!0,skipped:!1}:{...I,skipped:!1}},O);R+=z.length;for(let M of q$)h.push({agent:M.agent,output:M.output,error:M.error,success:M.interrupted!==!0&&M.exitCode===0,exitCode:M.interrupted===!0?0:M.exitCode,skipped:M.skipped,interrupted:M.interrupted,timedOut:M.timedOut,turnBudget:M.turnBudget,turnBudgetExceeded:M.turnBudgetExceeded,wrapUpRequested:M.wrapUpRequested,toolBudget:M.toolBudget,toolBudgetBlocked:M.toolBudgetBlocked,sessionFile:M.sessionFile,intercomTarget:M.intercomTarget,model:M.model,attemptedModels:M.attemptedModels,modelAttempts:M.modelAttempts,totalCost:M.totalCost,artifactPaths:M.artifactPaths,transcriptPath:M.transcriptPath,transcriptError:M.transcriptError,structuredOutput:M.structuredOutput,structuredOutputPath:M.structuredOutputPath,structuredOutputSchemaPath:M.structuredOutputSchemaPath,acceptance:M.acceptance});let C=aJ(U,_.items,q$),z$=q$.filter((M)=>M.exitCode!==0&&M.exitCode!==-1);if(z$.length===0)try{Yj(U.collect.outputSchema,C),y[U.collect.as]={text:JSON.stringify(C),structured:C,agent:U.parallel.agent,stepIndex:H},Y.outputs=y;let M=U.effectiveAcceptance&&!E?await M1({acceptance:U.effectiveAcceptance,output:"",report:Ej({results:q$,notes:`Dynamic fanout collected ${C.length} result(s) into ${U.collect.as}.`}),cwd:Q,signal:L$.signal,abortMessage:p??"Subagent timed out."}):void 0,o=E||L$.signal.aborted,L=o?void 0:M,A=L?L1(L):void 0,I=o?p??"Subagent timed out.":A;if(i(H,I?"failed":"completed",I,L),I)h.push({agent:U.parallel.agent,output:I,error:I,success:!1,exitCode:1,timedOut:o?!0:void 0,structuredOutput:C,acceptance:L}),Y.error=I}catch(M){let o=M instanceof x?M.message:M instanceof Error?M.message:String(M);h.push({agent:U.parallel.agent,output:o,error:o,success:!1,exitCode:1,structuredOutput:C}),Y.error=o,i(H,"failed",o)}if(T=e0(q$.map((M,o)=>({agent:M.agent,taskIndex:o,output:M.output,exitCode:M.exitCode,error:M.error})),(M,o)=>`=== Dynamic Item ${M+1} (${o}, key ${_.items[M]?.key??M}) ===`),$$(n,JSON.stringify({type:"subagent.dynamic.completed",ts:Date.now(),runId:j,stepIndex:H,success:z$.length===0})),z$.length>0)i(H,"failed",z$[0]?.error??"Dynamic fanout child failed.");if(Y.lastUpdate=Date.now(),a(),z$.length>0||Y.error)break;continue}if($0(U)){let V=U,_=V.concurrency??k1,z=V.failFast??!1,N=R,w=!1,d;if(V.worktree){let Z$=O8(V.parallel,Q);if(Z$){let v=Date.now();p8({statusPayload:Y,results:h,group:V,groupStartFlatIndex:N,setupError:A8(Z$,Q),failedAt:v,statusPath:f,eventsPath:n,asyncDir:k,runId:j,stepIndex:H}),R+=V.parallel.length;break}try{d=C8(Q,`${j}-s${H}`,V.parallel.length,{agents:V.parallel.map((v)=>v.agent),setupHook:$.worktreeSetupHook?{hookPath:$.worktreeSetupHook,timeoutMs:$.worktreeSetupHookTimeoutMs}:void 0,baseDir:$.worktreeBaseDir})}catch(v){let F=v instanceof Error?v.message:String(v),q$=Date.now();p8({statusPayload:Y,results:h,group:V,groupStartFlatIndex:N,setupError:F,failedAt:q$,statusPath:f,eventsPath:n,asyncDir:k,runId:j,stepIndex:H}),R+=V.parallel.length;break}}try{if(V.worktree)n5(Q,V);let Z$=Date.now();u5({statusPayload:Y,group:V,groupStartFlatIndex:N,groupStartTime:Z$,statusPath:f,eventsPath:n,asyncDir:k,runId:j,stepIndex:H});let v=await t0(V.parallel,_,async(F,q$)=>{let C=N+q$;if(E)return P(F.agent);if(s)return e$(F.agent);if(w&&z){let g=Date.now();return Y.steps[C].status="failed",Y.steps[C].error="Skipped due to fail-fast",Y.steps[C].startedAt=g,Y.steps[C].endedAt=g,Y.steps[C].durationMs=0,Y.steps[C].exitCode=-1,Y.steps[C].activityState=void 0,Y.lastUpdate=g,a(),$$(n,JSON.stringify({type:"subagent.step.failed",ts:g,runId:j,stepIndex:C,agent:F.agent,exitCode:-1,durationMs:0})),{agent:F.agent,output:"(skipped — fail-fast)",exitCode:-1,skipped:!0}}let z$=Date.now();Y.currentStep=C,Y.steps[C].status="running",Y.steps[C].error=void 0,Y.steps[C].activityState=void 0,yj(Y.steps[C]),Y.steps[C].startedAt=z$,Y.steps[C].endedAt=void 0,Y.steps[C].durationMs=void 0,Y.steps[C].lastActivityAt=z$,Y.outputFile=r.join(k,`output-${C}.log`),Y.lastActivityAt=z$,Y.lastUpdate=z$,a(),$$(n,JSON.stringify({type:"subagent.step.started",ts:z$,runId:j,stepIndex:C,agent:F.agent}));let M=$.sessionDir?r.join($.sessionDir,`parallel-${q$}`):void 0,{taskForRun:o,taskCwd:L}=l5(F,Q,d,q$);C1(C);let A=await kj(o,{previousOutput:T,placeholder:X,cwd:L,sessionEnabled:W0,outputs:y,sessionDir:M,artifactsDir:B,artifactConfig:q,id:j,flatIndex:C,flatStepCount:Math.max(Y.steps.length,1),outputFile:r.join(k,`output-${C}.log`),steerInboxDir:y0(k,C),piPackageRoot:$.piPackageRoot,piArgv1:$.piArgv1,childIntercomTarget:$.childIntercomTargets?.[C],orchestratorIntercomTarget:$.controlIntercomTarget,nestedRoute:$.nestedRoute,registerInterrupt:(g)=>A$(C,g),registerTimeout:(g)=>f$(C,g),registerTurnBudgetAbort:(g)=>S$(C,g),timeoutSignal:L$.signal,timeoutMessage:p,turnBudget:$.turnBudget,onAttemptStart:(g)=>T1(C,g.model,g.thinking),onChildEvent:(g)=>E1(C,g),skipAcceptance:()=>E});if(F.sessionFile)o$=F.sessionFile;let I=Date.now(),G$=I-z$,x$=A.interrupted===!0;if(Y.steps[C].status=E?"failed":x$?"paused":A.exitCode===0?"complete":"failed",Y.steps[C].endedAt=I,Y.steps[C].durationMs=G$,Y.steps[C].exitCode=E?1:x$?0:A.exitCode,Y.steps[C].timedOut=E||A.timedOut?!0:void 0,Y.steps[C].turnBudget=A.turnBudget,Y.steps[C].turnBudgetExceeded=A.turnBudgetExceeded,Y.steps[C].wrapUpRequested=A.wrapUpRequested,Y.steps[C].toolBudget=A.toolBudget,Y.steps[C].toolBudgetBlocked=A.toolBudgetBlocked,A.toolBudget)Y.toolBudget=A.toolBudget;if(A.toolBudgetBlocked)Y.toolBudgetBlocked=!0;if(A.turnBudget)Y.turnBudget=A.turnBudget;if(A.turnBudgetExceeded)Y.turnBudgetExceeded=!0;if(A.wrapUpRequested)Y.wrapUpRequested=!0;if(Y.steps[C].model=A.model,Y.steps[C].thinking=O0(A.model,Y.steps[C].thinking),Y.steps[C].attemptedModels=A.attemptedModels,Y.steps[C].modelAttempts=A.modelAttempts,Y.steps[C].totalCost=A.totalCost,Y.steps[C].error=E?p??"Subagent timed out.":A.error,Y.steps[C].transcriptPath=A.transcriptPath??Y.steps[C].transcriptPath,Y.steps[C].transcriptError=A.transcriptError,Y.steps[C].structuredOutput=A.structuredOutput,Y.steps[C].structuredOutputPath=A.structuredOutputPath,Y.steps[C].structuredOutputSchemaPath=A.structuredOutputSchemaPath,Y.steps[C].acceptance=A.acceptance,Y.lastUpdate=I,a(),$$(n,JSON.stringify({type:E?"subagent.step.failed":x$?"subagent.step.paused":A.exitCode===0?"subagent.step.completed":"subagent.step.failed",ts:I,runId:j,stepIndex:C,agent:F.agent,exitCode:E?1:x$?0:A.exitCode,durationMs:G$})),A.completionGuardTriggered){let g=A0({from:Y.steps[C].activityState,to:"needs_attention",runId:j,agent:F.agent,index:C,ts:I,message:`${F.agent} completed without making edits for an implementation task`,reason:"completion_guard"});E0(g)}if(A.exitCode!==0&&z)w=!0;return E?{...A,output:p??"Subagent timed out.",error:p??"Subagent timed out.",exitCode:1,interrupted:!1,timedOut:!0,skipped:!1}:{...A,skipped:!1}},O);R+=V.parallel.length;for(let F=0;F<V.parallel.length;F++){let q$=N+F,z$=($.sessionDir?Fj(r.join($.sessionDir,`parallel-${F}`)):null)??u8(v[F]?.modelAttempts);if(!z$)continue;Y.steps[q$].tokens=z$,Y$={input:Y$.input+z$.input,output:Y$.output+z$.output,total:Y$.total+z$.total}}Y.totalTokens={...Y$},Y.lastUpdate=Date.now(),a();for(let F of v)h.push({agent:F.agent,output:F.output,error:F.error,success:F.interrupted!==!0&&F.exitCode===0,exitCode:F.interrupted===!0?0:F.exitCode,skipped:F.skipped,interrupted:F.interrupted,timedOut:F.timedOut,turnBudget:F.turnBudget,turnBudgetExceeded:F.turnBudgetExceeded,wrapUpRequested:F.wrapUpRequested,toolBudget:F.toolBudget,toolBudgetBlocked:F.toolBudgetBlocked,sessionFile:F.sessionFile,intercomTarget:F.intercomTarget,model:F.model,attemptedModels:F.attemptedModels,modelAttempts:F.modelAttempts,totalCost:F.totalCost,artifactPaths:F.artifactPaths,transcriptPath:F.transcriptPath,transcriptError:F.transcriptError,structuredOutput:F.structuredOutput,structuredOutputPath:F.structuredOutputPath,structuredOutputSchemaPath:F.structuredOutputSchemaPath,acceptance:F.acceptance});for(let F=0;F<V.parallel.length;F++){let q$=V.parallel[F]?.outputName;if(q$)y[q$]=Hj({agent:v[F].agent,output:v[F].output,structuredOutput:v[F].structuredOutput},H)}if(Y.outputs=y,T=e0(v.map((F)=>({agent:F.agent,output:F.output,exitCode:F.exitCode,error:F.error,model:F.model,attemptedModels:F.attemptedModels}))),T=p5(T,d,k,H,V),$$(n,JSON.stringify({type:"subagent.parallel.completed",ts:Date.now(),runId:j,stepIndex:H,success:v.every((F)=>F.exitCode===0||F.exitCode===-1)})),v.some((F)=>F.exitCode!==0&&F.exitCode!==-1))break}finally{if(d)Oj(d)}}else{let V=U,_=Date.now();Y.currentStep=R,Y.steps[R].status="running",Y.steps[R].activityState=void 0,Y.activityState=void 0,yj(Y.steps[R]),Y.steps[R].skills=V.skills,Y.steps[R].startedAt=_,Y.steps[R].lastActivityAt=_,Y.lastActivityAt=_,Y.lastUpdate=_,Y.outputFile=r.join(k,`output-${R}.log`),a(),$$(n,JSON.stringify({type:"subagent.step.started",ts:_,runId:j,stepIndex:R,agent:V.agent})),C1(R);let z=await kj(V,{previousOutput:T,placeholder:X,cwd:Q,sessionEnabled:W0,outputs:y,sessionDir:$.sessionDir,artifactsDir:B,artifactConfig:q,id:j,flatIndex:R,flatStepCount:Math.max(Y.steps.length,1),outputFile:r.join(k,`output-${R}.log`),steerInboxDir:y0(k,R),piPackageRoot:$.piPackageRoot,piArgv1:$.piArgv1,childIntercomTarget:$.childIntercomTargets?.[R],orchestratorIntercomTarget:$.controlIntercomTarget,nestedRoute:$.nestedRoute,registerInterrupt:(v)=>A$(R,v),registerTimeout:(v)=>f$(R,v),registerTurnBudgetAbort:(v)=>S$(R,v),timeoutSignal:L$.signal,timeoutMessage:p,turnBudget:$.turnBudget,onAttemptStart:(v)=>T1(R,v.model,v.thinking),onChildEvent:(v)=>E1(R,v),skipAcceptance:()=>E});if(V.sessionFile)o$=V.sessionFile;if(T=z.output,h.push({agent:z.agent,output:E?p??"Subagent timed out.":z.output,error:E?p??"Subagent timed out.":z.error,success:!E&&z.interrupted!==!0&&z.exitCode===0,exitCode:E?1:z.interrupted===!0?0:z.exitCode,sessionFile:z.sessionFile,intercomTarget:z.intercomTarget,model:z.model,attemptedModels:z.attemptedModels,modelAttempts:z.modelAttempts,totalCost:z.totalCost,artifactPaths:z.artifactPaths,transcriptPath:z.transcriptPath,transcriptError:z.transcriptError,structuredOutput:z.structuredOutput,structuredOutputPath:z.structuredOutputPath,structuredOutputSchemaPath:z.structuredOutputSchemaPath,acceptance:z.acceptance,interrupted:z.interrupted,timedOut:E||z.timedOut?!0:void 0,turnBudget:z.turnBudget,turnBudgetExceeded:z.turnBudgetExceeded,wrapUpRequested:z.wrapUpRequested,toolBudget:z.toolBudget,toolBudgetBlocked:z.toolBudgetBlocked}),V.outputName)y[V.outputName]=Hj({agent:z.agent,output:z.output,structuredOutput:z.structuredOutput},H);Y.outputs=y;let N=$.sessionDir?Fj($.sessionDir):null,w=N?{input:N.input-Y$.input,output:N.output-Y$.output,total:N.total-Y$.total}:null;if(N)Y$=N;else if(w=u8(z.modelAttempts),w)Y$={input:Y$.input+w.input,output:Y$.output+w.output,total:Y$.total+w.total};let d=Date.now(),Z$=z.interrupted===!0;if(Y.steps[R].status=E?"failed":Z$?"paused":z.exitCode===0?"complete":"failed",Y.steps[R].endedAt=d,Y.steps[R].durationMs=d-_,Y.steps[R].exitCode=E?1:Z$?0:z.exitCode,Y.steps[R].timedOut=E||z.timedOut?!0:void 0,Y.steps[R].turnBudget=z.turnBudget,Y.steps[R].turnBudgetExceeded=z.turnBudgetExceeded,Y.steps[R].wrapUpRequested=z.wrapUpRequested,Y.steps[R].toolBudget=z.toolBudget,Y.steps[R].toolBudgetBlocked=z.toolBudgetBlocked,z.toolBudget)Y.toolBudget=z.toolBudget;if(z.toolBudgetBlocked)Y.toolBudgetBlocked=!0;if(z.turnBudget)Y.turnBudget=z.turnBudget;if(z.turnBudgetExceeded)Y.turnBudgetExceeded=!0;if(z.wrapUpRequested)Y.wrapUpRequested=!0;if(Y.steps[R].model=z.model,Y.steps[R].thinking=O0(z.model,Y.steps[R].thinking),Y.steps[R].attemptedModels=z.attemptedModels,Y.steps[R].modelAttempts=z.modelAttempts,Y.steps[R].totalCost=z.totalCost,Y.steps[R].error=E?p??"Subagent timed out.":z.error,Y.steps[R].transcriptPath=z.transcriptPath??Y.steps[R].transcriptPath,Y.steps[R].transcriptError=z.transcriptError,Y.steps[R].structuredOutput=z.structuredOutput,Y.steps[R].structuredOutputPath=z.structuredOutputPath,Y.steps[R].structuredOutputSchemaPath=z.structuredOutputSchemaPath,Y.steps[R].acceptance=z.acceptance,w)Y.steps[R].tokens=w,Y.totalTokens={...Y$};if(Y.lastUpdate=d,a(),$$(n,JSON.stringify({type:E?"subagent.step.failed":Z$?"subagent.step.paused":z.exitCode===0?"subagent.step.completed":"subagent.step.failed",ts:d,runId:j,stepIndex:R,agent:V.agent,exitCode:E?1:Z$?0:z.exitCode,durationMs:d-_,tokens:w})),z.completionGuardTriggered){let v=A0({from:Y.steps[R].activityState,to:"needs_attention",runId:j,agent:V.agent,index:R,ts:d,message:`${V.agent} completed without making edits for an implementation task`,reason:"completion_guard"});E0(v)}if(R++,z.exitCode!==0)break}}let n0=h.map((H)=>`${H.agent}:
72
+ ${U}`}function i5($,j){let J=r.join($,"progress.md");if(!j.parallel.some((Z)=>Z.task.includes(`Update progress at: ${J}`)))return;ej($)}function fj($){if(!$.artifactsDir||$.artifactConfig?.enabled===!1||$.artifactConfig?.includeTranscript===!1)return;return c1($.artifactsDir,$.runId,$.agent,$.flatStepCount>1?$.flatIndex:void 0).transcriptPath}async function n8($){let{id:j,steps:J,resultPath:Z,cwd:Q,placeholder:X,taskIndex:W,totalTasks:U,maxOutput:G,artifactsDir:B,artifactConfig:q}=$,O=new y1($.globalConcurrencyLimit??tj),T="",y={},h=[],S=Date.now(),v$=$.share===!0,k=$.asyncDir,f=r.join(k,"status.json"),n=r.join(k,"events.jsonl"),d$=r.join(k,`subagent-log-${j}.md`),W$=$.controlConfig??LJ,y$=new Map,K$=new Map,g$=new Map,A$=[],s=!1,S$,X$,_$,E=!1,t=!1,p=$.timeoutMs!==void 0?`Subagent timed out after ${$.timeoutMs}ms.`:void 0,q$=new AbortController,Y$={input:0,output:0,total:0},o$,u$=aj(J),j$=u$.length,c=[],H$=[],k$=0;for(let H=0;H<J.length;H++){let V=J[H];if($0(V)){c.push({start:k$,count:V.parallel.length,stepIndex:H});for(let K of V.parallel){let _=k$,z=fj({artifactsDir:B,artifactConfig:q,runId:j,agent:K.agent,flatIndex:_,flatStepCount:j$});H$.push({agent:K.agent,phase:K.phase,label:K.label,outputName:K.outputName,structured:K.structured,status:"pending",...K.toolBudget?{toolBudget:C0(K.toolBudget)}:{},...K.sessionFile?{sessionFile:K.sessionFile}:{},...z?{transcriptPath:z}:{},skills:K.skills,model:K.model,thinking:K.thinking,attemptedModels:K.modelCandidates&&K.modelCandidates.length>0?K.modelCandidates:K.model?[K.model]:void 0,recentTools:[],recentOutput:[]}),k$++}}else if(j0(V))c.push({start:k$,count:1,stepIndex:H}),H$.push({agent:`expand:${V.parallel.agent}`,phase:V.phase??V.parallel.phase,label:V.label??V.parallel.label??`Dynamic fanout (${V.collect.as})`,outputName:V.collect.as,structured:Boolean(V.collect.outputSchema),status:"pending",...V.parallel.toolBudget?{toolBudget:C0(V.parallel.toolBudget)}:{},recentTools:[],recentOutput:[]}),k$++;else{let K=k$,_=fj({artifactsDir:B,artifactConfig:q,runId:j,agent:V.agent,flatIndex:K,flatStepCount:j$});H$.push({agent:V.agent,phase:V.phase,label:V.label,outputName:V.outputName,structured:V.structured,status:"pending",...V.toolBudget?{toolBudget:C0(V.toolBudget)}:{},...V.sessionFile?{sessionFile:V.sessionFile}:{},..._?{transcriptPath:_}:{},skills:V.skills,model:V.model,thinking:V.thinking,attemptedModels:V.modelCandidates&&V.modelCandidates.length>0?V.modelCandidates:V.model?[V.model]:void 0,recentTools:[],recentOutput:[]}),k$++}}let W0=Boolean($.sessionDir)||v$||u$.some((H)=>Boolean(H.sessionFile)),Y={lifecycleArtifactVersion:S0,runId:j,...$.sessionId?{sessionId:$.sessionId}:{},mode:$.resultMode??(u$.length>1?"chain":"single"),state:"running",lastActivityAt:S,startedAt:S,lastUpdate:S,...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},...$.deadlineAt!==void 0?{deadlineAt:$.deadlineAt}:{},...$.turnBudget?{turnBudget:Rj($.turnBudget)}:{},...$.toolBudget?{toolBudget:C0($.toolBudget)}:{},pid:process.pid,cwd:Q,currentStep:0,chainStepCount:J.length,parallelGroups:c,workflowGraph:$.workflowGraph,steps:H$,artifactsDir:B,sessionDir:$.sessionDir,outputFile:r.join(k,"output-0.log")};e.mkdirSync(k,{recursive:!0}),b$(f,Y);let u=(H)=>{if(!$.nestedRoute||!$.nestedSelf)return;try{Q8($.nestedRoute,{type:H,ts:Date.now(),parentRunId:$.nestedSelf.parentRunId,parentStepIndex:$.nestedSelf.parentStepIndex,child:X8(Y,k,{id:j,parentRunId:$.nestedSelf.parentRunId,parentStepIndex:$.nestedSelf.parentStepIndex,depth:$.nestedSelf.depth,path:$.nestedSelf.path,mode:Y.mode,ts:Date.now()})})}catch(V){console.error("Failed to emit nested async status event:",V)}},U$=()=>{if(!$.workflowGraph)return;let H=structuredClone(Y.workflowGraph??$.workflowGraph),V=(_)=>{if(_==="complete"||_==="completed")return"completed";if(_==="running"||_==="failed"||_==="paused"||_==="pending")return _;return"pending"},K=(_)=>{if(_.flatIndex!==void 0){let z=Y.steps[_.flatIndex];if(z)_.status=V(z.status),_.error=z.error,_.acceptanceStatus=z.acceptance?.status;if(Y.currentStep===_.flatIndex)H.currentNodeId=_.id}for(let z of _.children??[])K(z);if(_.children?.length){if(_.children.every((z)=>z.status==="completed"))_.status="completed";else if(_.children.some((z)=>z.status==="running"))_.status="running";else if(_.children.some((z)=>z.status==="failed"))_.status="failed";else if(_.children.some((z)=>z.status==="paused"))_.status="paused"}if(_.error)_.status="failed"};for(let _ of H.nodes)K(_);Y.workflowGraph=H},a=()=>{U$(),b$(f,Y),u(Y.state==="running"||Y.state==="queued"?"subagent.nested.updated":"subagent.nested.completed")},N$=(H,V)=>{if(!V){y$.delete(H);return}if(y$.set(H,V),s)V()},f$=(H,V)=>{if(!V){K$.delete(H);return}if(K$.set(H,V),E)V()},D$=(H,V)=>{if(!V){g$.delete(H);return}g$.set(H,V)},t$=()=>{for(let H of[...y$.values()])H()},P$=()=>{for(let H of[...K$.values()])H()},V$=function*(H){for(let V of H??[])yield V,yield*V$(V.children),yield*V$(V.steps?.flatMap((K)=>K.children??[]))},l$=()=>{if(!$.nestedRoute)return;let H;try{H=Mj($.nestedRoute)}catch(V){$$(n,JSON.stringify({type:"subagent.nested.interrupt_failed",ts:Date.now(),runId:j,message:V instanceof Error?V.message:String(V)}));return}for(let V of V$(H.children)){if(V.state!=="running"&&V.state!=="queued")continue;let K=V.asyncDir??_j($.nestedRoute.rootRunId,V);if(!K)continue;try{KJ({asyncDir:K,pid:V.pid,source:"ancestor-interrupt"})}catch(_){$$(n,JSON.stringify({type:"subagent.nested.interrupt_failed",ts:Date.now(),runId:j,targetRunId:V.id,message:_ instanceof Error?_.message:String(_)}))}}},p$=()=>{if(!$.nestedRoute)return;let H;try{H=Mj($.nestedRoute)}catch(V){$$(n,JSON.stringify({type:"subagent.nested.timeout_failed",ts:Date.now(),runId:j,message:V instanceof Error?V.message:String(V)}));return}for(let V of V$(H.children)){if(V.state!=="running"&&V.state!=="queued")continue;let K=V.asyncDir??_j($.nestedRoute.rootRunId,V);if(!K)continue;try{m1({asyncDir:K,pid:V.pid,source:"ancestor-timeout"})}catch(_){$$(n,JSON.stringify({type:"subagent.nested.timeout_failed",ts:Date.now(),runId:j,targetRunId:V.id,message:_ instanceof Error?_.message:String(_)}))}}},e$=(H)=>({agent:H,output:"Paused after interrupt. Waiting for explicit next action.",exitCode:0,interrupted:!0}),P=(H)=>({agent:H,output:p??"Subagent timed out.",error:p??"Subagent timed out.",exitCode:1,timedOut:!0}),D=()=>{if(Y.mode!=="chain"||Y.state!=="running")return;let H=h8(k);if(H.length===0){let N=Dj(k);if((Y.pendingAppends??0)!==N)Y.pendingAppends=N,Y.lastUpdate=Date.now(),a();return}let V=H.flatMap((N)=>N.steps);J.push(...V);let K=Date.now(),_=Dj(k),z=g8({status:Y,steps:V,now:K,pendingAppends:_});if(p0.push(...Array.from({length:z.addedFlatSteps},()=>G1())),T0.push(...Array.from({length:z.addedFlatSteps},()=>{return})),$.childIntercomTargets)$.childIntercomTargets=Y.steps.map((N,w)=>Aj(j,N.agent,w));a();for(let N of H)$$(n,JSON.stringify({type:"subagent.chain.append.accepted",ts:K,runId:j,requestId:N.id,stepCount:N.steps.length,pendingAppends:_}))},i=(H,V,K,_)=>{let z=Y.workflowGraph?.nodes.find((N)=>N.id===`step-${H}`);if(!z)return;z.status=V,z.error=K,z.acceptanceStatus=_?.status??z.acceptanceStatus},M$=(H)=>{let V=Y.steps[H],K=V?.lastActivityAt??V?.startedAt??S,_=r.join(k,`output-${H}.log`);try{K=Math.max(K,e.statSync(_).mtimeMs)}catch(z){if(z.code!=="ENOENT")console.error(`Failed to inspect async output file '${_}':`,z)}return K},l0=new Set,vj=new Set,p0=H$.map(()=>G1()),T0=H$.map(()=>{return}),i8=300000,E0=(H)=>{if(!W$.enabled)return;let V=$.childIntercomTargets?.[H.index??Y.currentStep],K=H.type==="active_long_running"?W$.notifyChannels.filter((_)=>_!=="intercom"):W$.notifyChannels;if(K.length===0||!FJ(W$,H,l0,V))return;$$(n,JSON.stringify({type:"subagent.control",event:H,channels:K,childIntercomTarget:V,noticeText:p1(H,V),...$.controlIntercomTarget&&K.includes("intercom")?{intercom:{to:$.controlIntercomTarget,message:OJ(H,V)}}:{}}))},A1=()=>{let H=Y.steps.filter((V)=>V.status==="running"&&typeof V.currentTool==="string"&&V.currentTool.length>0).sort((V,K)=>(K.currentToolStartedAt??0)-(V.currentToolStartedAt??0))[0];Y.currentTool=H?.currentTool,Y.currentToolStartedAt=H?.currentToolStartedAt,Y.currentPath=H?.currentPath},gj=(H,V)=>{if(!W$.enabled||vj.has(H))return!1;let K=Y.steps[H];if(!K||K.status!=="running"||K.activityState==="needs_attention")return!1;let _=U8(W$,{startedAt:K.startedAt??S,now:V,turns:K.turnCount??0,tokens:K.tokens?.total??0});if(!_)return!1;vj.add(H);let z=K.activityState;K.activityState="active_long_running",Y.activityState=Y.activityState==="needs_attention"?"needs_attention":"active_long_running";let N=A0({type:"active_long_running",from:z,to:"active_long_running",runId:j,agent:K.agent,index:H,ts:V,message:`${K.agent} is still active but long-running`,reason:_,turns:K.turnCount,tokens:K.tokens?.total,toolCount:K.toolCount,currentTool:K.currentTool,currentToolDurationMs:K.currentToolStartedAt?Math.max(0,V-K.currentToolStartedAt):void 0,currentPath:K.currentPath,elapsedMs:V-(K.startedAt??S)});return E0(N),!0},N1=(H)=>{if(Y.state!=="running")return;let V=Y.steps.map((w,d)=>({step:w,index:d})).filter(({step:w})=>w.status==="running").map(({index:w})=>w),K=H.targetIndex!==void 0?[H.targetIndex]:V,_=Date.now(),z=[],N=[];for(let w of K){let d=Y.steps[w];if(!d){N.push({index:w,reason:"child index out of range"});continue}if(d.status!=="running"){N.push({index:w,reason:`child is ${d.status}`});continue}VJ(k,w,H),d.steerCount=(d.steerCount??0)+1,d.lastSteerAt=_,z.push(w)}if(z.length>0)Y.steerCount=(Y.steerCount??0)+z.length,Y.lastSteerAt=_,Y.lastUpdate=_,a();$$(n,JSON.stringify({type:"subagent.steer.requested",ts:_,runId:j,requestId:H.id,message:H.message,...H.source?{source:H.source}:{},...H.targetIndex!==void 0?{targetIndex:H.targetIndex}:{},acceptedIndexes:z,...N.length?{rejected:N}:{}}))},C1=(H)=>{let V=[];for(let K of A$.splice(0))if(K.targetIndex===void 0)N1({...K,targetIndex:H});else if(K.targetIndex===H)N1(K);else V.push(K);A$.push(...V)},T1=(H,V,K,_=Date.now())=>{let z=Y.steps[H];if(!z)return;z.model=V,z.thinking=K,Y.lastUpdate=_,a()},r8=(H,V,K,_)=>{let z=$.turnBudget,N=Y.steps[H];if(!z||!N||E||t||N.turnBudgetExceeded)return;if(V<z.maxTurns){let v={...z,outcome:"within-budget",turnCount:V};N.turnBudget=v,Y.turnBudget=v;return}let w=O1(z,V,!1);if(N.turnBudget=w,Y.turnBudget=w,!N.wrapUpRequested)N.wrapUpRequested=!0,Y.wrapUpRequested=!0,Ij(N,[bj(z,V)]);if(!wj(z,V,_))return;let d=O1(z,V,!0),Z$=u0(z,V);N.turnBudget=d,N.turnBudgetExceeded=!0,N.wrapUpRequested=!0,N.error=Z$,t=!0,Y.turnBudget=d,Y.turnBudgetExceeded=!0,Y.wrapUpRequested=!0,Y.error=Z$,Y.lastUpdate=K,$$(n,JSON.stringify({type:"subagent.step.turn_budget_exceeded",ts:K,runId:j,stepIndex:H,agent:N.agent,turnCount:V,maxTurns:z.maxTurns,graceTurns:z.graceTurns,message:Z$})),g$.get(H)?.(Z$,d)},E1=(H,V)=>{let K=Y.steps[H];if(!K)return;let _=Date.now();if(Y.currentStep=H,V.type==="tool_execution_start"&&V.toolName){let z=qj(V.toolName,V.args),N=V8(V.toolName,V.args);K.toolCount=(K.toolCount??0)+1;let w=u$[H]?.toolBudget;if(w)K.toolBudget=Z1(w,K.toolCount),Y.toolBudget=K.toolBudget;K.currentTool=V.toolName,K.currentToolArgs=w0(V.args??{}),K.currentToolStartedAt=_,K.currentPath=N,T0[H]={tool:V.toolName,path:N,mutates:z,startedAt:_},Y.toolCount=(Y.toolCount??0)+1,A1()}else if(V.type==="tool_execution_end"){if(K.currentTool)K.recentTools??=[],K.recentTools.push({tool:K.currentTool,args:K.currentToolArgs||"",endMs:_});K.currentTool=void 0,K.currentToolArgs=void 0,K.currentToolStartedAt=void 0,K.currentPath=void 0,A1()}else if(V.type==="tool_result_end"&&V.message){let z=T0[H];T0[H]=void 0;let N=s$(V.message.content);if(z&&N.includes("Tool budget hard limit reached")){let w=u$[H]?.toolBudget;if(w)K.toolBudget=Z1(w,K.toolCount??0,z.tool),K.toolBudgetBlocked=!0,Y.toolBudget=K.toolBudget,Y.toolBudgetBlocked=!0}if(Ij(K,N.split(`
73
+ `).slice(-10)),z?.mutates&&K8(N)){let w=p0[H];if(G8(w,{tool:z.tool,path:z.path,error:N.split(`
74
+ `).find((d)=>d.trim())?.trim().slice(0,180)??"mutating tool failed",ts:_},i8),W$.enabled&&B8(w,W$.failedToolAttemptsBeforeAttention)&&K.activityState!=="needs_attention"){let d=K.activityState;K.activityState="needs_attention",Y.activityState="needs_attention",E0(A0({type:"needs_attention",from:d,to:"needs_attention",runId:j,agent:K.agent,index:H,ts:_,message:`${K.agent} needs attention after repeated mutating tool failures`,reason:"tool_failures",turns:K.turnCount,tokens:K.tokens?.total,toolCount:K.toolCount,currentTool:z.tool,currentToolDurationMs:z.startedAt?Math.max(0,_-z.startedAt):void 0,currentPath:z.path,recentFailureSummary:_8(w)}))}}else if(z?.mutates)z8(p0[H])}else if(V.type==="message_end"&&V.message?.role==="assistant"){Ij(K,Cj(s$(V.message.content)).split(`
75
+ `).slice(-10)),K.turnCount=(K.turnCount??0)+1;let z=V.message.usage;if(z){let N=z.input??z.inputTokens??0,w=z.output??z.outputTokens??0,d=K.tokens?.input??0,Z$=K.tokens?.output??0;K.tokens={input:d+N,output:Z$+w,total:d+Z$+N+w};let v=Y.totalTokens?.input??0,F=Y.totalTokens?.output??0;Y.totalTokens={input:v+N,output:F+w,total:v+F+N+w}}Y.turnCount=Math.max(Y.turnCount??0,K.turnCount),r8(H,K.turnCount,_,hj(V.message))}A1(),K.lastActivityAt=_,Y.lastActivityAt=_,Y.lastUpdate=_,gj(H,_),a()},s8=(H)=>{if(!W$.enabled)return!1;let V=!1,K=Y.lastActivityAt??S;for(let z=0;z<Y.steps.length;z++){let N=Y.steps[z];if(N.status!=="running")continue;let w=M$(z);if(K=Math.max(K,w),N.lastActivityAt!==w)N.lastActivityAt=w,V=!0;if(qJ({config:W$,startedAt:N.startedAt??S,lastActivityAt:w,now:H})==="needs_attention"){let Z$=N.activityState;if(N.activityState="needs_attention",Z$!=="needs_attention")E0(A0({from:Z$,to:"needs_attention",runId:j,agent:N.agent,index:z,ts:H,lastActivityAt:w})),V=!0}else if(gj(z,H))V=!0}if(Y.lastActivityAt!==K)Y.lastActivityAt=K,V=!0;let _=Y.steps.some((z)=>z.activityState==="needs_attention")?"needs_attention":Y.steps.some((z)=>z.activityState==="active_long_running")?"active_long_running":void 0;if(_!==S$)S$=_,Y.activityState=_,V=!0;if(Y.lastUpdate=H,V)a();return V};if(W$.enabled)X$=setInterval(()=>{if(Y.state!=="running")return;let H=Date.now();s8(H)},1000),X$.unref?.();let mj=()=>{if(g1(k),s||Y.state!=="running")return;s=!0;let H=Date.now();Y.state="paused",S$=void 0,Y.activityState=void 0,Y.lastUpdate=H;for(let V of Y.steps)if(V.status==="running")V.status="paused",V.activityState=void 0,V.endedAt=H,V.durationMs=V.startedAt?H-V.startedAt:void 0,V.lastActivityAt=H;a(),$$(n,JSON.stringify({type:"subagent.run.paused",ts:H,runId:j})),l$(),t$()},cj=()=>{if(E||s||Y.state!=="running")return;E=!0;let H=Date.now(),V=p??"Subagent timed out.";Y.state="failed",Y.timedOut=!0,Y.error=V,S$=void 0,Y.activityState=void 0,Y.lastUpdate=H;for(let K of Y.steps){if(K.status!=="running"&&K.status!=="pending")continue;K.status="failed",K.error=V,K.exitCode=1,K.timedOut=!0,K.activityState=void 0,K.endedAt=H,K.durationMs=K.startedAt?H-K.startedAt:0,K.lastActivityAt=H}a(),$$(n,JSON.stringify({type:"subagent.run.timed_out",ts:H,runId:j,timeoutMs:$.timeoutMs,deadlineAt:$.deadlineAt,message:V})),q$.abort(),p$(),P$()};process.on(R5,mj);let a8=UJ(k,{onInterrupt:mj,onTimeout:cj,onSteer:(H)=>{if((H.targetIndex!==void 0?Y.steps[H.targetIndex]:void 0)?.status==="pending")A$.push(H);else if(H.targetIndex!==void 0||Y.steps.some((K)=>K.status==="running"))N1(H);else A$.push(H)}});if($.deadlineAt!==void 0){let H=Math.max(0,$.deadlineAt-Date.now());_$=setTimeout(cj,H),_$.unref?.()}$$(n,JSON.stringify({type:"subagent.run.started",lifecycleArtifactVersion:S0,ts:S,runId:j,mode:Y.mode,cwd:Q,pid:process.pid}));let R=0,dj=0;while(!0){if(s||E||t)break;if(D(),dj>=J.length)break;let H=dj++,V=J[H];if(j0(V)){let K=R,_;try{if(_=sJ(V,y,H,{maxItems:$.dynamicFanoutMaxItems,allowRunnerFields:!0}),_.collectedOnEmpty)Yj(V.collect.outputSchema,_.collectedOnEmpty)}catch(M){let o=Date.now(),L=M instanceof x?M.message:M instanceof Error?M.message:String(M);Y.state="failed",Y.error=L,Y.currentStep=R;let A=Y.steps[K];if(A)A.status="failed",A.error=L,A.startedAt=o,A.endedAt=o,A.durationMs=0,A.exitCode=1;Y.lastUpdate=o,i(H,"failed",L),a(),h.push({agent:V.parallel.agent,output:L,error:L,success:!1,exitCode:1});break}if(_.parallel.length===0){let M=Date.now(),o=_.collectedOnEmpty??[];y[V.collect.as]={text:JSON.stringify(o),structured:o,agent:V.parallel.agent,stepIndex:H},Y.outputs=y;let L=Y.steps[K];if(L)L.status="complete",L.startedAt=M,L.endedAt=M,L.durationMs=0;T="Dynamic fanout produced 0 results.";let A=V.effectiveAcceptance?.explicit&&!E?await M1({acceptance:V.effectiveAcceptance,output:"",report:Ej({results:[],notes:"Dynamic fanout produced 0 results."}),cwd:Q,signal:q$.signal,abortMessage:p??"Subagent timed out."}):void 0,I=E||q$.signal.aborted,G$=I?void 0:A;if(L&&G$)L.acceptance=G$;let x$=G$?L1(G$):void 0;if(I||x$){let g=I?p??"Subagent timed out.":x$;if(Y.state="failed",Y.error=g,L)L.status="failed",L.error=g,L.exitCode=1,L.timedOut=I?!0:void 0;i(H,"failed",g,G$),Y.lastUpdate=Date.now(),a(),h.push({agent:V.parallel.agent,output:g,error:g,success:!1,exitCode:1,timedOut:I?!0:void 0,acceptance:G$});break}R++,Y.lastUpdate=M,i(H,"completed",void 0,G$),a();continue}let z=_.parallel.map((M,o)=>{let L=V.thinkingOverrides?.[o],A=L?W1(V.parallel.model,L,!0):V.parallel.model,I=L?O0(A,L):void 0;return{...V.parallel,task:M.task??V.parallel.task,label:M.label??V.parallel.label,...V.sessionFiles?.[o]?{sessionFile:V.sessionFiles[o]}:{},...L?{...A?{model:A}:{},...I?{thinking:I}:{},...V.parallel.modelCandidates?{modelCandidates:V.parallel.modelCandidates.map((G$)=>W1(G$,L,!0))}:{}}:{},structuredOutput:void 0,structuredOutputSchema:V.parallel.structuredOutputSchema??V.parallel.structuredOutput?.schema}}),N=Math.max(Y.steps.length-1+z.length,1),w=z.map((M,o)=>{let L=fj({artifactsDir:B,artifactConfig:q,runId:j,agent:M.agent,flatIndex:K+o,flatStepCount:N});return{agent:M.agent,phase:M.phase??V.phase,label:M.label,outputName:void 0,structured:Boolean(M.structuredOutputSchema),status:"pending",...M.sessionFile?{sessionFile:M.sessionFile}:{},...L?{transcriptPath:L}:{},skills:M.skills,model:M.model,thinking:M.thinking,attemptedModels:M.modelCandidates&&M.modelCandidates.length>0?M.modelCandidates:M.model?[M.model]:void 0,recentTools:[],recentOutput:[]}});if(Y.steps.splice(K,1,...w),$.childIntercomTargets)$.childIntercomTargets=Y.steps.map((M,o)=>Aj(j,M.agent,o));p0.splice(K,1,...w.map(()=>G1())),T0.splice(K,1,...w.map(()=>{return}));let d=w.length-1;for(let M of Y.parallelGroups)if(M.stepIndex===H)M.start=K,M.count=w.length;else if(M.start>K)M.start+=d;if(Y.workflowGraph){let M=(L)=>{for(let A of L){if(A.stepIndex!==void 0&&A.stepIndex>H&&A.flatIndex!==void 0&&A.flatIndex>=K)A.flatIndex+=w.length;if(A.children)M(A.children)}};M(Y.workflowGraph.nodes);let o=Y.workflowGraph.nodes.find((L)=>L.id===`step-${H}`);if(o)o.children=_.items.map((L,A)=>({id:`step-${H}-item-${L.idKey}`,kind:"agent",agent:V.parallel.agent,phase:z[A]?.phase??V.phase,label:z[A]?.label?.trim()||`${V.parallel.agent} ${L.key}`,status:"pending",flatIndex:K+A,stepIndex:H,itemKey:L.key,structured:Boolean(z[A]?.structuredOutputSchema)}))}a();let Z$=V.concurrency??k1,v=V.failFast??!1,F=!1,F$=await t0(z,Z$,async(M,o)=>{let L=K+o;if(E)return P(M.agent);if(s)return e$(M.agent);if(F&&v){let g=Date.now();return Y.steps[L].status="failed",Y.steps[L].error="Skipped due to fail-fast",Y.steps[L].startedAt=g,Y.steps[L].endedAt=g,Y.steps[L].durationMs=0,Y.steps[L].exitCode=-1,Y.lastUpdate=g,a(),{agent:M.agent,output:"(skipped — fail-fast)",exitCode:-1,skipped:!0}}let A=Date.now();Y.currentStep=L,Y.steps[L].status="running",Y.steps[L].error=void 0,Y.steps[L].activityState=void 0,yj(Y.steps[L]),Y.steps[L].startedAt=A,Y.steps[L].lastActivityAt=A,Y.outputFile=r.join(k,`output-${L}.log`),Y.lastActivityAt=A,Y.lastUpdate=A,a(),$$(n,JSON.stringify({type:"subagent.step.started",ts:A,runId:j,stepIndex:L,agent:M.agent})),C1(L);let I=await kj(M,{previousOutput:T,placeholder:X,cwd:Q,sessionEnabled:W0,outputs:y,sessionDir:$.sessionDir?r.join($.sessionDir,`dynamic-${H}-${o}`):void 0,artifactsDir:B,artifactConfig:q,id:j,flatIndex:L,flatStepCount:Math.max(Y.steps.length,1),outputFile:r.join(k,`output-${L}.log`),steerInboxDir:y0(k,L),piPackageRoot:$.piPackageRoot,piArgv1:$.piArgv1,childIntercomTarget:$.childIntercomTargets?.[L],orchestratorIntercomTarget:$.controlIntercomTarget,nestedRoute:$.nestedRoute,registerInterrupt:(g)=>N$(L,g),registerTimeout:(g)=>f$(L,g),registerTurnBudgetAbort:(g)=>D$(L,g),timeoutSignal:q$.signal,timeoutMessage:p,turnBudget:$.turnBudget,onAttemptStart:(g)=>T1(L,g.model,g.thinking),onChildEvent:(g)=>E1(L,g),skipAcceptance:()=>E}),G$=Date.now(),x$=I.interrupted===!0;if(Y.steps[L].status=E?"failed":x$?"paused":I.exitCode===0?"complete":"failed",Y.steps[L].endedAt=G$,Y.steps[L].durationMs=G$-A,Y.steps[L].exitCode=E?1:x$?0:I.exitCode,Y.steps[L].timedOut=E||I.timedOut?!0:void 0,Y.steps[L].turnBudget=I.turnBudget,Y.steps[L].turnBudgetExceeded=I.turnBudgetExceeded,Y.steps[L].wrapUpRequested=I.wrapUpRequested,Y.steps[L].toolBudget=I.toolBudget,Y.steps[L].toolBudgetBlocked=I.toolBudgetBlocked,I.toolBudget)Y.toolBudget=I.toolBudget;if(I.toolBudgetBlocked)Y.toolBudgetBlocked=!0;if(I.turnBudget)Y.turnBudget=I.turnBudget;if(I.turnBudgetExceeded)Y.turnBudgetExceeded=!0;if(I.wrapUpRequested)Y.wrapUpRequested=!0;if(Y.steps[L].model=I.model,Y.steps[L].thinking=O0(I.model,Y.steps[L].thinking),Y.steps[L].attemptedModels=I.attemptedModels,Y.steps[L].modelAttempts=I.modelAttempts,Y.steps[L].totalCost=I.totalCost,Y.steps[L].error=E?p??"Subagent timed out.":I.error,Y.steps[L].transcriptPath=I.transcriptPath??Y.steps[L].transcriptPath,Y.steps[L].transcriptError=I.transcriptError,Y.steps[L].structuredOutput=I.structuredOutput,Y.steps[L].structuredOutputPath=I.structuredOutputPath,Y.steps[L].structuredOutputSchemaPath=I.structuredOutputSchemaPath,Y.steps[L].acceptance=I.acceptance,Y.lastUpdate=G$,a(),$$(n,JSON.stringify({type:E?"subagent.step.failed":x$?"subagent.step.paused":I.exitCode===0?"subagent.step.completed":"subagent.step.failed",ts:G$,runId:j,stepIndex:L,agent:M.agent,exitCode:E?1:x$?0:I.exitCode,durationMs:G$-A})),I.exitCode!==0&&v)F=!0;return E?{...I,output:p??"Subagent timed out.",error:p??"Subagent timed out.",exitCode:1,interrupted:!1,timedOut:!0,skipped:!1}:{...I,skipped:!1}},O);R+=z.length;for(let M of F$)h.push({agent:M.agent,output:M.output,error:M.error,success:M.interrupted!==!0&&M.exitCode===0,exitCode:M.interrupted===!0?0:M.exitCode,skipped:M.skipped,interrupted:M.interrupted,timedOut:M.timedOut,turnBudget:M.turnBudget,turnBudgetExceeded:M.turnBudgetExceeded,wrapUpRequested:M.wrapUpRequested,toolBudget:M.toolBudget,toolBudgetBlocked:M.toolBudgetBlocked,sessionFile:M.sessionFile,intercomTarget:M.intercomTarget,model:M.model,attemptedModels:M.attemptedModels,modelAttempts:M.modelAttempts,totalCost:M.totalCost,artifactPaths:M.artifactPaths,transcriptPath:M.transcriptPath,transcriptError:M.transcriptError,structuredOutput:M.structuredOutput,structuredOutputPath:M.structuredOutputPath,structuredOutputSchemaPath:M.structuredOutputSchemaPath,acceptance:M.acceptance});let C=aJ(V,_.items,F$),z$=F$.filter((M)=>M.exitCode!==0&&M.exitCode!==-1);if(z$.length===0)try{Yj(V.collect.outputSchema,C),y[V.collect.as]={text:JSON.stringify(C),structured:C,agent:V.parallel.agent,stepIndex:H},Y.outputs=y;let M=V.effectiveAcceptance&&!E?await M1({acceptance:V.effectiveAcceptance,output:"",report:Ej({results:F$,notes:`Dynamic fanout collected ${C.length} result(s) into ${V.collect.as}.`}),cwd:Q,signal:q$.signal,abortMessage:p??"Subagent timed out."}):void 0,o=E||q$.signal.aborted,L=o?void 0:M,A=L?L1(L):void 0,I=o?p??"Subagent timed out.":A;if(i(H,I?"failed":"completed",I,L),I)h.push({agent:V.parallel.agent,output:I,error:I,success:!1,exitCode:1,timedOut:o?!0:void 0,structuredOutput:C,acceptance:L}),Y.error=I}catch(M){let o=M instanceof x?M.message:M instanceof Error?M.message:String(M);h.push({agent:V.parallel.agent,output:o,error:o,success:!1,exitCode:1,structuredOutput:C}),Y.error=o,i(H,"failed",o)}if(T=e0(F$.map((M,o)=>({agent:M.agent,taskIndex:o,output:M.output,exitCode:M.exitCode,error:M.error})),(M,o)=>`=== Dynamic Item ${M+1} (${o}, key ${_.items[M]?.key??M}) ===`),$$(n,JSON.stringify({type:"subagent.dynamic.completed",ts:Date.now(),runId:j,stepIndex:H,success:z$.length===0})),z$.length>0)i(H,"failed",z$[0]?.error??"Dynamic fanout child failed.");if(Y.lastUpdate=Date.now(),a(),z$.length>0||Y.error)break;continue}if($0(V)){let K=V,_=K.concurrency??k1,z=K.failFast??!1,N=R,w=!1,d;if(K.worktree){let Z$=O8(K.parallel,Q);if(Z$){let v=Date.now();p8({statusPayload:Y,results:h,group:K,groupStartFlatIndex:N,setupError:A8(Z$,Q),failedAt:v,statusPath:f,eventsPath:n,asyncDir:k,runId:j,stepIndex:H}),R+=K.parallel.length;break}try{d=C8(Q,`${j}-s${H}`,K.parallel.length,{agents:K.parallel.map((v)=>v.agent),setupHook:$.worktreeSetupHook?{hookPath:$.worktreeSetupHook,timeoutMs:$.worktreeSetupHookTimeoutMs}:void 0,baseDir:$.worktreeBaseDir})}catch(v){let F=v instanceof Error?v.message:String(v),F$=Date.now();p8({statusPayload:Y,results:h,group:K,groupStartFlatIndex:N,setupError:F,failedAt:F$,statusPath:f,eventsPath:n,asyncDir:k,runId:j,stepIndex:H}),R+=K.parallel.length;break}}try{if(K.worktree)i5(Q,K);let Z$=Date.now();l5({statusPayload:Y,group:K,groupStartFlatIndex:N,groupStartTime:Z$,statusPath:f,eventsPath:n,asyncDir:k,runId:j,stepIndex:H});let v=await t0(K.parallel,_,async(F,F$)=>{let C=N+F$;if(E)return P(F.agent);if(s)return e$(F.agent);if(w&&z){let g=Date.now();return Y.steps[C].status="failed",Y.steps[C].error="Skipped due to fail-fast",Y.steps[C].startedAt=g,Y.steps[C].endedAt=g,Y.steps[C].durationMs=0,Y.steps[C].exitCode=-1,Y.steps[C].activityState=void 0,Y.lastUpdate=g,a(),$$(n,JSON.stringify({type:"subagent.step.failed",ts:g,runId:j,stepIndex:C,agent:F.agent,exitCode:-1,durationMs:0})),{agent:F.agent,output:"(skipped — fail-fast)",exitCode:-1,skipped:!0}}let z$=Date.now();Y.currentStep=C,Y.steps[C].status="running",Y.steps[C].error=void 0,Y.steps[C].activityState=void 0,yj(Y.steps[C]),Y.steps[C].startedAt=z$,Y.steps[C].endedAt=void 0,Y.steps[C].durationMs=void 0,Y.steps[C].lastActivityAt=z$,Y.outputFile=r.join(k,`output-${C}.log`),Y.lastActivityAt=z$,Y.lastUpdate=z$,a(),$$(n,JSON.stringify({type:"subagent.step.started",ts:z$,runId:j,stepIndex:C,agent:F.agent}));let M=$.sessionDir?r.join($.sessionDir,`parallel-${F$}`):void 0,{taskForRun:o,taskCwd:L}=p5(F,Q,d,F$);C1(C);let A=await kj(o,{previousOutput:T,placeholder:X,cwd:L,sessionEnabled:W0,outputs:y,sessionDir:M,artifactsDir:B,artifactConfig:q,id:j,flatIndex:C,flatStepCount:Math.max(Y.steps.length,1),outputFile:r.join(k,`output-${C}.log`),steerInboxDir:y0(k,C),piPackageRoot:$.piPackageRoot,piArgv1:$.piArgv1,childIntercomTarget:$.childIntercomTargets?.[C],orchestratorIntercomTarget:$.controlIntercomTarget,nestedRoute:$.nestedRoute,registerInterrupt:(g)=>N$(C,g),registerTimeout:(g)=>f$(C,g),registerTurnBudgetAbort:(g)=>D$(C,g),timeoutSignal:q$.signal,timeoutMessage:p,turnBudget:$.turnBudget,onAttemptStart:(g)=>T1(C,g.model,g.thinking),onChildEvent:(g)=>E1(C,g),skipAcceptance:()=>E});if(F.sessionFile)o$=F.sessionFile;let I=Date.now(),G$=I-z$,x$=A.interrupted===!0;if(Y.steps[C].status=E?"failed":x$?"paused":A.exitCode===0?"complete":"failed",Y.steps[C].endedAt=I,Y.steps[C].durationMs=G$,Y.steps[C].exitCode=E?1:x$?0:A.exitCode,Y.steps[C].timedOut=E||A.timedOut?!0:void 0,Y.steps[C].turnBudget=A.turnBudget,Y.steps[C].turnBudgetExceeded=A.turnBudgetExceeded,Y.steps[C].wrapUpRequested=A.wrapUpRequested,Y.steps[C].toolBudget=A.toolBudget,Y.steps[C].toolBudgetBlocked=A.toolBudgetBlocked,A.toolBudget)Y.toolBudget=A.toolBudget;if(A.toolBudgetBlocked)Y.toolBudgetBlocked=!0;if(A.turnBudget)Y.turnBudget=A.turnBudget;if(A.turnBudgetExceeded)Y.turnBudgetExceeded=!0;if(A.wrapUpRequested)Y.wrapUpRequested=!0;if(Y.steps[C].model=A.model,Y.steps[C].thinking=O0(A.model,Y.steps[C].thinking),Y.steps[C].attemptedModels=A.attemptedModels,Y.steps[C].modelAttempts=A.modelAttempts,Y.steps[C].totalCost=A.totalCost,Y.steps[C].error=E?p??"Subagent timed out.":A.error,Y.steps[C].transcriptPath=A.transcriptPath??Y.steps[C].transcriptPath,Y.steps[C].transcriptError=A.transcriptError,Y.steps[C].structuredOutput=A.structuredOutput,Y.steps[C].structuredOutputPath=A.structuredOutputPath,Y.steps[C].structuredOutputSchemaPath=A.structuredOutputSchemaPath,Y.steps[C].acceptance=A.acceptance,Y.lastUpdate=I,a(),$$(n,JSON.stringify({type:E?"subagent.step.failed":x$?"subagent.step.paused":A.exitCode===0?"subagent.step.completed":"subagent.step.failed",ts:I,runId:j,stepIndex:C,agent:F.agent,exitCode:E?1:x$?0:A.exitCode,durationMs:G$})),A.completionGuardTriggered){let g=A0({from:Y.steps[C].activityState,to:"needs_attention",runId:j,agent:F.agent,index:C,ts:I,message:`${F.agent} completed without making edits for an implementation task`,reason:"completion_guard"});E0(g)}if(A.exitCode!==0&&z)w=!0;return E?{...A,output:p??"Subagent timed out.",error:p??"Subagent timed out.",exitCode:1,interrupted:!1,timedOut:!0,skipped:!1}:{...A,skipped:!1}},O);R+=K.parallel.length;for(let F=0;F<K.parallel.length;F++){let F$=N+F,z$=($.sessionDir?Fj(r.join($.sessionDir,`parallel-${F}`)):null)??u8(v[F]?.modelAttempts);if(!z$)continue;Y.steps[F$].tokens=z$,Y$={input:Y$.input+z$.input,output:Y$.output+z$.output,total:Y$.total+z$.total}}Y.totalTokens={...Y$},Y.lastUpdate=Date.now(),a();for(let F of v)h.push({agent:F.agent,output:F.output,error:F.error,success:F.interrupted!==!0&&F.exitCode===0,exitCode:F.interrupted===!0?0:F.exitCode,skipped:F.skipped,interrupted:F.interrupted,timedOut:F.timedOut,turnBudget:F.turnBudget,turnBudgetExceeded:F.turnBudgetExceeded,wrapUpRequested:F.wrapUpRequested,toolBudget:F.toolBudget,toolBudgetBlocked:F.toolBudgetBlocked,sessionFile:F.sessionFile,intercomTarget:F.intercomTarget,model:F.model,attemptedModels:F.attemptedModels,modelAttempts:F.modelAttempts,totalCost:F.totalCost,artifactPaths:F.artifactPaths,transcriptPath:F.transcriptPath,transcriptError:F.transcriptError,structuredOutput:F.structuredOutput,structuredOutputPath:F.structuredOutputPath,structuredOutputSchemaPath:F.structuredOutputSchemaPath,acceptance:F.acceptance});for(let F=0;F<K.parallel.length;F++){let F$=K.parallel[F]?.outputName;if(F$)y[F$]=Hj({agent:v[F].agent,output:v[F].output,structuredOutput:v[F].structuredOutput},H)}if(Y.outputs=y,T=e0(v.map((F)=>({agent:F.agent,output:F.output,exitCode:F.exitCode,error:F.error,model:F.model,attemptedModels:F.attemptedModels}))),T=n5(T,d,k,H,K),$$(n,JSON.stringify({type:"subagent.parallel.completed",ts:Date.now(),runId:j,stepIndex:H,success:v.every((F)=>F.exitCode===0||F.exitCode===-1)})),v.some((F)=>F.exitCode!==0&&F.exitCode!==-1))break}finally{if(d)Oj(d)}}else{let K=V,_=Date.now();Y.currentStep=R,Y.steps[R].status="running",Y.steps[R].activityState=void 0,Y.activityState=void 0,yj(Y.steps[R]),Y.steps[R].skills=K.skills,Y.steps[R].startedAt=_,Y.steps[R].lastActivityAt=_,Y.lastActivityAt=_,Y.lastUpdate=_,Y.outputFile=r.join(k,`output-${R}.log`),a(),$$(n,JSON.stringify({type:"subagent.step.started",ts:_,runId:j,stepIndex:R,agent:K.agent})),C1(R);let z=await kj(K,{previousOutput:T,placeholder:X,cwd:Q,sessionEnabled:W0,outputs:y,sessionDir:$.sessionDir,artifactsDir:B,artifactConfig:q,id:j,flatIndex:R,flatStepCount:Math.max(Y.steps.length,1),outputFile:r.join(k,`output-${R}.log`),steerInboxDir:y0(k,R),piPackageRoot:$.piPackageRoot,piArgv1:$.piArgv1,childIntercomTarget:$.childIntercomTargets?.[R],orchestratorIntercomTarget:$.controlIntercomTarget,nestedRoute:$.nestedRoute,registerInterrupt:(v)=>N$(R,v),registerTimeout:(v)=>f$(R,v),registerTurnBudgetAbort:(v)=>D$(R,v),timeoutSignal:q$.signal,timeoutMessage:p,turnBudget:$.turnBudget,onAttemptStart:(v)=>T1(R,v.model,v.thinking),onChildEvent:(v)=>E1(R,v),skipAcceptance:()=>E});if(K.sessionFile)o$=K.sessionFile;if(T=z.output,h.push({agent:z.agent,output:E?p??"Subagent timed out.":z.output,error:E?p??"Subagent timed out.":z.error,success:!E&&z.interrupted!==!0&&z.exitCode===0,exitCode:E?1:z.interrupted===!0?0:z.exitCode,sessionFile:z.sessionFile,intercomTarget:z.intercomTarget,model:z.model,attemptedModels:z.attemptedModels,modelAttempts:z.modelAttempts,totalCost:z.totalCost,artifactPaths:z.artifactPaths,transcriptPath:z.transcriptPath,transcriptError:z.transcriptError,structuredOutput:z.structuredOutput,structuredOutputPath:z.structuredOutputPath,structuredOutputSchemaPath:z.structuredOutputSchemaPath,acceptance:z.acceptance,interrupted:z.interrupted,timedOut:E||z.timedOut?!0:void 0,turnBudget:z.turnBudget,turnBudgetExceeded:z.turnBudgetExceeded,wrapUpRequested:z.wrapUpRequested,toolBudget:z.toolBudget,toolBudgetBlocked:z.toolBudgetBlocked}),K.outputName)y[K.outputName]=Hj({agent:z.agent,output:z.output,structuredOutput:z.structuredOutput},H);Y.outputs=y;let N=$.sessionDir?Fj($.sessionDir):null,w=N?{input:N.input-Y$.input,output:N.output-Y$.output,total:N.total-Y$.total}:null;if(N)Y$=N;else if(w=u8(z.modelAttempts),w)Y$={input:Y$.input+w.input,output:Y$.output+w.output,total:Y$.total+w.total};let d=Date.now(),Z$=z.interrupted===!0;if(Y.steps[R].status=E?"failed":Z$?"paused":z.exitCode===0?"complete":"failed",Y.steps[R].endedAt=d,Y.steps[R].durationMs=d-_,Y.steps[R].exitCode=E?1:Z$?0:z.exitCode,Y.steps[R].timedOut=E||z.timedOut?!0:void 0,Y.steps[R].turnBudget=z.turnBudget,Y.steps[R].turnBudgetExceeded=z.turnBudgetExceeded,Y.steps[R].wrapUpRequested=z.wrapUpRequested,Y.steps[R].toolBudget=z.toolBudget,Y.steps[R].toolBudgetBlocked=z.toolBudgetBlocked,z.toolBudget)Y.toolBudget=z.toolBudget;if(z.toolBudgetBlocked)Y.toolBudgetBlocked=!0;if(z.turnBudget)Y.turnBudget=z.turnBudget;if(z.turnBudgetExceeded)Y.turnBudgetExceeded=!0;if(z.wrapUpRequested)Y.wrapUpRequested=!0;if(Y.steps[R].model=z.model,Y.steps[R].thinking=O0(z.model,Y.steps[R].thinking),Y.steps[R].attemptedModels=z.attemptedModels,Y.steps[R].modelAttempts=z.modelAttempts,Y.steps[R].totalCost=z.totalCost,Y.steps[R].error=E?p??"Subagent timed out.":z.error,Y.steps[R].transcriptPath=z.transcriptPath??Y.steps[R].transcriptPath,Y.steps[R].transcriptError=z.transcriptError,Y.steps[R].structuredOutput=z.structuredOutput,Y.steps[R].structuredOutputPath=z.structuredOutputPath,Y.steps[R].structuredOutputSchemaPath=z.structuredOutputSchemaPath,Y.steps[R].acceptance=z.acceptance,w)Y.steps[R].tokens=w,Y.totalTokens={...Y$};if(Y.lastUpdate=d,a(),$$(n,JSON.stringify({type:E?"subagent.step.failed":Z$?"subagent.step.paused":z.exitCode===0?"subagent.step.completed":"subagent.step.failed",ts:d,runId:j,stepIndex:R,agent:K.agent,exitCode:E?1:Z$?0:z.exitCode,durationMs:d-_,tokens:w})),z.completionGuardTriggered){let v=A0({from:Y.steps[R].activityState,to:"needs_attention",runId:j,agent:K.agent,index:R,ts:d,message:`${K.agent} completed without making edits for an implementation task`,reason:"completion_guard"});E0(v)}if(R++,z.exitCode!==0)break}}let n0=h.map((H)=>`${H.agent}:
76
76
  ${H.output}`).join(`
77
77
 
78
- `),S1=!1;if(G){let H={...nj,...G},U=h[h.length-1]?.artifactPaths?.outputPath,V=sj(n0,H,U);if(V.truncated)n0=V.text,S1=!0}let oj=$.resultMode??Y.mode,i0=h.reduce((H,U)=>({inputTokens:H.inputTokens+(U.totalCost?.inputTokens??0),outputTokens:H.outputTokens+(U.totalCost?.outputTokens??0),costUsd:H.costUsd+(U.totalCost?.costUsd??0)}),{inputTokens:0,outputTokens:0,costUsd:0}),D1=i0.inputTokens>0||i0.outputTokens>0||i0.costUsd>0?i0:void 0,r0=Y.steps.map((H)=>H.agent),t8=r0.length===1?r0[0]:oj==="parallel"?`parallel:${r0.join("+")}`:`chain:${r0.join("->")}`,H0,s0,b1,M0;if(v$){if(H0=$.sessionDir?x5($.sessionDir)??void 0:void 0,!H0&&o$)H0=o$;if(H0)try{let H=$.sessionDir??r.dirname(H0),U=await c5(H0,H,$.piPackageRoot),V=d5(U);if("error"in V)M0=V.error;else s0=V.shareUrl,b1=V.gistUrl}catch(H){M0=String(H)}else M0="Session file not found."}if(X$)clearInterval(X$),X$=void 0;if(B$)clearTimeout(B$),B$=void 0;a8();let R1=H0??o$,U0=Date.now();if(Y.state=E||t?"failed":s?"paused":h.every((H)=>H.success)?"complete":"failed",Y.activityState=void 0,E)Y.timedOut=!0,Y.error=p??"Subagent timed out.";if(t&&!Y.error){let H=Y.turnBudget;Y.error=H?u0(H,H.turnCount):"Subagent exceeded turn budget."}if(Y.endedAt=U0,Y.lastUpdate=U0,Y.sessionFile=R1,Y.totalCost=D1,Y.shareUrl=s0,Y.gistUrl=b1,Y.shareError=M0,Y.state==="failed"&&!Y.error){let H=Y.steps.find((U)=>U.status==="failed");if(H?.agent)Y.error=`Step failed: ${H.agent}`}a(),$$(n,JSON.stringify({type:"subagent.run.completed",lifecycleArtifactVersion:S0,ts:U0,runId:j,status:Y.state,durationMs:U0-S,totalTokens:Y.totalTokens,totalCost:D1})),o5(d$,{id:j,mode:Y.mode,cwd:Q,startedAt:S,endedAt:U0,steps:Y.steps.map((H)=>({agent:H.agent,status:H.status,durationMs:H.durationMs})),summary:n0,truncated:S1,artifactsDir:B,sessionFile:R1,shareUrl:s0,shareError:M0});try{D$(Z,{lifecycleArtifactVersion:S0,id:j,agent:t8,mode:oj,success:!E&&!t&&!s&&h.every((H)=>H.success),state:E||t?"failed":s?"paused":h.every((H)=>H.success)?"complete":"failed",summary:E?p??"Subagent timed out.":t?Y.error??"Subagent exceeded turn budget.":s?"Paused after interrupt. Waiting for explicit next action.":n0,...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},...$.deadlineAt!==void 0?{deadlineAt:$.deadlineAt}:{},...Y.turnBudget?{turnBudget:Y.turnBudget}:{},...Y.turnBudgetExceeded?{turnBudgetExceeded:!0}:{},...Y.wrapUpRequested?{wrapUpRequested:!0}:{},...Y.toolBudget?{toolBudget:Y.toolBudget}:{},...Y.toolBudgetBlocked?{toolBudgetBlocked:!0}:{},...E?{timedOut:!0,error:p??"Subagent timed out."}:t?{error:Y.error??"Subagent exceeded turn budget."}:{},results:h.map((H)=>({agent:H.agent,output:H.output,error:H.error,success:H.success,skipped:H.skipped||void 0,interrupted:H.interrupted||void 0,timedOut:H.timedOut||void 0,turnBudget:H.turnBudget,turnBudgetExceeded:H.turnBudgetExceeded||void 0,wrapUpRequested:H.wrapUpRequested||void 0,toolBudget:H.toolBudget,toolBudgetBlocked:H.toolBudgetBlocked||void 0,sessionFile:H.sessionFile,intercomTarget:H.intercomTarget,model:H.model,attemptedModels:H.attemptedModels,modelAttempts:H.modelAttempts,totalCost:H.totalCost,artifactPaths:H.artifactPaths,truncated:H.truncated,transcriptPath:H.transcriptPath,transcriptError:H.transcriptError,structuredOutput:H.structuredOutput,structuredOutputPath:H.structuredOutputPath,structuredOutputSchemaPath:H.structuredOutputSchemaPath,acceptance:H.acceptance})),outputs:y,workflowGraph:Y.workflowGraph,exitCode:E||t?1:s||h.every((H)=>H.success)?0:1,timestamp:U0,durationMs:U0-S,totalTokens:Y.totalTokens,totalCost:D1,truncated:S1,artifactsDir:B,cwd:Q,asyncDir:k,sessionId:$.sessionId,sessionFile:R1,intercomTarget:$.controlIntercomTarget,shareUrl:s0,gistUrl:b1,shareError:M0,...W!==void 0&&{taskIndex:W},...K!==void 0&&{totalTasks:K}})}catch(H){console.error(`Failed to write result file ${Z}:`,H)}}var Pj=process.argv[2];if(Pj)try{let $=e.readFileSync(Pj,"utf-8"),j=JSON.parse($);try{e.unlinkSync(Pj)}catch{}n8(j).catch((J)=>{console.error("Subagent runner error:",J),process.exit(1)})}catch($){console.error("Subagent runner error:",$),process.exit(1)}else{let $="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",(j)=>{$+=j}),process.stdin.on("end",()=>{try{let j=JSON.parse($);n8(j).catch((J)=>{console.error("Subagent runner error:",J),process.exit(1)})}catch(j){console.error("Subagent runner error:",j),process.exit(1)}})}
78
+ `),S1=!1;if(G){let H={...nj,...G},V=h[h.length-1]?.artifactPaths?.outputPath,K=sj(n0,H,V);if(K.truncated)n0=K.text,S1=!0}let oj=$.resultMode??Y.mode,i0=h.reduce((H,V)=>({inputTokens:H.inputTokens+(V.totalCost?.inputTokens??0),outputTokens:H.outputTokens+(V.totalCost?.outputTokens??0),costUsd:H.costUsd+(V.totalCost?.costUsd??0)}),{inputTokens:0,outputTokens:0,costUsd:0}),D1=i0.inputTokens>0||i0.outputTokens>0||i0.costUsd>0?i0:void 0,r0=Y.steps.map((H)=>H.agent),t8=r0.length===1?r0[0]:oj==="parallel"?`parallel:${r0.join("+")}`:`chain:${r0.join("->")}`,H0,s0,b1,M0;if(v$){if(H0=$.sessionDir?h5($.sessionDir)??void 0:void 0,!H0&&o$)H0=o$;if(H0)try{let H=$.sessionDir??r.dirname(H0),V=await d5(H0,H,$.piPackageRoot),K=o5(V);if("error"in K)M0=K.error;else s0=K.shareUrl,b1=K.gistUrl}catch(H){M0=String(H)}else M0="Session file not found."}if(X$)clearInterval(X$),X$=void 0;if(_$)clearTimeout(_$),_$=void 0;a8();let R1=H0??o$,V0=Date.now();if(Y.state=E||t?"failed":s?"paused":h.every((H)=>H.success)?"complete":"failed",Y.activityState=void 0,E)Y.timedOut=!0,Y.error=p??"Subagent timed out.";if(t&&!Y.error){let H=Y.turnBudget;Y.error=H?u0(H,H.turnCount):"Subagent exceeded turn budget."}if(Y.endedAt=V0,Y.lastUpdate=V0,Y.sessionFile=R1,Y.totalCost=D1,Y.shareUrl=s0,Y.gistUrl=b1,Y.shareError=M0,Y.state==="failed"&&!Y.error){let H=Y.steps.find((V)=>V.status==="failed");if(H?.agent)Y.error=`Step failed: ${H.agent}`}a(),$$(n,JSON.stringify({type:"subagent.run.completed",lifecycleArtifactVersion:S0,ts:V0,runId:j,status:Y.state,durationMs:V0-S,totalTokens:Y.totalTokens,totalCost:D1})),u5(d$,{id:j,mode:Y.mode,cwd:Q,startedAt:S,endedAt:V0,steps:Y.steps.map((H)=>({agent:H.agent,status:H.status,durationMs:H.durationMs})),summary:n0,truncated:S1,artifactsDir:B,sessionFile:R1,shareUrl:s0,shareError:M0});try{b$(Z,{lifecycleArtifactVersion:S0,id:j,agent:t8,mode:oj,success:!E&&!t&&!s&&h.every((H)=>H.success),state:E||t?"failed":s?"paused":h.every((H)=>H.success)?"complete":"failed",summary:E?p??"Subagent timed out.":t?Y.error??"Subagent exceeded turn budget.":s?"Paused after interrupt. Waiting for explicit next action.":n0,...$.timeoutMs!==void 0?{timeoutMs:$.timeoutMs}:{},...$.deadlineAt!==void 0?{deadlineAt:$.deadlineAt}:{},...Y.turnBudget?{turnBudget:Y.turnBudget}:{},...Y.turnBudgetExceeded?{turnBudgetExceeded:!0}:{},...Y.wrapUpRequested?{wrapUpRequested:!0}:{},...Y.toolBudget?{toolBudget:Y.toolBudget}:{},...Y.toolBudgetBlocked?{toolBudgetBlocked:!0}:{},...E?{timedOut:!0,error:p??"Subagent timed out."}:t?{error:Y.error??"Subagent exceeded turn budget."}:{},results:h.map((H)=>({agent:H.agent,output:H.output,error:H.error,success:H.success,skipped:H.skipped||void 0,interrupted:H.interrupted||void 0,timedOut:H.timedOut||void 0,turnBudget:H.turnBudget,turnBudgetExceeded:H.turnBudgetExceeded||void 0,wrapUpRequested:H.wrapUpRequested||void 0,toolBudget:H.toolBudget,toolBudgetBlocked:H.toolBudgetBlocked||void 0,sessionFile:H.sessionFile,intercomTarget:H.intercomTarget,model:H.model,attemptedModels:H.attemptedModels,modelAttempts:H.modelAttempts,totalCost:H.totalCost,artifactPaths:H.artifactPaths,truncated:H.truncated,transcriptPath:H.transcriptPath,transcriptError:H.transcriptError,structuredOutput:H.structuredOutput,structuredOutputPath:H.structuredOutputPath,structuredOutputSchemaPath:H.structuredOutputSchemaPath,acceptance:H.acceptance})),outputs:y,workflowGraph:Y.workflowGraph,exitCode:E||t?1:s||h.every((H)=>H.success)?0:1,timestamp:V0,durationMs:V0-S,totalTokens:Y.totalTokens,totalCost:D1,truncated:S1,artifactsDir:B,cwd:Q,asyncDir:k,sessionId:$.sessionId,sessionFile:R1,intercomTarget:$.controlIntercomTarget,shareUrl:s0,gistUrl:b1,shareError:M0,...W!==void 0&&{taskIndex:W},...U!==void 0&&{totalTasks:U}})}catch(H){console.error(`Failed to write result file ${Z}:`,H)}}var Pj=process.argv[2];if(Pj)try{let $=e.readFileSync(Pj,"utf-8"),j=JSON.parse($);try{e.unlinkSync(Pj)}catch{}n8(j).catch((J)=>{console.error("Subagent runner error:",J),process.exit(1)})}catch($){console.error("Subagent runner error:",$),process.exit(1)}else{let $="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",(j)=>{$+=j}),process.stdin.on("end",()=>{try{let j=JSON.parse($);n8(j).catch((J)=>{console.error("Subagent runner error:",J),process.exit(1)})}catch(j){console.error("Subagent runner error:",j),process.exit(1)}})}