@duckmind/dm-darwin-x64 0.48.5 → 0.49.6

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 (97) hide show
  1. package/dm +0 -0
  2. package/extensions/.dm-extensions.json +159 -220
  3. package/extensions/dm-9router-ext/package.json +0 -6
  4. package/extensions/dm-9router-ext/src/index.js +1 -1
  5. package/extensions/dm-ask-user/package.json +0 -4
  6. package/extensions/dm-caveman/extensions/caveman.js +29 -0
  7. package/extensions/dm-caveman/package.json +20 -0
  8. package/extensions/dm-cli-anything/index.js +5 -5
  9. package/extensions/dm-cli-anything/package.json +0 -7
  10. package/extensions/dm-cli-anything/skills/cli-anything/SKILL.md +1 -3
  11. package/extensions/dm-context/package.json +0 -1
  12. package/extensions/dm-cua/package.json +0 -7
  13. package/extensions/dm-fff/package.json +0 -6
  14. package/extensions/dm-goal/package.json +0 -8
  15. package/extensions/dm-grill-me/index.js +2 -2
  16. package/extensions/dm-grill-me/package.json +0 -7
  17. package/extensions/dm-image2/package.json +0 -8
  18. package/extensions/dm-subagents/.m/artifacts/shell/shell_output_1783845384621_9cf9262bf674.txt +1336 -0
  19. package/extensions/dm-subagents/.m/artifacts/shell/shell_output_1783846154938_6a41cefee0bf.txt +1336 -0
  20. package/extensions/dm-subagents/package.json +0 -11
  21. package/extensions/dm-subagents/src/extension/doctor.js +10 -10
  22. package/extensions/dm-subagents/src/extension/fanout-child.js +97 -97
  23. package/extensions/dm-subagents/src/extension/index.js +121 -121
  24. package/extensions/dm-subagents/src/extension/rpc.js +5 -5
  25. package/extensions/dm-subagents/src/extension/schemas.js +1 -1
  26. package/extensions/dm-subagents/src/extension/tool-description.js +2 -2
  27. package/extensions/dm-subagents/src/intercom/native-supervisor-channel.js +5 -5
  28. package/extensions/dm-subagents/src/runs/background/async-execution.js +19 -19
  29. package/extensions/dm-subagents/src/runs/background/async-job-tracker.js +9 -9
  30. package/extensions/dm-subagents/src/runs/background/async-resume.js +5 -5
  31. package/extensions/dm-subagents/src/runs/background/async-status.js +8 -8
  32. package/extensions/dm-subagents/src/runs/background/fleet-view.js +13 -13
  33. package/extensions/dm-subagents/src/runs/background/result-watcher.js +5 -5
  34. package/extensions/dm-subagents/src/runs/background/run-id-resolver.js +3 -3
  35. package/extensions/dm-subagents/src/runs/background/run-status.js +19 -19
  36. package/extensions/dm-subagents/src/runs/background/stale-run-reconciler.js +7 -7
  37. package/extensions/dm-subagents/src/runs/background/subagent-runner.js +35 -35
  38. package/extensions/dm-subagents/src/runs/background/wait.js +7 -7
  39. package/extensions/dm-subagents/src/runs/foreground/chain-execution.js +32 -32
  40. package/extensions/dm-subagents/src/runs/foreground/execution.js +26 -26
  41. package/extensions/dm-subagents/src/runs/foreground/subagent-executor.js +96 -96
  42. package/extensions/dm-subagents/src/runs/shared/dm-args.js +1 -1
  43. package/extensions/dm-subagents/src/runs/shared/nested-events.js +6 -6
  44. package/extensions/dm-subagents/src/runs/shared/subagent-prompt-runtime.js +13 -13
  45. package/extensions/dm-subagents/src/shared/fork-context.js +4 -4
  46. package/extensions/dm-tasks/package.json +0 -7
  47. package/extensions/dm-usage/package.json +0 -7
  48. package/extensions/greedysearch-dm/bin/cdp-greedy.mjs +1 -8
  49. package/extensions/greedysearch-dm/bin/gschrome.mjs +3 -3
  50. package/extensions/greedysearch-dm/bin/launch-visible.mjs +3 -3
  51. package/extensions/greedysearch-dm/bin/launch.mjs +4 -4
  52. package/extensions/greedysearch-dm/bin/search.mjs +103 -103
  53. package/extensions/greedysearch-dm/extractors/consensus.mjs +35 -35
  54. package/extensions/greedysearch-dm/extractors/gemini.mjs +38 -38
  55. package/extensions/greedysearch-dm/extractors/logically.mjs +35 -35
  56. package/extensions/greedysearch-dm/package.json +0 -10
  57. package/extensions/greedysearch-dm/src/search/chrome.mjs +23 -23
  58. package/extensions/greedysearch-dm/src/search/fetch-source.mjs +35 -35
  59. package/extensions/greedysearch-dm/src/search/research.mjs +61 -61
  60. package/extensions/greedysearch-dm/src/search/synthesis-runner.mjs +4 -4
  61. package/package.json +1 -1
  62. package/extensions/dm-9router-ext/README.md +0 -142
  63. package/extensions/dm-9router-ext/tsconfig.json +0 -17
  64. package/extensions/dm-ask-user/README.md +0 -226
  65. package/extensions/dm-cli-anything/LICENSE +0 -201
  66. package/extensions/dm-cli-anything/README.md +0 -33
  67. package/extensions/dm-cli-anything/vendor/UPSTREAM.md +0 -14
  68. package/extensions/dm-context/AGENTS.md +0 -41
  69. package/extensions/dm-context/README.md +0 -18
  70. package/extensions/dm-context/tsconfig.json +0 -16
  71. package/extensions/dm-cua/README.md +0 -24
  72. package/extensions/dm-fff/README.md +0 -36
  73. package/extensions/dm-fff/tsconfig.json +0 -13
  74. package/extensions/dm-goal/CHANGELOG.md +0 -12
  75. package/extensions/dm-goal/LICENSE +0 -21
  76. package/extensions/dm-goal/README.md +0 -29
  77. package/extensions/dm-goal/tsconfig.json +0 -15
  78. package/extensions/dm-grill-me/DESIGN.md +0 -301
  79. package/extensions/dm-grill-me/LICENSE +0 -21
  80. package/extensions/dm-grill-me/README.md +0 -82
  81. package/extensions/dm-grill-me/tsconfig.json +0 -17
  82. package/extensions/dm-image2/README.md +0 -33
  83. package/extensions/dm-subagents/CHANGELOG.md +0 -1211
  84. package/extensions/dm-subagents/README.md +0 -29
  85. package/extensions/dm-subagents/banner.png +0 -0
  86. package/extensions/dm-subagents/biome.json +0 -26
  87. package/extensions/dm-subagents/tsconfig.json +0 -18
  88. package/extensions/dm-tasks/LICENSE +0 -21
  89. package/extensions/dm-tasks/README.md +0 -30
  90. package/extensions/dm-tasks/biome.json +0 -26
  91. package/extensions/dm-tasks/tsconfig.json +0 -14
  92. package/extensions/dm-usage/LICENSE +0 -21
  93. package/extensions/dm-usage/README.md +0 -29
  94. package/extensions/dm-usage/insights-screenshot.png +0 -0
  95. package/extensions/dm-usage/screenshot.png +0 -0
  96. package/extensions/greedysearch-dm/LICENSE +0 -21
  97. package/extensions/greedysearch-dm/README.md +0 -222
@@ -1,8 +1,8 @@
1
- import*as O$ from"node:path";import{Compile as Y0}from"typebox/compile";import*as q from"node:fs";import*as z from"node:path";import*as E from"node:os";import*as y from"node:path";function m($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function N$($){let J=$?.env??process.env,Q=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof Q==="function")return`uid-${Q()}`;for(let K of["USERNAME","USER","LOGNAME"]){let Y=J[K];if(Y)return`user-${m(Y)}`}let Z=$&&Object.hasOwn($,"userInfo")?$.userInfo:E.userInfo;try{let K=Z?.().username;if(K)return`user-${m(K)}`}catch{}let X=J.USERPROFILE??J.HOME;if(X)return`home-${m(X)}`;let W=$&&Object.hasOwn($,"homedir")?$.homedir:E.homedir;try{let K=W?.();if(K)return`home-${m(K)}`}catch{}return"shared"}var _=y.join(E.tmpdir(),`dm-subagents-${N$()}`),S=y.join(_,"async-subagent-results"),h=y.join(_,"async-subagent-runs"),b$=y.join(_,"chain-runs"),C0=y.join(_,"artifacts");import*as F from"node:fs";import*as k from"node:path";var D=new Map;function o($){return $ instanceof Error?$.message:String($)}function j$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function J$($){let J=k.join($,"status.json"),Q;try{Q=F.statSync(J)}catch(K){if(j$(K))return null;throw Error(`Failed to inspect async status file '${J}': ${o(K)}`,{cause:K instanceof Error?K:void 0})}let Z=D.get(J);if(Z&&Z.mtime===Q.mtimeMs)return Z.status;let X;try{X=F.readFileSync(J,"utf-8")}catch(K){if(j$(K))return null;throw Error(`Failed to read async status file '${J}': ${o(K)}`,{cause:K instanceof Error?K:void 0})}let W;try{W=JSON.parse(X)}catch(K){throw Error(`Failed to parse async status file '${J}': ${o(K)}`,{cause:K instanceof Error?K:void 0})}if(D.set(J,{mtime:Q.mtimeMs,status:W}),D.size>50){let K=D.keys().next().value;if(K)D.delete(K)}return W}import*as u from"node:path";import*as y$ from"node:fs";import*as T from"node:path";var S$=[10,25,50,100,200,500,1000,2000,4000],x$=new Set(["EACCES","EBUSY","EPERM"]),Z$=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,Q$=Z$?new Int32Array(Z$):void 0;function D$($){if($<=0)return;if(Q$)try{Atomics.wait(Q$,0,0,$);return}catch{}let J=Date.now()+$;while(Date.now()<J);}function k$($){let J=$?.code;return typeof J==="string"&&x$.has(J)}function I$($,J,Q,Z,X){for(let W=0;;W++)try{$.renameSync(J,Q);return}catch(K){let Y=Z[W];if(Y===void 0||!k$(K))throw K;X(Y)}}function w$($={}){let J=$.fs??y$,Q=$.now??Date.now,Z=$.pid??process.pid,X=$.random??Math.random,K=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??S$:[],Y=$.wait??D$;return(H,B)=>{J.mkdirSync(T.dirname(H),{recursive:!0});let V=T.join(T.dirname(H),`.${T.basename(H)}.${Z}.${Q()}.${X().toString(36).slice(2)}.tmp`);try{J.writeFileSync(V,JSON.stringify(B,null,2),"utf-8"),I$(J,V,H,K,Y)}finally{J.rmSync(V,{force:!0})}}}var N=w$();var r0=process.platform==="win32"?"SIGBREAK":"SIGUSR2";function R$($){return u.join($,"control")}function P$($){return u.join(R$($),"timeout.json")}function v$($,J={},Q={}){let Z=P$($),X={...J,ts:J.ts??Q.now?.()??Date.now(),type:"timeout"};return N(Z,X),Z}function W$($){v$($.asyncDir,$.source?{source:$.source}:{},{now:$.now})}import*as L from"node:fs";import*as O from"node:path";function g$($,J,Q){if(typeof $!=="object"||$===null)return!1;let{start:Z,count:X,stepIndex:W}=$;return typeof Z==="number"&&typeof X==="number"&&typeof W==="number"&&Number.isInteger(Z)&&Number.isInteger(X)&&Number.isInteger(W)&&Z>=0&&X>0&&W>=0&&W<Q&&Z+X<=J}function X$($,J,Q){if(!Array.isArray($))return[];return $.filter((Z)=>g$(Z,J,Q)).sort((Z,X)=>Z.stepIndex-X.stepIndex||Z.start-X.start)}import*as b from"node:path";import*as x from"node:path";import{fileURLToPath as K$}from"node:url";import*as f from"node:os";import*as C from"node:path";var $j=C.join(f.homedir(),".config","mcp","mcp.json"),jj={cursor:[C.join(f.homedir(),".cursor","mcp.json")],"claude-code":[C.join(f.homedir(),".claude","mcp.json"),C.join(f.homedir(),".claude.json"),C.join(f.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[C.join(f.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[C.join(f.homedir(),".codex","config.json")],windsurf:[C.join(f.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as Qj}from"typebox/compile";var Cj=x.join(x.dirname(K$(import.meta.url)),"subagent-prompt-runtime.ts"),Aj=x.join(x.dirname(K$(import.meta.url)),"..","..","extension","fanout-child.ts");var Pj=b.join(_,"nested-subagent-events");function l($){return $ instanceof Error?$.message:String($)}function h$($){let J=O.join($,"runner.stderr.log"),Q=65536,Z;try{let W=L.statSync(J);if(W.size<=0)return;let K=L.openSync(J,"r");try{let Y=Math.min(W.size,65536),H=Math.max(0,W.size-Y),B=Buffer.alloc(Y);L.readSync(K,B,0,Y,H),Z=B.toString("utf-8").trim()}finally{L.closeSync(K)}}catch{return}if(!Z)return;let X=Z.split(/\r?\n/).slice(-30).join(`
1
+ import*as F$ from"node:path";import{Compile as B0}from"typebox/compile";import*as _ from"node:fs";import*as z from"node:path";import*as y from"node:os";import*as S from"node:path";function m($){return $.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function b$($){let J=$?.env??process.env,Q=$&&Object.hasOwn($,"getuid")?$.getuid:process.getuid?.bind(process);if(typeof Q==="function")return`uid-${Q()}`;for(let K of["USERNAME","USER","LOGNAME"]){let Y=J[K];if(Y)return`user-${m(Y)}`}let Z=$&&Object.hasOwn($,"userInfo")?$.userInfo:y.userInfo;try{let K=Z?.().username;if(K)return`user-${m(K)}`}catch{}let X=J.USERPROFILE??J.HOME;if(X)return`home-${m(X)}`;let W=$&&Object.hasOwn($,"homedir")?$.homedir:y.homedir;try{let K=W?.();if(K)return`home-${m(K)}`}catch{}return"shared"}var T=S.join(y.tmpdir(),`dm-subagents-${b$()}`),x=S.join(T,"async-subagent-results"),c=S.join(T,"async-subagent-runs"),E$=S.join(T,"chain-runs"),f0=S.join(T,"artifacts");import*as F from"node:fs";import*as I from"node:path";var k=new Map;function u($){return $ instanceof Error?$.message:String($)}function J$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function Z$($){let J=I.join($,"status.json"),Q;try{Q=F.statSync(J)}catch(K){if(J$(K))return null;throw Error(`Failed to inspect async status file '${J}': ${u(K)}`,{cause:K instanceof Error?K:void 0})}let Z=k.get(J);if(Z&&Z.mtime===Q.mtimeMs)return Z.status;let X;try{X=F.readFileSync(J,"utf-8")}catch(K){if(J$(K))return null;throw Error(`Failed to read async status file '${J}': ${u(K)}`,{cause:K instanceof Error?K:void 0})}let W;try{W=JSON.parse(X)}catch(K){throw Error(`Failed to parse async status file '${J}': ${u(K)}`,{cause:K instanceof Error?K:void 0})}if(k.set(J,{mtime:Q.mtimeMs,status:W}),k.size>50){let K=k.keys().next().value;if(K)k.delete(K)}return W}import*as l from"node:path";import*as S$ from"node:fs";import*as N from"node:path";var x$=[10,25,50,100,200,500,1000,2000,4000],D$=new Set(["EACCES","EBUSY","EPERM"]),Q$=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,W$=Q$?new Int32Array(Q$):void 0;function k$($){if($<=0)return;if(W$)try{Atomics.wait(W$,0,0,$);return}catch{}let J=Date.now()+$;while(Date.now()<J);}function I$($){let J=$?.code;return typeof J==="string"&&D$.has(J)}function w$($,J,Q,Z,X){for(let W=0;;W++)try{$.renameSync(J,Q);return}catch(K){let Y=Z[W];if(Y===void 0||!I$(K))throw K;X(Y)}}function R$($={}){let J=$.fs??S$,Q=$.now??Date.now,Z=$.pid??process.pid,X=$.random??Math.random,K=$.retryRenameErrors??process.platform==="win32"?$.retryDelaysMs??x$:[],Y=$.wait??k$;return(H,B)=>{J.mkdirSync(N.dirname(H),{recursive:!0});let V=N.join(N.dirname(H),`.${N.basename(H)}.${Z}.${Q()}.${X().toString(36).slice(2)}.tmp`);try{J.writeFileSync(V,JSON.stringify(B,null,2),"utf-8"),w$(J,V,H,K,Y)}finally{J.rmSync(V,{force:!0})}}}var b=R$();var a0=process.platform==="win32"?"SIGBREAK":"SIGUSR2";function P$($){return l.join($,"control")}function v$($){return l.join(P$($),"timeout.json")}function g$($,J={},Q={}){let Z=v$($),X={...J,ts:J.ts??Q.now?.()??Date.now(),type:"timeout"};return b(Z,X),Z}function X$($){g$($.asyncDir,$.source?{source:$.source}:{},{now:$.now})}import*as L from"node:fs";import*as O from"node:path";function h$($,J,Q){if(typeof $!=="object"||$===null)return!1;let{start:Z,count:X,stepIndex:W}=$;return typeof Z==="number"&&typeof X==="number"&&typeof W==="number"&&Number.isInteger(Z)&&Number.isInteger(X)&&Number.isInteger(W)&&Z>=0&&X>0&&W>=0&&W<Q&&Z+X<=J}function K$($,J,Q){if(!Array.isArray($))return[];return $.filter((Z)=>h$(Z,J,Q)).sort((Z,X)=>Z.stepIndex-X.stepIndex||Z.start-X.start)}import*as E from"node:path";import*as D from"node:fs";import*as A from"node:path";import{fileURLToPath as c$}from"node:url";import*as q from"node:os";import*as C from"node:path";var Jj=C.join(q.homedir(),".config","mcp","mcp.json"),Zj={cursor:[C.join(q.homedir(),".cursor","mcp.json")],"claude-code":[C.join(q.homedir(),".claude","mcp.json"),C.join(q.homedir(),".claude.json"),C.join(q.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[C.join(q.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[C.join(q.homedir(),".codex","config.json")],windsurf:[C.join(q.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as Xj}from"typebox/compile";function Y$($,J){let Q=c$($),Z=A.extname(Q),X=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(Z)?Z:".ts",W=A.dirname(Q);while(!D.existsSync(A.join(W,"package.json"))){let K=A.dirname(W);if(K===W)throw Error(`Unable to resolve dm-subagents package root from ${Q}`);W=K}return A.join(W,`${J}${X}`)}var fj=Y$(import.meta.url,A.join("src","runs","shared","subagent-prompt-runtime")),qj=Y$(import.meta.url,A.join("src","extension","fanout-child"));var gj=E.join(T,"nested-subagent-events");function i($){return $ instanceof Error?$.message:String($)}function d$($){let J=O.join($,"runner.stderr.log"),Q=65536,Z;try{let W=L.statSync(J);if(W.size<=0)return;let K=L.openSync(J,"r");try{let Y=Math.min(W.size,65536),H=Math.max(0,W.size-Y),B=Buffer.alloc(Y);L.readSync(K,B,0,Y,H),Z=B.toString("utf-8").trim()}finally{L.closeSync(K)}}catch{return}if(!Z)return;let X=Z.split(/\r?\n/).slice(-30).join(`
2
2
  `);return X.length>4000?`${X.slice(-4000)}
3
- [stderr tail truncated]`:X}function H$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function c$($,J){try{L.mkdirSync(O.dirname($),{recursive:!0}),L.appendFileSync($,`${JSON.stringify(J)}
4
- `,"utf-8")}catch{}}function d$($){let J=O.join($,"status.json"),Q;try{Q=L.readFileSync(J,"utf-8")}catch(Z){if(H$(Z))return null;throw Error(`Failed to read async status file '${J}': ${l(Z)}`,{cause:Z instanceof Error?Z:void 0})}try{return JSON.parse(Q)}catch(Z){throw Error(`Failed to parse async status file '${J}': ${l(Z)}`,{cause:Z instanceof Error?Z:void 0})}}function p$($){try{let J=JSON.parse(L.readFileSync($,"utf-8"));return{state:J.success?"complete":J.state==="paused"||J.exitCode===0?"paused":"failed",...Array.isArray(J.results)?{results:J.results}:{}}}catch(J){if(H$(J))return;throw Error(`Failed to read async result file '${$}': ${l(J)}`,{cause:J instanceof Error?J:void 0})}}function n$($,J){if(J?.success===!0)return"complete";if(J?.success===!1)return"failed";return $}function o$($,J,Q){let Z=p$(J);if(!Z)return;let X=($.steps??[]).map((W,K)=>{if(W.status!=="running"&&W.status!=="pending")return W;let Y=Z.results?.[K],H=n$(Z.state,Y);return{...W,status:H==="complete"?"complete":H,endedAt:W.endedAt??Q,durationMs:W.startedAt!==void 0&&W.durationMs===void 0?Math.max(0,Q-W.startedAt):W.durationMs,exitCode:W.exitCode??(H==="complete"||H==="paused"?0:1),error:H==="failed"?W.error??Y?.error:W.error,sessionFile:W.sessionFile??Y?.sessionFile,model:W.model??Y?.model,attemptedModels:W.attemptedModels??Y?.attemptedModels,modelAttempts:W.modelAttempts??Y?.modelAttempts}});return{...$,state:Z.state,activityState:void 0,lastUpdate:Q,endedAt:$.endedAt??Q,steps:X}}function u$($,J,Q){let Z=J.startedAt??Q,X=J.agents?.length?J.agents:["subagent"],W=J.chainStepCount,K=W!==void 0?X$(J.parallelGroups,X.length,W):[];return{runId:J.runId||O.basename($),...J.sessionId?{sessionId:J.sessionId}:{},mode:J.mode??"single",state:"running",pid:J.pid,startedAt:Z,lastUpdate:Q,currentStep:0,...W!==void 0?{chainStepCount:W}:{},...K.length?{parallelGroups:K}:{},steps:X.map((Y)=>({agent:Y,status:"running",startedAt:Z})),...J.sessionFile?{sessionFile:J.sessionFile}:{}}}function l$($,J,Q,Z){let X=$.runId||O.basename(J),W=typeof $.pid==="number"?$.pid:"unknown",K=Z??`Async runner process ${W} exited or disappeared before writing a result. Marked run failed by stale-run reconciliation.`,Y=h$(J),H=Y?`${K}
3
+ [stderr tail truncated]`:X}function B$($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function p$($,J){try{L.mkdirSync(O.dirname($),{recursive:!0}),L.appendFileSync($,`${JSON.stringify(J)}
4
+ `,"utf-8")}catch{}}function n$($){let J=O.join($,"status.json"),Q;try{Q=L.readFileSync(J,"utf-8")}catch(Z){if(B$(Z))return null;throw Error(`Failed to read async status file '${J}': ${i(Z)}`,{cause:Z instanceof Error?Z:void 0})}try{return JSON.parse(Q)}catch(Z){throw Error(`Failed to parse async status file '${J}': ${i(Z)}`,{cause:Z instanceof Error?Z:void 0})}}function o$($){try{let J=JSON.parse(L.readFileSync($,"utf-8"));return{state:J.success?"complete":J.state==="paused"||J.exitCode===0?"paused":"failed",...Array.isArray(J.results)?{results:J.results}:{}}}catch(J){if(B$(J))return;throw Error(`Failed to read async result file '${$}': ${i(J)}`,{cause:J instanceof Error?J:void 0})}}function u$($,J){if(J?.success===!0)return"complete";if(J?.success===!1)return"failed";return $}function l$($,J,Q){let Z=o$(J);if(!Z)return;let X=($.steps??[]).map((W,K)=>{if(W.status!=="running"&&W.status!=="pending")return W;let Y=Z.results?.[K],H=u$(Z.state,Y);return{...W,status:H==="complete"?"complete":H,endedAt:W.endedAt??Q,durationMs:W.startedAt!==void 0&&W.durationMs===void 0?Math.max(0,Q-W.startedAt):W.durationMs,exitCode:W.exitCode??(H==="complete"||H==="paused"?0:1),error:H==="failed"?W.error??Y?.error:W.error,sessionFile:W.sessionFile??Y?.sessionFile,model:W.model??Y?.model,attemptedModels:W.attemptedModels??Y?.attemptedModels,modelAttempts:W.modelAttempts??Y?.modelAttempts}});return{...$,state:Z.state,activityState:void 0,lastUpdate:Q,endedAt:$.endedAt??Q,steps:X}}function i$($,J,Q){let Z=J.startedAt??Q,X=J.agents?.length?J.agents:["subagent"],W=J.chainStepCount,K=W!==void 0?K$(J.parallelGroups,X.length,W):[];return{runId:J.runId||O.basename($),...J.sessionId?{sessionId:J.sessionId}:{},mode:J.mode??"single",state:"running",pid:J.pid,startedAt:Z,lastUpdate:Q,currentStep:0,...W!==void 0?{chainStepCount:W}:{},...K.length?{parallelGroups:K}:{},steps:X.map((Y)=>({agent:Y,status:"running",startedAt:Z})),...J.sessionFile?{sessionFile:J.sessionFile}:{}}}function r$($,J,Q,Z){let X=$.runId||O.basename(J),W=typeof $.pid==="number"?$.pid:"unknown",K=Z??`Async runner process ${W} exited or disappeared before writing a result. Marked run failed by stale-run reconciliation.`,Y=d$(J),H=Y?`${K}
5
5
 
6
6
  Runner stderr tail:
7
- ${Y}`:K,V=(($.steps?.length)?$.steps:[{agent:"subagent",status:"running"}]).map((G)=>G.status==="running"||G.status==="pending"?{...G,status:"failed",activityState:void 0,endedAt:G.endedAt??Q,durationMs:G.startedAt!==void 0&&G.durationMs===void 0?Math.max(0,Q-G.startedAt):G.durationMs,exitCode:G.exitCode??1,error:G.error??H}:G),A={...$,state:"failed",activityState:void 0,lastUpdate:Q,endedAt:Q,steps:V},M=V[$.currentStep??0]?.agent??V[0]?.agent??"subagent";return{status:A,message:H,result:{id:X,agent:M,mode:$.mode,success:!1,state:"failed",summary:H,results:V.map((G)=>({agent:G.agent,output:G.status==="complete"||G.status==="completed"?"":H,error:G.status==="complete"||G.status==="completed"?void 0:G.error??H,success:G.status==="complete"||G.status==="completed",model:G.model,attemptedModels:G.attemptedModels,modelAttempts:G.modelAttempts,sessionFile:G.sessionFile})),exitCode:1,timestamp:Q,durationMs:Math.max(0,Q-$.startedAt),asyncDir:J,sessionId:$.sessionId,sessionFile:$.sessionFile}}}function Y$($,J,Q,Z,X){let W=l$(J,$,Z,X);return N(Q,W.result),N(O.join($,"status.json"),W.status),c$(O.join($,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:Z,runId:W.status.runId,pid:J.pid,resultPath:Q,message:W.message}),{status:W.status,repaired:!0,resultPath:Q,message:W.message}}function i$($,J=process.kill){try{return J($,0),"alive"}catch(Q){let Z=typeof Q==="object"&&Q!==null&&"code"in Q?Q.code:void 0;if(Z==="ESRCH")return"dead";if(Z==="EPERM")return"unknown";return"unknown"}}function i($,J={}){let Q=J.now?.()??Date.now(),Z=d$($),X=!Z&&J.startedRun?u$($,J.startedRun,Q):void 0,W=Z??X;if(!W)return{status:null,repaired:!1};let K=W.runId||O.basename($),Y=O.join(J.resultsDir??S,`${K}.json`);if(L.existsSync(Y)){let B=W.state==="running"||W.state==="queued"?o$(W,Y,Q):void 0;if(B)return N(O.join($,"status.json"),B),{status:B,repaired:!0,resultPath:Y,message:"Existing async result file was used to repair stale running status."};return{status:W,repaired:!1,resultPath:Y}}if(W.state!=="running"||typeof W.pid!=="number")return{status:Z??null,repaired:!1,resultPath:Y};if(!Z){let B=J.startedRun?.startedAt??W.startedAt;if(Q-B<(J.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:Y}}if(i$(W.pid,J.kill)!=="dead"){let B=J.staleAlivePidMs??86400000,V=W.lastUpdate??W.startedAt;if(Q-V<=B)return{status:Z??null,repaired:!1,resultPath:Y};let A=`Async runner process ${W.pid} still has a live PID, but status has not updated for ${Q-V}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;return Y$($,W,Y,Q,A)}return Y$($,W,Y,Q)}var ej=process.platform==="win32"?"SIGBREAK":"SIGUSR2";function r($,J){if($===void 0)return;if($.trim()==="")throw Error(`${J} must not be empty.`);if(z.isAbsolute($)||/[\\/]/.test($)||$.includes(".."))throw Error(`${J} must be an async run id or prefix, not a path.`);return $}function c($,J,Q){let Z=z.resolve($),X=z.resolve(J),W=z.relative(Z,X);if(W===""||!W.startsWith("..")&&!z.isAbsolute(W))return;throw Error(`${Q} must be inside ${Z}.`)}function B$($,J,Q=""){if(!q.existsSync($))return[];return q.readdirSync($).filter((Z)=>Z.startsWith(J)&&(!Q||Z.endsWith(Q))).map((Z)=>Q?Z.slice(0,-Q.length):Z).sort()}function s($,J){let Q=z.join($,`${J}.json`);return c($,Q,"Async result file"),q.existsSync(Q)?Q:null}function r$($,J,Q){let Z=r($,"id");if(!Z)return[];let X=z.resolve(J),W=z.resolve(Q);return[...new Set([...B$(X,Z),...B$(W,Z,".json")])].sort().map((Y)=>{let H=z.join(X,Y);return c(X,H,"Async run directory"),{id:Y,location:{asyncDir:q.existsSync(H)?H:null,resultPath:s(W,Y),resolvedId:Y}}})}function G$($,J,Q){let Z=z.resolve(J),X=z.resolve(Q),W=r($.id,"id")??r($.runId,"runId");if($.dir){let B=z.resolve($.dir);c(Z,B,"Async run directory");let V=W??z.basename(B);if(W&&W!==z.basename(B))throw Error(`Async run id '${W}' does not match directory '${z.basename(B)}'.`);return{asyncDir:B,resultPath:s(X,V),resolvedId:V}}if(!W)return{asyncDir:null,resultPath:null};let K=z.join(Z,W);c(Z,K,"Async run directory");let Y=s(X,W);if(q.existsSync(K)||Y)return{asyncDir:q.existsSync(K)?K:null,resultPath:Y,resolvedId:W};let H=r$(W,Z,X);if(H.length===0)return{asyncDir:null,resultPath:null,resolvedId:W};if(H.length>1)throw Error(`Ambiguous async run id prefix '${W}' matched: ${H.map((B)=>B.id).join(", ")}. Provide a longer id.`);return H[0].location}import{Type as j}from"typebox";function U$($){return V$($,[])}function V$($,J){if(!$||typeof $!=="object")return $;let Q=Array.isArray($)?[]:Object.create(Object.getPrototypeOf($));for(let Z of Reflect.ownKeys($)){let X=Object.getOwnPropertyDescriptor($,Z);if(!X)continue;if(Z==="description"&&!s$(J))continue;if("value"in X){let W=typeof Z==="string"?[...J,Z]:J;X.value=V$(X.value,W)}Object.defineProperty(Q,Z,X)}return Q}function s$($){return $.length===2&&$[0]==="properties"}var I=j.Unsafe({anyOf:[{type:"array",items:{type:"string"}},{type:"boolean"},{type:"string"}],description:"Skill name(s) to make available (comma-separated), array of strings, or boolean (false disables, true uses default)"}),d=j.Unsafe({anyOf:[{type:"string"},{type:"boolean"}],description:"Output filename/path (string), or false to disable file output"}),w=j.String({enum:["inline","file-only"],description:"Return saved output inline (default) or only a concise file reference. file-only requires output to be a path."}),p=j.Unsafe({anyOf:[{type:"array",items:{type:"string"}},{type:"boolean"}],description:"Files to read before running (array of filenames), or false to disable"}),n=j.Unsafe({type:"object",additionalProperties:!0,description:"JSON Schema object for strict structured output. Non-object roots are rejected."}),R=j.Unsafe({anyOf:[{type:"string",enum:["auto","none","attested","checked","verified","reviewed"]},{type:"boolean",enum:[!1]},{type:"object",additionalProperties:!0}],description:"Optional acceptance policy. Omitted means auto-inferred; verified requires configured runtime commands."}),a$=j.Object({maxTurns:j.Integer({minimum:1}),graceTurns:j.Optional(j.Integer({minimum:0}))},{additionalProperties:!1,description:"Optional assistant-turn budget. At maxTurns the child is asked to wrap up; after graceTurns additional assistant turns it is aborted and partial output is returned."}),t$=j.Unsafe({anyOf:[{type:"array",minItems:1,items:{type:"string",minLength:1}},{type:"string",enum:["*"]}]}),P=j.Object({soft:j.Optional(j.Integer({minimum:1})),hard:j.Integer({minimum:1}),block:j.Optional(t$)},{additionalProperties:!1,description:"Optional child tool-call budget. soft nudges the child; after hard, block tools (default read/grep/find/ls, or '*' for all tools) are blocked so the child can finalize."}),e$=j.Object({agent:j.String(),task:j.String(),cwd:j.Optional(j.String()),count:j.Optional(j.Integer({minimum:1,description:"Repeat this parallel task N times with the same settings."})),output:j.Optional(d),outputMode:j.Optional(w),reads:j.Optional(p),progress:j.Optional(j.Boolean({description:"Enable progress.md tracking for this task"})),model:j.Optional(j.String({description:"Override model for this task (e.g. 'google/gemini-3-pro')"})),skill:j.Optional(I),toolBudget:j.Optional(P),acceptance:j.Optional(R)}),$0=j.Object({agent:j.String(),task:j.Optional(j.String({description:"Task template with {task}, {previous}, {chain_dir} variables. Defaults to {previous}."})),phase:j.Optional(j.String({description:"Optional phase/group label for status and graph rendering."})),label:j.Optional(j.String({description:"Optional user-facing label for this parallel task."})),as:j.Optional(j.String({description:"Optional safe identifier used as {outputs.name} in later chain steps."})),outputSchema:j.Optional(n),cwd:j.Optional(j.String()),count:j.Optional(j.Integer({minimum:1,description:"Repeat this parallel task N times with the same settings."})),output:j.Optional(d),outputMode:j.Optional(w),reads:j.Optional(p),progress:j.Optional(j.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:j.Optional(I),model:j.Optional(j.String({description:"Override model for this task"})),toolBudget:j.Optional(P),acceptance:j.Optional(R)}),j0=j.Object({from:j.Object({output:j.String({description:"Prior named structured output to expand from."}),path:j.String({description:"JSON Pointer into the structured output, e.g. /items."})},{additionalProperties:!1}),item:j.Optional(j.String({description:"Template variable name for each item. Defaults to item."})),key:j.Optional(j.String({description:"JSON Pointer relative to each item for stable child ids."})),maxItems:j.Optional(j.Integer({minimum:0,description:"Required fanout bound unless configured globally."})),onEmpty:j.Optional(j.String({enum:["skip","fail"],description:"Empty input behavior. Defaults to skip."}))},{additionalProperties:!1}),J0=j.Object({agent:j.String(),task:j.Optional(j.String({description:"Task template with {item}, {item.path}, {task}, {previous}, {chain_dir}, and {outputs.name} variables."})),phase:j.Optional(j.String({description:"Optional phase/group label for status and graph rendering."})),label:j.Optional(j.String({description:"Optional user-facing label; item templates are supported."})),outputSchema:j.Optional(n),cwd:j.Optional(j.String()),output:j.Optional(d),outputMode:j.Optional(w),reads:j.Optional(p),progress:j.Optional(j.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:j.Optional(I),model:j.Optional(j.String({description:"Override model for this task"})),toolBudget:j.Optional(P),acceptance:j.Optional(R)},{additionalProperties:!1}),Z0=j.Object({as:j.String({description:"Safe output name for the ordered collected result array."}),outputSchema:j.Optional(n)},{additionalProperties:!1}),Q0=j.Object({agent:j.Optional(j.String({description:"Sequential step agent name"})),task:j.Optional(j.String({description:"Task template with variables: {task}=original request, {previous}=prior step's text response, {chain_dir}=shared folder, {outputs.name}=prior named output. Required for first step, defaults to '{previous}' for subsequent steps."})),phase:j.Optional(j.String({description:"Optional phase/group label for status and graph rendering."})),label:j.Optional(j.String({description:"Optional user-facing label for this chain step."})),as:j.Optional(j.String({description:"Optional safe identifier used as {outputs.name} in later chain steps."})),outputSchema:j.Optional(n),cwd:j.Optional(j.String()),output:j.Optional(d),outputMode:j.Optional(w),reads:j.Optional(p),progress:j.Optional(j.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:j.Optional(I),model:j.Optional(j.String({description:"Override model for this step"})),toolBudget:j.Optional(P),acceptance:j.Optional(R),parallel:j.Optional(j.Unsafe({anyOf:[j.Array($0,{minItems:1,description:"Tasks to run in parallel"}),J0],description:"Static parallel tasks array, or a single dynamic fanout child template when expand/collect are present."})),expand:j.Optional(j0),collect:j.Optional(Z0),concurrency:j.Optional(j.Number({description:"Max concurrent tasks (default: 4)"})),failFast:j.Optional(j.Boolean({description:"Stop on first failure (default: false)"})),worktree:j.Optional(j.Boolean({description:"Create isolated git worktrees for each parallel task."}))},{description:"Chain step: use {agent, task?, ...} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout.",additionalProperties:!1}),W0=j.Object({enabled:j.Optional(j.Boolean({description:"Enable/disable subagent control attention tracking for this run"})),needsAttentionAfterMs:j.Optional(j.Integer({minimum:1,description:"No-observed-activity window before a run needs attention"})),activeNoticeAfterMs:j.Optional(j.Integer({minimum:1,description:"Active-long-running notice threshold by elapsed ms (default: 240000)"})),activeNoticeAfterTurns:j.Optional(j.Integer({minimum:1,description:"Optional active-long-running notice threshold by assistant turns (disabled by default)"})),activeNoticeAfterTokens:j.Optional(j.Integer({minimum:1,description:"Optional active-long-running notice threshold by total tokens (disabled by default)"})),failedToolAttemptsBeforeAttention:j.Optional(j.Integer({minimum:1,description:"Consecutive mutating-tool failures before escalating to needs_attention (default: 3)"})),notifyOn:j.Optional(j.Array(j.String({enum:["active_long_running","needs_attention"]}),{description:"Control event types that should notify the parent/orchestrator. Defaults to active_long_running and needs_attention."})),notifyChannels:j.Optional(j.Array(j.String({enum:["event","async","intercom"]}),{description:"Notification channels to use when available. Defaults to event, async, and intercom."}))}),X0=j.Object({agent:j.Optional(j.String({description:"Agent name (SINGLE mode) or target for management get/update/delete"})),task:j.Optional(j.String({description:"Task (SINGLE mode, optional for self-contained agents)"})),action:j.Optional(j.String({description:"Management/control action only. Must be omitted for execution mode (single, parallel, or chain)."})),id:j.Optional(j.String({description:"Run id or prefix for action='status', action='interrupt', action='resume', action='steer', or action='append-step'."})),runId:j.Optional(j.String({description:"Target run ID for action='interrupt', action='resume', action='steer', or action='append-step'. Defaults to the most recently active controllable run for interrupt. Prefer id for new calls."})),dir:j.Optional(j.String({description:"Async run directory for action='status', action='resume', or action='steer'."})),index:j.Optional(j.Integer({minimum:0,description:"Zero-based child index for actions that target a specific child or transcript."})),view:j.Optional(j.String({enum:["fleet","transcript"],description:"Optional status view. Use view='fleet' for a read-only active foreground/async fleet surface, or view='transcript' with id/dir (and optional index) to tail a run transcript."})),lines:j.Optional(j.Integer({minimum:1,maximum:500,description:"Maximum transcript lines for action='status', view='transcript'. Defaults to 80."})),message:j.Optional(j.String({description:"Follow-up message for action='resume' or non-terminal guidance for action='steer'. Use index to choose a child from multi-child runs."})),schedule:j.Optional(j.String({description:"Explicit one-shot schedule for action='schedule'. Only honored when scheduledRuns.enabled is true. Use '+10m' or a future ISO timestamp with timezone; scheduled runs always launch async with fresh context."})),scheduleName:j.Optional(j.String({description:"Optional display name for action='schedule'."})),chainName:j.Optional(j.String({description:"Chain name for get/update/delete management actions"})),config:j.Optional(j.Unsafe({anyOf:[{type:"object",additionalProperties:!0},{type:"string"}],description:"Agent/chain config for create/update. Object or JSON string; presence of steps creates a chain."})),tasks:j.Optional(j.Array(e$,{description:"PARALLEL mode: [{agent, task, count?, output?, outputMode?, reads?, progress?}, ...]"})),concurrency:j.Optional(j.Integer({minimum:1,description:"Top-level PARALLEL mode only: max concurrent tasks. Defaults to config.parallel.concurrency or 4."})),worktree:j.Optional(j.Boolean({description:"Create isolated git worktrees for parallel tasks; requires clean git state."})),chain:j.Optional(j.Array(Q0,{description:"CHAIN mode: sequential steps; each result becomes {previous}. append-step takes one tail step and may use {chain_dir}/{outputs.name}."})),context:j.Optional(j.String({enum:["fresh","fork"],description:"'fresh' or 'fork' to branch from parent session. Explicit context overrides every child in the invocation. If omitted, each requested agent uses its own defaultContext; agents without defaultContext: 'fork' run fresh."})),chainDir:j.Optional(j.String({description:"Persistent chain artifact directory; defaults to user-scoped temp storage."})),async:j.Optional(j.Boolean({description:"Run in background (default: false, or per config)"})),timeoutMs:j.Optional(j.Integer({minimum:1,description:"Optional run-level timeout in ms for foreground and async/background runs. Alias of maxRuntimeMs."})),maxRuntimeMs:j.Optional(j.Integer({minimum:1,description:"Alias of timeoutMs for optional run-level timeout in foreground and async/background runs."})),turnBudget:j.Optional(a$),toolBudget:j.Optional(P),agentScope:j.Optional(j.String({description:"Agent discovery scope: 'user', 'project', or 'both' (default: 'both'; project wins on name collisions)"})),cwd:j.Optional(j.String()),artifacts:j.Optional(j.Boolean({description:"Write debug artifacts (default: true)"})),includeProgress:j.Optional(j.Boolean({description:"Include full progress in result (default: false)"})),share:j.Optional(j.Boolean({description:"Upload session to GitHub Gist for sharing (default: false)"})),sessionDir:j.Optional(j.String({description:"Directory to store session logs (default: temp; enables sessions even if share=false)"})),clarify:j.Optional(j.Boolean({description:"Show TUI to preview/edit before execution. Explicit clarify: true keeps the run foreground for the clarify UI; omitted clarify can still run in the background when async: true is set."})),control:j.Optional(W0),output:j.Optional(j.Unsafe({anyOf:[{type:"string"},{type:"boolean"}],description:"Output file for single agent (string), or false to disable. Relative paths resolve against cwd."})),outputMode:j.Optional(w),skill:j.Optional(I),model:j.Optional(j.String({description:"Override model for single agent (e.g. 'anthropic/claude-sonnet-4')"})),acceptance:j.Optional(R)}),z$=U$(X0),K0=j.Object({id:j.Optional(j.String({description:"Run id or prefix to wait for one specific run. Omit to wait across every active async run started in this session."})),all:j.Optional(j.Boolean({description:"Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id targets a single run."})),timeoutMs:j.Optional(j.Integer({minimum:1,description:"Give up waiting after this many milliseconds (the runs keep going regardless). Defaults to 1800000 (30 minutes)."}))}),J1=U$(K0);var v=1,F$="subagents:rpc:v1:request",C$="subagents:rpc:v1:ready",A$="subagents:rpc:v1:reply:",e=["ping","status","spawn","interrupt","stop"];class U extends Error{code;constructor($,J){super(J);this.name="SubagentRpcError",this.code=$}}var L$=Y0(z$);function M$($){return`${A$}${$}`}function g($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function H0($){if(typeof $!=="string"||$.trim().length===0||/[\r\n]/.test($))throw new U("invalid_request","RPC requestId must be a non-empty string without newlines.");return $}function f$($,J){if($===void 0)return{};if(!g($))throw new U("invalid_params",`RPC ${J} params must be an object.`);return $}function q$($,J){if(L$.Check($))return;let Q=[...L$.Errors($)].slice(0,4).map((Z)=>Z.message);throw new U("invalid_params",`${J}: ${Q.join("; ")||"invalid subagent parameters"}`)}function _$($){return $.content.filter((J)=>J.type==="text").map((J)=>J.text).join(`
8
- `)}function B0($){return{text:_$($),...$.details?{details:$.details}:{},...$.isError?{isError:!0}:{}}}function G0($){if(!$.isError)return;throw new U("execution_failed",_$($)||"Subagent RPC execution failed.")}function t($,J){let Q=f$($,J),Z={};if(Q.id!==void 0)Z.id=Q.id;if(Q.runId!==void 0)Z.runId=Q.runId;if(Q.dir!==void 0)Z.dir=Q.dir;if(Q.index!==void 0)Z.index=Q.index;return Z}function U0($){if(!$)return{};return{cwd:$.cwd,sessionId:$.sessionManager.getSessionId()??void 0,sessionFile:$.sessionManager.getSessionFile()??null}}function T$($){return{version:v,methods:[...e],capabilities:{status:!0,asyncSpawn:!0,interrupt:!0,stop:!0},events:{ready:C$,request:F$,replyPrefix:A$},session:U0($)}}async function a($,J,Q,Z,X){q$(X,`RPC ${Z} params`);let W=new AbortController,K=await $.execute(`rpc-${Z}-${Q}`,X,W.signal,void 0,J);return G0(K),B0(K)}function V0($){let J=f$($,"spawn");if(J.action!==void 0)throw new U("invalid_params","RPC spawn does not accept management/control actions. Use status or interrupt RPC methods instead.");if(J.async===!1)throw new U("invalid_params","RPC spawn only supports detached async launches; omit async or set async: true.");if(J.clarify===!0)throw new U("invalid_params","RPC spawn cannot open the clarify UI; omit clarify or set clarify: false.");return{...J,async:!0,clarify:!1}}function z0($,J,Q){let Z=t($,"stop");q$({action:"status",...Z},"RPC stop target params");let X=J.asyncDirRoot??h,W=J.resultsDir??S,K;try{K=G$(Z,X,W)}catch(M){throw new U("invalid_params",M instanceof Error?M.message:String(M))}if(!K.asyncDir)throw new U("not_found","Async run not found or already completed; stop requires a live async run directory.");let Y=Q.sessionManager.getSessionId(),H=J$(K.asyncDir),B=H?.runId??K.resolvedId??O$.basename(K.asyncDir);if(!H)throw new U("not_found",`Status file not found for async run '${B}'.`);if(!Y||H.sessionId!==Y)throw new U("not_found",`Async run '${B}' was not found in the active session.`);let V;try{V=i(K.asyncDir,{resultsDir:W,kill:J.kill,now:J.now}).status}catch(M){throw new U("execution_failed",M instanceof Error?M.message:String(M))}let A=V?.runId??B;if(!V)throw new U("not_found",`Status file not found for async run '${A}'.`);if(V.sessionId!==Y)throw new U("not_found",`Async run '${A}' was not found in the active session.`);if(V.state!=="running")throw new U("invalid_state",`Async run ${A} is ${V.state}; stop only supports running async runs.`);try{W$({asyncDir:K.asyncDir,pid:V.pid,kill:J.kill,now:J.now,source:"rpc-stop"})}catch(M){throw new U("execution_failed",M instanceof Error?M.message:String(M))}return{runId:A,asyncDir:K.asyncDir,previousState:V.state,state:"stopping",message:`Stop requested for async run ${A}.`}}async function L0($,J){let Q=J.getContext();if($.method==="ping")return T$(Q);if(!Q)throw new U("no_active_session","No active extension context for subagent RPC.");if($.method==="spawn")return a(J,Q,$.requestId,$.method,V0($.params));if($.method==="status")return a(J,Q,$.requestId,$.method,{action:"status",...t($.params,"status")});if($.method==="interrupt")return a(J,Q,$.requestId,$.method,{action:"interrupt",...t($.params,"interrupt")});if($.method==="stop")return z0($.params,J,Q);throw new U("unsupported_method",`Unsupported subagent RPC method: ${String($.method)}`)}function M0($){if(!g($))throw new U("invalid_request","Subagent RPC request must be an object.");let J=H0($.requestId);if($.version!==v)throw new U("unsupported_version",`Unsupported subagent RPC version: ${String($.version)}.`);if(typeof $.method!=="string"||!e.includes($.method))throw new U("unsupported_method",`Unsupported subagent RPC method: ${String($.method)}.`);return{version:v,requestId:J,method:$.method,...$.params!==void 0?{params:$.params}:{},...g($.source)?{source:$.source}:{}}}function O0($){if(!g($))return"unknown";let J=$.requestId;return typeof J==="string"&&J.trim().length>0&&!/[\r\n]/.test(J)?J:"unknown"}function F0($,J){let Q=O0($),Z=g($)&&typeof $.method==="string"&&e.includes($.method)?$.method:void 0,X=J instanceof U?J:new U("execution_failed",J instanceof Error?J.message:String(J));return{version:v,requestId:Q,...Z?{method:Z}:{},success:!1,error:{code:X.code,message:X.message}}}function G1($){let J=$.events.on(F$,async(Q)=>{let Z;try{Z=M0(Q);let X=await L0(Z,$);$.events.emit(M$(Z.requestId),{version:v,requestId:Z.requestId,method:Z.method,success:!0,data:X})}catch(X){let W=F0(Z??Q,X);$.events.emit(M$(W.requestId),W)}});return{emitReady:(Q)=>{$.events.emit(C$,T$(Q??$.getContext()))},dispose:()=>{if(typeof J==="function")J()}}}export{M$ as subagentRpcReplyEvent,G1 as registerSubagentRpcBridge,F$ as SUBAGENT_RPC_REQUEST_EVENT,A$ as SUBAGENT_RPC_REPLY_EVENT_PREFIX,C$ as SUBAGENT_RPC_READY_EVENT,v as SUBAGENT_RPC_PROTOCOL_VERSION,e as SUBAGENT_RPC_METHODS};
7
+ ${Y}`:K,V=(($.steps?.length)?$.steps:[{agent:"subagent",status:"running"}]).map((G)=>G.status==="running"||G.status==="pending"?{...G,status:"failed",activityState:void 0,endedAt:G.endedAt??Q,durationMs:G.startedAt!==void 0&&G.durationMs===void 0?Math.max(0,Q-G.startedAt):G.durationMs,exitCode:G.exitCode??1,error:G.error??H}:G),f={...$,state:"failed",activityState:void 0,lastUpdate:Q,endedAt:Q,steps:V},M=V[$.currentStep??0]?.agent??V[0]?.agent??"subagent";return{status:f,message:H,result:{id:X,agent:M,mode:$.mode,success:!1,state:"failed",summary:H,results:V.map((G)=>({agent:G.agent,output:G.status==="complete"||G.status==="completed"?"":H,error:G.status==="complete"||G.status==="completed"?void 0:G.error??H,success:G.status==="complete"||G.status==="completed",model:G.model,attemptedModels:G.attemptedModels,modelAttempts:G.modelAttempts,sessionFile:G.sessionFile})),exitCode:1,timestamp:Q,durationMs:Math.max(0,Q-$.startedAt),asyncDir:J,sessionId:$.sessionId,sessionFile:$.sessionFile}}}function H$($,J,Q,Z,X){let W=r$(J,$,Z,X);return b(Q,W.result),b(O.join($,"status.json"),W.status),p$(O.join($,"events.jsonl"),{type:"subagent.run.repaired_stale",ts:Z,runId:W.status.runId,pid:J.pid,resultPath:Q,message:W.message}),{status:W.status,repaired:!0,resultPath:Q,message:W.message}}function s$($,J=process.kill){try{return J($,0),"alive"}catch(Q){let Z=typeof Q==="object"&&Q!==null&&"code"in Q?Q.code:void 0;if(Z==="ESRCH")return"dead";if(Z==="EPERM")return"unknown";return"unknown"}}function r($,J={}){let Q=J.now?.()??Date.now(),Z=n$($),X=!Z&&J.startedRun?i$($,J.startedRun,Q):void 0,W=Z??X;if(!W)return{status:null,repaired:!1};let K=W.runId||O.basename($),Y=O.join(J.resultsDir??x,`${K}.json`);if(L.existsSync(Y)){let B=W.state==="running"||W.state==="queued"?l$(W,Y,Q):void 0;if(B)return b(O.join($,"status.json"),B),{status:B,repaired:!0,resultPath:Y,message:"Existing async result file was used to repair stale running status."};return{status:W,repaired:!1,resultPath:Y}}if(W.state!=="running"||typeof W.pid!=="number")return{status:Z??null,repaired:!1,resultPath:Y};if(!Z){let B=J.startedRun?.startedAt??W.startedAt;if(Q-B<(J.missingStatusGraceMs??1000))return{status:null,repaired:!1,resultPath:Y}}if(s$(W.pid,J.kill)!=="dead"){let B=J.staleAlivePidMs??86400000,V=W.lastUpdate??W.startedAt;if(Q-V<=B)return{status:Z??null,repaired:!1,resultPath:Y};let f=`Async runner process ${W.pid} still has a live PID, but status has not updated for ${Q-V}ms. Marked run failed by stale-run reconciliation because PID ownership cannot be verified.`;return H$($,W,Y,Q,f)}return H$($,W,Y,Q)}var j1=process.platform==="win32"?"SIGBREAK":"SIGUSR2";function s($,J){if($===void 0)return;if($.trim()==="")throw Error(`${J} must not be empty.`);if(z.isAbsolute($)||/[\\/]/.test($)||$.includes(".."))throw Error(`${J} must be an async run id or prefix, not a path.`);return $}function d($,J,Q){let Z=z.resolve($),X=z.resolve(J),W=z.relative(Z,X);if(W===""||!W.startsWith("..")&&!z.isAbsolute(W))return;throw Error(`${Q} must be inside ${Z}.`)}function G$($,J,Q=""){if(!_.existsSync($))return[];return _.readdirSync($).filter((Z)=>Z.startsWith(J)&&(!Q||Z.endsWith(Q))).map((Z)=>Q?Z.slice(0,-Q.length):Z).sort()}function a($,J){let Q=z.join($,`${J}.json`);return d($,Q,"Async result file"),_.existsSync(Q)?Q:null}function a$($,J,Q){let Z=s($,"id");if(!Z)return[];let X=z.resolve(J),W=z.resolve(Q);return[...new Set([...G$(X,Z),...G$(W,Z,".json")])].sort().map((Y)=>{let H=z.join(X,Y);return d(X,H,"Async run directory"),{id:Y,location:{asyncDir:_.existsSync(H)?H:null,resultPath:a(W,Y),resolvedId:Y}}})}function U$($,J,Q){let Z=z.resolve(J),X=z.resolve(Q),W=s($.id,"id")??s($.runId,"runId");if($.dir){let B=z.resolve($.dir);d(Z,B,"Async run directory");let V=W??z.basename(B);if(W&&W!==z.basename(B))throw Error(`Async run id '${W}' does not match directory '${z.basename(B)}'.`);return{asyncDir:B,resultPath:a(X,V),resolvedId:V}}if(!W)return{asyncDir:null,resultPath:null};let K=z.join(Z,W);d(Z,K,"Async run directory");let Y=a(X,W);if(_.existsSync(K)||Y)return{asyncDir:_.existsSync(K)?K:null,resultPath:Y,resolvedId:W};let H=a$(W,Z,X);if(H.length===0)return{asyncDir:null,resultPath:null,resolvedId:W};if(H.length>1)throw Error(`Ambiguous async run id prefix '${W}' matched: ${H.map((B)=>B.id).join(", ")}. Provide a longer id.`);return H[0].location}import{Type as j}from"typebox";function V$($){return z$($,[])}function z$($,J){if(!$||typeof $!=="object")return $;let Q=Array.isArray($)?[]:Object.create(Object.getPrototypeOf($));for(let Z of Reflect.ownKeys($)){let X=Object.getOwnPropertyDescriptor($,Z);if(!X)continue;if(Z==="description"&&!t$(J))continue;if("value"in X){let W=typeof Z==="string"?[...J,Z]:J;X.value=z$(X.value,W)}Object.defineProperty(Q,Z,X)}return Q}function t$($){return $.length===2&&$[0]==="properties"}var w=j.Unsafe({anyOf:[{type:"array",items:{type:"string"}},{type:"boolean"},{type:"string"}],description:"Skill name(s) to make available (comma-separated), array of strings, or boolean (false disables, true uses default)"}),p=j.Unsafe({anyOf:[{type:"string"},{type:"boolean"}],description:"Output filename/path (string), or false to disable file output"}),R=j.String({enum:["inline","file-only"],description:"Return saved output inline (default) or only a concise file reference. file-only requires output to be a path."}),n=j.Unsafe({anyOf:[{type:"array",items:{type:"string"}},{type:"boolean"}],description:"Files to read before running (array of filenames), or false to disable"}),o=j.Unsafe({type:"object",additionalProperties:!0,description:"JSON Schema object for strict structured output. Non-object roots are rejected."}),P=j.Unsafe({anyOf:[{type:"string",enum:["auto","none","attested","checked","verified","reviewed"]},{type:"boolean",enum:[!1]},{type:"object",additionalProperties:!0}],description:"Optional acceptance policy. Omitted means auto-inferred; verified requires configured runtime commands."}),e$=j.Object({maxTurns:j.Integer({minimum:1}),graceTurns:j.Optional(j.Integer({minimum:0}))},{additionalProperties:!1,description:"Optional assistant-turn budget. At maxTurns the child is asked to wrap up; after graceTurns additional assistant turns it is aborted and partial output is returned."}),$0=j.Unsafe({anyOf:[{type:"array",minItems:1,items:{type:"string",minLength:1}},{type:"string",enum:["*"]}]}),v=j.Object({soft:j.Optional(j.Integer({minimum:1})),hard:j.Integer({minimum:1}),block:j.Optional($0)},{additionalProperties:!1,description:"Optional child tool-call budget. soft nudges the child; after hard, block tools (default read/grep/find/ls, or '*' for all tools) are blocked so the child can finalize."}),j0=j.Object({agent:j.String(),task:j.String(),cwd:j.Optional(j.String()),count:j.Optional(j.Integer({minimum:1,description:"Repeat this parallel task N times with the same settings."})),output:j.Optional(p),outputMode:j.Optional(R),reads:j.Optional(n),progress:j.Optional(j.Boolean({description:"Enable progress.md tracking for this task"})),model:j.Optional(j.String({description:"Override model for this task (e.g. 'google/gemini-3-pro')"})),skill:j.Optional(w),toolBudget:j.Optional(v),acceptance:j.Optional(P)}),J0=j.Object({agent:j.String(),task:j.Optional(j.String({description:"Task template with {task}, {previous}, {chain_dir} variables. Defaults to {previous}."})),phase:j.Optional(j.String({description:"Optional phase/group label for status and graph rendering."})),label:j.Optional(j.String({description:"Optional user-facing label for this parallel task."})),as:j.Optional(j.String({description:"Optional safe identifier used as {outputs.name} in later chain steps."})),outputSchema:j.Optional(o),cwd:j.Optional(j.String()),count:j.Optional(j.Integer({minimum:1,description:"Repeat this parallel task N times with the same settings."})),output:j.Optional(p),outputMode:j.Optional(R),reads:j.Optional(n),progress:j.Optional(j.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:j.Optional(w),model:j.Optional(j.String({description:"Override model for this task"})),toolBudget:j.Optional(v),acceptance:j.Optional(P)}),Z0=j.Object({from:j.Object({output:j.String({description:"Prior named structured output to expand from."}),path:j.String({description:"JSON Pointer into the structured output, e.g. /items."})},{additionalProperties:!1}),item:j.Optional(j.String({description:"Template variable name for each item. Defaults to item."})),key:j.Optional(j.String({description:"JSON Pointer relative to each item for stable child ids."})),maxItems:j.Optional(j.Integer({minimum:0,description:"Required fanout bound unless configured globally."})),onEmpty:j.Optional(j.String({enum:["skip","fail"],description:"Empty input behavior. Defaults to skip."}))},{additionalProperties:!1}),Q0=j.Object({agent:j.String(),task:j.Optional(j.String({description:"Task template with {item}, {item.path}, {task}, {previous}, {chain_dir}, and {outputs.name} variables."})),phase:j.Optional(j.String({description:"Optional phase/group label for status and graph rendering."})),label:j.Optional(j.String({description:"Optional user-facing label; item templates are supported."})),outputSchema:j.Optional(o),cwd:j.Optional(j.String()),output:j.Optional(p),outputMode:j.Optional(R),reads:j.Optional(n),progress:j.Optional(j.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:j.Optional(w),model:j.Optional(j.String({description:"Override model for this task"})),toolBudget:j.Optional(v),acceptance:j.Optional(P)},{additionalProperties:!1}),W0=j.Object({as:j.String({description:"Safe output name for the ordered collected result array."}),outputSchema:j.Optional(o)},{additionalProperties:!1}),X0=j.Object({agent:j.Optional(j.String({description:"Sequential step agent name"})),task:j.Optional(j.String({description:"Task template with variables: {task}=original request, {previous}=prior step's text response, {chain_dir}=shared folder, {outputs.name}=prior named output. Required for first step, defaults to '{previous}' for subsequent steps."})),phase:j.Optional(j.String({description:"Optional phase/group label for status and graph rendering."})),label:j.Optional(j.String({description:"Optional user-facing label for this chain step."})),as:j.Optional(j.String({description:"Optional safe identifier used as {outputs.name} in later chain steps."})),outputSchema:j.Optional(o),cwd:j.Optional(j.String()),output:j.Optional(p),outputMode:j.Optional(R),reads:j.Optional(n),progress:j.Optional(j.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:j.Optional(w),model:j.Optional(j.String({description:"Override model for this step"})),toolBudget:j.Optional(v),acceptance:j.Optional(P),parallel:j.Optional(j.Unsafe({anyOf:[j.Array(J0,{minItems:1,description:"Tasks to run in parallel"}),Q0],description:"Static parallel tasks array, or a single dynamic fanout child template when expand/collect are present."})),expand:j.Optional(Z0),collect:j.Optional(W0),concurrency:j.Optional(j.Number({description:"Max concurrent tasks (default: 4)"})),failFast:j.Optional(j.Boolean({description:"Stop on first failure (default: false)"})),worktree:j.Optional(j.Boolean({description:"Create isolated git worktrees for each parallel task."}))},{description:"Chain step: use {agent, task?, ...} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout.",additionalProperties:!1}),K0=j.Object({enabled:j.Optional(j.Boolean({description:"Enable/disable subagent control attention tracking for this run"})),needsAttentionAfterMs:j.Optional(j.Integer({minimum:1,description:"No-observed-activity window before a run needs attention"})),activeNoticeAfterMs:j.Optional(j.Integer({minimum:1,description:"Active-long-running notice threshold by elapsed ms (default: 240000)"})),activeNoticeAfterTurns:j.Optional(j.Integer({minimum:1,description:"Optional active-long-running notice threshold by assistant turns (disabled by default)"})),activeNoticeAfterTokens:j.Optional(j.Integer({minimum:1,description:"Optional active-long-running notice threshold by total tokens (disabled by default)"})),failedToolAttemptsBeforeAttention:j.Optional(j.Integer({minimum:1,description:"Consecutive mutating-tool failures before escalating to needs_attention (default: 3)"})),notifyOn:j.Optional(j.Array(j.String({enum:["active_long_running","needs_attention"]}),{description:"Control event types that should notify the parent/orchestrator. Defaults to active_long_running and needs_attention."})),notifyChannels:j.Optional(j.Array(j.String({enum:["event","async","intercom"]}),{description:"Notification channels to use when available. Defaults to event, async, and intercom."}))}),Y0=j.Object({agent:j.Optional(j.String({description:"Agent name (SINGLE mode) or target for management get/update/delete. For generic SINGLE work, omit agent; task-only execution uses the bundled default."})),task:j.Optional(j.String({description:"Task (SINGLE mode, optional for self-contained agents)"})),action:j.Optional(j.String({description:"Management/control action only. Must be omitted for execution mode (single, parallel, or chain)."})),id:j.Optional(j.String({description:"Run id or prefix for action='status', action='interrupt', action='resume', action='steer', or action='append-step'."})),runId:j.Optional(j.String({description:"Target run ID for action='interrupt', action='resume', action='steer', or action='append-step'. Defaults to the most recently active controllable run for interrupt. Prefer id for new calls."})),dir:j.Optional(j.String({description:"Async run directory for action='status', action='resume', or action='steer'."})),index:j.Optional(j.Integer({minimum:0,description:"Zero-based child index for actions that target a specific child or transcript."})),view:j.Optional(j.String({enum:["fleet","transcript"],description:"Optional status view. Use view='fleet' for a read-only active foreground/async fleet surface, or view='transcript' with id/dir (and optional index) to tail a run transcript."})),lines:j.Optional(j.Integer({minimum:1,maximum:500,description:"Maximum transcript lines for action='status', view='transcript'. Defaults to 80."})),message:j.Optional(j.String({description:"Follow-up message for action='resume' or non-terminal guidance for action='steer'. Use index to choose a child from multi-child runs."})),schedule:j.Optional(j.String({description:"Explicit one-shot schedule for action='schedule'. Only honored when scheduledRuns.enabled is true. Use '+10m' or a future ISO timestamp with timezone; scheduled runs always launch async with fresh context."})),scheduleName:j.Optional(j.String({description:"Optional display name for action='schedule'."})),chainName:j.Optional(j.String({description:"Chain name for get/update/delete management actions"})),config:j.Optional(j.Unsafe({anyOf:[{type:"object",additionalProperties:!0},{type:"string"}],description:"Agent/chain config for create/update. Object or JSON string; presence of steps creates a chain."})),tasks:j.Optional(j.Array(j0,{description:"PARALLEL mode: [{agent, task, count?, output?, outputMode?, reads?, progress?}, ...]"})),concurrency:j.Optional(j.Integer({minimum:1,description:"Top-level PARALLEL mode only: max concurrent tasks. Defaults to config.parallel.concurrency or 4."})),worktree:j.Optional(j.Boolean({description:"Create isolated git worktrees for parallel tasks; requires clean git state."})),chain:j.Optional(j.Array(X0,{description:"CHAIN mode: sequential steps; each result becomes {previous}. append-step takes one tail step and may use {chain_dir}/{outputs.name}."})),context:j.Optional(j.String({enum:["fresh","fork"],description:"'fresh' or 'fork' to branch from parent session. Explicit context overrides every child in the invocation. If omitted, each requested agent uses its own defaultContext; agents without defaultContext: 'fork' run fresh."})),chainDir:j.Optional(j.String({description:"Persistent chain artifact directory; defaults to user-scoped temp storage."})),async:j.Optional(j.Boolean({description:"Run in background (default: false, or per config)"})),timeoutMs:j.Optional(j.Integer({minimum:1,description:"Optional run-level timeout in ms for foreground and async/background runs. Alias of maxRuntimeMs."})),maxRuntimeMs:j.Optional(j.Integer({minimum:1,description:"Alias of timeoutMs for optional run-level timeout in foreground and async/background runs."})),turnBudget:j.Optional(e$),toolBudget:j.Optional(v),agentScope:j.Optional(j.String({description:"Agent discovery scope: 'user', 'project', or 'both' (default: 'both'; project wins on name collisions)"})),cwd:j.Optional(j.String()),artifacts:j.Optional(j.Boolean({description:"Write debug artifacts (default: true)"})),includeProgress:j.Optional(j.Boolean({description:"Include full progress in result (default: false)"})),share:j.Optional(j.Boolean({description:"Upload session to GitHub Gist for sharing (default: false)"})),sessionDir:j.Optional(j.String({description:"Directory to store session logs (default: temp; enables sessions even if share=false)"})),clarify:j.Optional(j.Boolean({description:"Show TUI to preview/edit before execution. Explicit clarify: true keeps the run foreground for the clarify UI; omitted clarify can still run in the background when async: true is set."})),control:j.Optional(K0),output:j.Optional(j.Unsafe({anyOf:[{type:"string"},{type:"boolean"}],description:"Output file for single agent (string), or false to disable. Relative paths resolve against cwd."})),outputMode:j.Optional(R),skill:j.Optional(w),model:j.Optional(j.String({description:"Override model for single agent (e.g. 'anthropic/claude-sonnet-4')"})),acceptance:j.Optional(P)}),L$=V$(Y0),H0=j.Object({id:j.Optional(j.String({description:"Run id or prefix to wait for one specific run. Omit to wait across every active async run started in this session."})),all:j.Optional(j.Boolean({description:"Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id targets a single run."})),timeoutMs:j.Optional(j.Integer({minimum:1,description:"Give up waiting after this many milliseconds (the runs keep going regardless). Defaults to 1800000 (30 minutes)."}))}),Q1=V$(H0);var g=1,C$="subagents:rpc:v1:request",A$="subagents:rpc:v1:ready",f$="subagents:rpc:v1:reply:",$$=["ping","status","spawn","interrupt","stop"];class U extends Error{code;constructor($,J){super(J);this.name="SubagentRpcError",this.code=$}}var M$=B0(L$);function O$($){return`${f$}${$}`}function h($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function G0($){if(typeof $!=="string"||$.trim().length===0||/[\r\n]/.test($))throw new U("invalid_request","RPC requestId must be a non-empty string without newlines.");return $}function q$($,J){if($===void 0)return{};if(!h($))throw new U("invalid_params",`RPC ${J} params must be an object.`);return $}function _$($,J){if(M$.Check($))return;let Q=[...M$.Errors($)].slice(0,4).map((Z)=>Z.message);throw new U("invalid_params",`${J}: ${Q.join("; ")||"invalid subagent parameters"}`)}function T$($){return $.content.filter((J)=>J.type==="text").map((J)=>J.text).join(`
8
+ `)}function U0($){return{text:T$($),...$.details?{details:$.details}:{},...$.isError?{isError:!0}:{}}}function V0($){if(!$.isError)return;throw new U("execution_failed",T$($)||"Subagent RPC execution failed.")}function e($,J){let Q=q$($,J),Z={};if(Q.id!==void 0)Z.id=Q.id;if(Q.runId!==void 0)Z.runId=Q.runId;if(Q.dir!==void 0)Z.dir=Q.dir;if(Q.index!==void 0)Z.index=Q.index;return Z}function z0($){if(!$)return{};return{cwd:$.cwd,sessionId:$.sessionManager.getSessionId()??void 0,sessionFile:$.sessionManager.getSessionFile()??null}}function N$($){return{version:g,methods:[...$$],capabilities:{status:!0,asyncSpawn:!0,interrupt:!0,stop:!0},events:{ready:A$,request:C$,replyPrefix:f$},session:z0($)}}async function t($,J,Q,Z,X){_$(X,`RPC ${Z} params`);let W=new AbortController,K=await $.execute(`rpc-${Z}-${Q}`,X,W.signal,void 0,J);return V0(K),U0(K)}function L0($){let J=q$($,"spawn");if(J.action!==void 0)throw new U("invalid_params","RPC spawn does not accept management/control actions. Use status or interrupt RPC methods instead.");if(J.async===!1)throw new U("invalid_params","RPC spawn only supports detached async launches; omit async or set async: true.");if(J.clarify===!0)throw new U("invalid_params","RPC spawn cannot open the clarify UI; omit clarify or set clarify: false.");return{...J,async:!0,clarify:!1}}function M0($,J,Q){let Z=e($,"stop");_$({action:"status",...Z},"RPC stop target params");let X=J.asyncDirRoot??c,W=J.resultsDir??x,K;try{K=U$(Z,X,W)}catch(M){throw new U("invalid_params",M instanceof Error?M.message:String(M))}if(!K.asyncDir)throw new U("not_found","Async run not found or already completed; stop requires a live async run directory.");let Y=Q.sessionManager.getSessionId(),H=Z$(K.asyncDir),B=H?.runId??K.resolvedId??F$.basename(K.asyncDir);if(!H)throw new U("not_found",`Status file not found for async run '${B}'.`);if(!Y||H.sessionId!==Y)throw new U("not_found",`Async run '${B}' was not found in the active session.`);let V;try{V=r(K.asyncDir,{resultsDir:W,kill:J.kill,now:J.now}).status}catch(M){throw new U("execution_failed",M instanceof Error?M.message:String(M))}let f=V?.runId??B;if(!V)throw new U("not_found",`Status file not found for async run '${f}'.`);if(V.sessionId!==Y)throw new U("not_found",`Async run '${f}' was not found in the active session.`);if(V.state!=="running")throw new U("invalid_state",`Async run ${f} is ${V.state}; stop only supports running async runs.`);try{X$({asyncDir:K.asyncDir,pid:V.pid,kill:J.kill,now:J.now,source:"rpc-stop"})}catch(M){throw new U("execution_failed",M instanceof Error?M.message:String(M))}return{runId:f,asyncDir:K.asyncDir,previousState:V.state,state:"stopping",message:`Stop requested for async run ${f}.`}}async function O0($,J){let Q=J.getContext();if($.method==="ping")return N$(Q);if(!Q)throw new U("no_active_session","No active extension context for subagent RPC.");if($.method==="spawn")return t(J,Q,$.requestId,$.method,L0($.params));if($.method==="status")return t(J,Q,$.requestId,$.method,{action:"status",...e($.params,"status")});if($.method==="interrupt")return t(J,Q,$.requestId,$.method,{action:"interrupt",...e($.params,"interrupt")});if($.method==="stop")return M0($.params,J,Q);throw new U("unsupported_method",`Unsupported subagent RPC method: ${String($.method)}`)}function F0($){if(!h($))throw new U("invalid_request","Subagent RPC request must be an object.");let J=G0($.requestId);if($.version!==g)throw new U("unsupported_version",`Unsupported subagent RPC version: ${String($.version)}.`);if(typeof $.method!=="string"||!$$.includes($.method))throw new U("unsupported_method",`Unsupported subagent RPC method: ${String($.method)}.`);return{version:g,requestId:J,method:$.method,...$.params!==void 0?{params:$.params}:{},...h($.source)?{source:$.source}:{}}}function C0($){if(!h($))return"unknown";let J=$.requestId;return typeof J==="string"&&J.trim().length>0&&!/[\r\n]/.test(J)?J:"unknown"}function A0($,J){let Q=C0($),Z=h($)&&typeof $.method==="string"&&$$.includes($.method)?$.method:void 0,X=J instanceof U?J:new U("execution_failed",J instanceof Error?J.message:String(J));return{version:g,requestId:Q,...Z?{method:Z}:{},success:!1,error:{code:X.code,message:X.message}}}function V1($){let J=$.events.on(C$,async(Q)=>{let Z;try{Z=F0(Q);let X=await O0(Z,$);$.events.emit(O$(Z.requestId),{version:g,requestId:Z.requestId,method:Z.method,success:!0,data:X})}catch(X){let W=A0(Z??Q,X);$.events.emit(O$(W.requestId),W)}});return{emitReady:(Q)=>{$.events.emit(A$,N$(Q??$.getContext()))},dispose:()=>{if(typeof J==="function")J()}}}export{O$ as subagentRpcReplyEvent,V1 as registerSubagentRpcBridge,C$ as SUBAGENT_RPC_REQUEST_EVENT,f$ as SUBAGENT_RPC_REPLY_EVENT_PREFIX,A$ as SUBAGENT_RPC_READY_EVENT,g as SUBAGENT_RPC_PROTOCOL_VERSION,$$ as SUBAGENT_RPC_METHODS};
@@ -1 +1 @@
1
- import{Type as f}from"typebox";function V(q){return X(q,[])}function X(q,R){if(!q||typeof q!=="object")return q;let U=Array.isArray(q)?[]:Object.create(Object.getPrototypeOf(q));for(let w of Reflect.ownKeys(q)){let z=Object.getOwnPropertyDescriptor(q,w);if(!z)continue;if(w==="description"&&!Z(R))continue;if("value"in z){let Y=typeof w==="string"?[...R,w]:R;z.value=X(z.value,Y)}Object.defineProperty(U,w,z)}return U}function Z(q){return q.length===2&&q[0]==="properties"}var E=f.Unsafe({anyOf:[{type:"array",items:{type:"string"}},{type:"boolean"},{type:"string"}],description:"Skill name(s) to make available (comma-separated), array of strings, or boolean (false disables, true uses default)"}),K=f.Unsafe({anyOf:[{type:"string"},{type:"boolean"}],description:"Output filename/path (string), or false to disable file output"}),F=f.String({enum:["inline","file-only"],description:"Return saved output inline (default) or only a concise file reference. file-only requires output to be a path."}),M=f.Unsafe({anyOf:[{type:"array",items:{type:"string"}},{type:"boolean"}],description:"Files to read before running (array of filenames), or false to disable"}),Q=f.Unsafe({type:"object",additionalProperties:!0,description:"JSON Schema object for strict structured output. Non-object roots are rejected."}),G=f.Unsafe({anyOf:[{type:"string",enum:["auto","none","attested","checked","verified","reviewed"]},{type:"boolean",enum:[!1]},{type:"object",additionalProperties:!0}],description:"Optional acceptance policy. Omitted means auto-inferred; verified requires configured runtime commands."}),_=f.Object({maxTurns:f.Integer({minimum:1}),graceTurns:f.Optional(f.Integer({minimum:0}))},{additionalProperties:!1,description:"Optional assistant-turn budget. At maxTurns the child is asked to wrap up; after graceTurns additional assistant turns it is aborted and partial output is returned."}),$=f.Unsafe({anyOf:[{type:"array",minItems:1,items:{type:"string",minLength:1}},{type:"string",enum:["*"]}]}),H=f.Object({soft:f.Optional(f.Integer({minimum:1})),hard:f.Integer({minimum:1}),block:f.Optional($)},{additionalProperties:!1,description:"Optional child tool-call budget. soft nudges the child; after hard, block tools (default read/grep/find/ls, or '*' for all tools) are blocked so the child can finalize."}),g=f.Object({agent:f.String(),task:f.String(),cwd:f.Optional(f.String()),count:f.Optional(f.Integer({minimum:1,description:"Repeat this parallel task N times with the same settings."})),output:f.Optional(K),outputMode:f.Optional(F),reads:f.Optional(M),progress:f.Optional(f.Boolean({description:"Enable progress.md tracking for this task"})),model:f.Optional(f.String({description:"Override model for this task (e.g. 'google/gemini-3-pro')"})),skill:f.Optional(E),toolBudget:f.Optional(H),acceptance:f.Optional(G)}),x=f.Object({agent:f.String(),task:f.Optional(f.String({description:"Task template with {task}, {previous}, {chain_dir} variables. Defaults to {previous}."})),phase:f.Optional(f.String({description:"Optional phase/group label for status and graph rendering."})),label:f.Optional(f.String({description:"Optional user-facing label for this parallel task."})),as:f.Optional(f.String({description:"Optional safe identifier used as {outputs.name} in later chain steps."})),outputSchema:f.Optional(Q),cwd:f.Optional(f.String()),count:f.Optional(f.Integer({minimum:1,description:"Repeat this parallel task N times with the same settings."})),output:f.Optional(K),outputMode:f.Optional(F),reads:f.Optional(M),progress:f.Optional(f.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:f.Optional(E),model:f.Optional(f.String({description:"Override model for this task"})),toolBudget:f.Optional(H),acceptance:f.Optional(G)}),C=f.Object({from:f.Object({output:f.String({description:"Prior named structured output to expand from."}),path:f.String({description:"JSON Pointer into the structured output, e.g. /items."})},{additionalProperties:!1}),item:f.Optional(f.String({description:"Template variable name for each item. Defaults to item."})),key:f.Optional(f.String({description:"JSON Pointer relative to each item for stable child ids."})),maxItems:f.Optional(f.Integer({minimum:0,description:"Required fanout bound unless configured globally."})),onEmpty:f.Optional(f.String({enum:["skip","fail"],description:"Empty input behavior. Defaults to skip."}))},{additionalProperties:!1}),I=f.Object({agent:f.String(),task:f.Optional(f.String({description:"Task template with {item}, {item.path}, {task}, {previous}, {chain_dir}, and {outputs.name} variables."})),phase:f.Optional(f.String({description:"Optional phase/group label for status and graph rendering."})),label:f.Optional(f.String({description:"Optional user-facing label; item templates are supported."})),outputSchema:f.Optional(Q),cwd:f.Optional(f.String()),output:f.Optional(K),outputMode:f.Optional(F),reads:f.Optional(M),progress:f.Optional(f.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:f.Optional(E),model:f.Optional(f.String({description:"Override model for this task"})),toolBudget:f.Optional(H),acceptance:f.Optional(G)},{additionalProperties:!1}),W=f.Object({as:f.String({description:"Safe output name for the ordered collected result array."}),outputSchema:f.Optional(Q)},{additionalProperties:!1}),B=f.Object({agent:f.Optional(f.String({description:"Sequential step agent name"})),task:f.Optional(f.String({description:"Task template with variables: {task}=original request, {previous}=prior step's text response, {chain_dir}=shared folder, {outputs.name}=prior named output. Required for first step, defaults to '{previous}' for subsequent steps."})),phase:f.Optional(f.String({description:"Optional phase/group label for status and graph rendering."})),label:f.Optional(f.String({description:"Optional user-facing label for this chain step."})),as:f.Optional(f.String({description:"Optional safe identifier used as {outputs.name} in later chain steps."})),outputSchema:f.Optional(Q),cwd:f.Optional(f.String()),output:f.Optional(K),outputMode:f.Optional(F),reads:f.Optional(M),progress:f.Optional(f.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:f.Optional(E),model:f.Optional(f.String({description:"Override model for this step"})),toolBudget:f.Optional(H),acceptance:f.Optional(G),parallel:f.Optional(f.Unsafe({anyOf:[f.Array(x,{minItems:1,description:"Tasks to run in parallel"}),I],description:"Static parallel tasks array, or a single dynamic fanout child template when expand/collect are present."})),expand:f.Optional(C),collect:f.Optional(W),concurrency:f.Optional(f.Number({description:"Max concurrent tasks (default: 4)"})),failFast:f.Optional(f.Boolean({description:"Stop on first failure (default: false)"})),worktree:f.Optional(f.Boolean({description:"Create isolated git worktrees for each parallel task."}))},{description:"Chain step: use {agent, task?, ...} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout.",additionalProperties:!1}),L=f.Object({enabled:f.Optional(f.Boolean({description:"Enable/disable subagent control attention tracking for this run"})),needsAttentionAfterMs:f.Optional(f.Integer({minimum:1,description:"No-observed-activity window before a run needs attention"})),activeNoticeAfterMs:f.Optional(f.Integer({minimum:1,description:"Active-long-running notice threshold by elapsed ms (default: 240000)"})),activeNoticeAfterTurns:f.Optional(f.Integer({minimum:1,description:"Optional active-long-running notice threshold by assistant turns (disabled by default)"})),activeNoticeAfterTokens:f.Optional(f.Integer({minimum:1,description:"Optional active-long-running notice threshold by total tokens (disabled by default)"})),failedToolAttemptsBeforeAttention:f.Optional(f.Integer({minimum:1,description:"Consecutive mutating-tool failures before escalating to needs_attention (default: 3)"})),notifyOn:f.Optional(f.Array(f.String({enum:["active_long_running","needs_attention"]}),{description:"Control event types that should notify the parent/orchestrator. Defaults to active_long_running and needs_attention."})),notifyChannels:f.Optional(f.Array(f.String({enum:["event","async","intercom"]}),{description:"Notification channels to use when available. Defaults to event, async, and intercom."}))}),N=f.Object({agent:f.Optional(f.String({description:"Agent name (SINGLE mode) or target for management get/update/delete"})),task:f.Optional(f.String({description:"Task (SINGLE mode, optional for self-contained agents)"})),action:f.Optional(f.String({description:"Management/control action only. Must be omitted for execution mode (single, parallel, or chain)."})),id:f.Optional(f.String({description:"Run id or prefix for action='status', action='interrupt', action='resume', action='steer', or action='append-step'."})),runId:f.Optional(f.String({description:"Target run ID for action='interrupt', action='resume', action='steer', or action='append-step'. Defaults to the most recently active controllable run for interrupt. Prefer id for new calls."})),dir:f.Optional(f.String({description:"Async run directory for action='status', action='resume', or action='steer'."})),index:f.Optional(f.Integer({minimum:0,description:"Zero-based child index for actions that target a specific child or transcript."})),view:f.Optional(f.String({enum:["fleet","transcript"],description:"Optional status view. Use view='fleet' for a read-only active foreground/async fleet surface, or view='transcript' with id/dir (and optional index) to tail a run transcript."})),lines:f.Optional(f.Integer({minimum:1,maximum:500,description:"Maximum transcript lines for action='status', view='transcript'. Defaults to 80."})),message:f.Optional(f.String({description:"Follow-up message for action='resume' or non-terminal guidance for action='steer'. Use index to choose a child from multi-child runs."})),schedule:f.Optional(f.String({description:"Explicit one-shot schedule for action='schedule'. Only honored when scheduledRuns.enabled is true. Use '+10m' or a future ISO timestamp with timezone; scheduled runs always launch async with fresh context."})),scheduleName:f.Optional(f.String({description:"Optional display name for action='schedule'."})),chainName:f.Optional(f.String({description:"Chain name for get/update/delete management actions"})),config:f.Optional(f.Unsafe({anyOf:[{type:"object",additionalProperties:!0},{type:"string"}],description:"Agent/chain config for create/update. Object or JSON string; presence of steps creates a chain."})),tasks:f.Optional(f.Array(g,{description:"PARALLEL mode: [{agent, task, count?, output?, outputMode?, reads?, progress?}, ...]"})),concurrency:f.Optional(f.Integer({minimum:1,description:"Top-level PARALLEL mode only: max concurrent tasks. Defaults to config.parallel.concurrency or 4."})),worktree:f.Optional(f.Boolean({description:"Create isolated git worktrees for parallel tasks; requires clean git state."})),chain:f.Optional(f.Array(B,{description:"CHAIN mode: sequential steps; each result becomes {previous}. append-step takes one tail step and may use {chain_dir}/{outputs.name}."})),context:f.Optional(f.String({enum:["fresh","fork"],description:"'fresh' or 'fork' to branch from parent session. Explicit context overrides every child in the invocation. If omitted, each requested agent uses its own defaultContext; agents without defaultContext: 'fork' run fresh."})),chainDir:f.Optional(f.String({description:"Persistent chain artifact directory; defaults to user-scoped temp storage."})),async:f.Optional(f.Boolean({description:"Run in background (default: false, or per config)"})),timeoutMs:f.Optional(f.Integer({minimum:1,description:"Optional run-level timeout in ms for foreground and async/background runs. Alias of maxRuntimeMs."})),maxRuntimeMs:f.Optional(f.Integer({minimum:1,description:"Alias of timeoutMs for optional run-level timeout in foreground and async/background runs."})),turnBudget:f.Optional(_),toolBudget:f.Optional(H),agentScope:f.Optional(f.String({description:"Agent discovery scope: 'user', 'project', or 'both' (default: 'both'; project wins on name collisions)"})),cwd:f.Optional(f.String()),artifacts:f.Optional(f.Boolean({description:"Write debug artifacts (default: true)"})),includeProgress:f.Optional(f.Boolean({description:"Include full progress in result (default: false)"})),share:f.Optional(f.Boolean({description:"Upload session to GitHub Gist for sharing (default: false)"})),sessionDir:f.Optional(f.String({description:"Directory to store session logs (default: temp; enables sessions even if share=false)"})),clarify:f.Optional(f.Boolean({description:"Show TUI to preview/edit before execution. Explicit clarify: true keeps the run foreground for the clarify UI; omitted clarify can still run in the background when async: true is set."})),control:f.Optional(L),output:f.Optional(f.Unsafe({anyOf:[{type:"string"},{type:"boolean"}],description:"Output file for single agent (string), or false to disable. Relative paths resolve against cwd."})),outputMode:f.Optional(F),skill:f.Optional(E),model:f.Optional(f.String({description:"Override model for single agent (e.g. 'anthropic/claude-sonnet-4')"})),acceptance:f.Optional(G)}),j=V(N),T=f.Object({id:f.Optional(f.String({description:"Run id or prefix to wait for one specific run. Omit to wait across every active async run started in this session."})),all:f.Optional(f.Boolean({description:"Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id targets a single run."})),timeoutMs:f.Optional(f.Integer({minimum:1,description:"Give up waiting after this many milliseconds (the runs keep going regardless). Defaults to 1800000 (30 minutes)."}))}),D=V(T);export{D as WaitParams,j as SubagentParams};
1
+ import{Type as f}from"typebox";function V(q){return X(q,[])}function X(q,R){if(!q||typeof q!=="object")return q;let U=Array.isArray(q)?[]:Object.create(Object.getPrototypeOf(q));for(let w of Reflect.ownKeys(q)){let z=Object.getOwnPropertyDescriptor(q,w);if(!z)continue;if(w==="description"&&!Z(R))continue;if("value"in z){let Y=typeof w==="string"?[...R,w]:R;z.value=X(z.value,Y)}Object.defineProperty(U,w,z)}return U}function Z(q){return q.length===2&&q[0]==="properties"}var E=f.Unsafe({anyOf:[{type:"array",items:{type:"string"}},{type:"boolean"},{type:"string"}],description:"Skill name(s) to make available (comma-separated), array of strings, or boolean (false disables, true uses default)"}),K=f.Unsafe({anyOf:[{type:"string"},{type:"boolean"}],description:"Output filename/path (string), or false to disable file output"}),F=f.String({enum:["inline","file-only"],description:"Return saved output inline (default) or only a concise file reference. file-only requires output to be a path."}),M=f.Unsafe({anyOf:[{type:"array",items:{type:"string"}},{type:"boolean"}],description:"Files to read before running (array of filenames), or false to disable"}),Q=f.Unsafe({type:"object",additionalProperties:!0,description:"JSON Schema object for strict structured output. Non-object roots are rejected."}),G=f.Unsafe({anyOf:[{type:"string",enum:["auto","none","attested","checked","verified","reviewed"]},{type:"boolean",enum:[!1]},{type:"object",additionalProperties:!0}],description:"Optional acceptance policy. Omitted means auto-inferred; verified requires configured runtime commands."}),_=f.Object({maxTurns:f.Integer({minimum:1}),graceTurns:f.Optional(f.Integer({minimum:0}))},{additionalProperties:!1,description:"Optional assistant-turn budget. At maxTurns the child is asked to wrap up; after graceTurns additional assistant turns it is aborted and partial output is returned."}),$=f.Unsafe({anyOf:[{type:"array",minItems:1,items:{type:"string",minLength:1}},{type:"string",enum:["*"]}]}),H=f.Object({soft:f.Optional(f.Integer({minimum:1})),hard:f.Integer({minimum:1}),block:f.Optional($)},{additionalProperties:!1,description:"Optional child tool-call budget. soft nudges the child; after hard, block tools (default read/grep/find/ls, or '*' for all tools) are blocked so the child can finalize."}),g=f.Object({agent:f.String(),task:f.String(),cwd:f.Optional(f.String()),count:f.Optional(f.Integer({minimum:1,description:"Repeat this parallel task N times with the same settings."})),output:f.Optional(K),outputMode:f.Optional(F),reads:f.Optional(M),progress:f.Optional(f.Boolean({description:"Enable progress.md tracking for this task"})),model:f.Optional(f.String({description:"Override model for this task (e.g. 'google/gemini-3-pro')"})),skill:f.Optional(E),toolBudget:f.Optional(H),acceptance:f.Optional(G)}),x=f.Object({agent:f.String(),task:f.Optional(f.String({description:"Task template with {task}, {previous}, {chain_dir} variables. Defaults to {previous}."})),phase:f.Optional(f.String({description:"Optional phase/group label for status and graph rendering."})),label:f.Optional(f.String({description:"Optional user-facing label for this parallel task."})),as:f.Optional(f.String({description:"Optional safe identifier used as {outputs.name} in later chain steps."})),outputSchema:f.Optional(Q),cwd:f.Optional(f.String()),count:f.Optional(f.Integer({minimum:1,description:"Repeat this parallel task N times with the same settings."})),output:f.Optional(K),outputMode:f.Optional(F),reads:f.Optional(M),progress:f.Optional(f.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:f.Optional(E),model:f.Optional(f.String({description:"Override model for this task"})),toolBudget:f.Optional(H),acceptance:f.Optional(G)}),C=f.Object({from:f.Object({output:f.String({description:"Prior named structured output to expand from."}),path:f.String({description:"JSON Pointer into the structured output, e.g. /items."})},{additionalProperties:!1}),item:f.Optional(f.String({description:"Template variable name for each item. Defaults to item."})),key:f.Optional(f.String({description:"JSON Pointer relative to each item for stable child ids."})),maxItems:f.Optional(f.Integer({minimum:0,description:"Required fanout bound unless configured globally."})),onEmpty:f.Optional(f.String({enum:["skip","fail"],description:"Empty input behavior. Defaults to skip."}))},{additionalProperties:!1}),I=f.Object({agent:f.String(),task:f.Optional(f.String({description:"Task template with {item}, {item.path}, {task}, {previous}, {chain_dir}, and {outputs.name} variables."})),phase:f.Optional(f.String({description:"Optional phase/group label for status and graph rendering."})),label:f.Optional(f.String({description:"Optional user-facing label; item templates are supported."})),outputSchema:f.Optional(Q),cwd:f.Optional(f.String()),output:f.Optional(K),outputMode:f.Optional(F),reads:f.Optional(M),progress:f.Optional(f.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:f.Optional(E),model:f.Optional(f.String({description:"Override model for this task"})),toolBudget:f.Optional(H),acceptance:f.Optional(G)},{additionalProperties:!1}),W=f.Object({as:f.String({description:"Safe output name for the ordered collected result array."}),outputSchema:f.Optional(Q)},{additionalProperties:!1}),B=f.Object({agent:f.Optional(f.String({description:"Sequential step agent name"})),task:f.Optional(f.String({description:"Task template with variables: {task}=original request, {previous}=prior step's text response, {chain_dir}=shared folder, {outputs.name}=prior named output. Required for first step, defaults to '{previous}' for subsequent steps."})),phase:f.Optional(f.String({description:"Optional phase/group label for status and graph rendering."})),label:f.Optional(f.String({description:"Optional user-facing label for this chain step."})),as:f.Optional(f.String({description:"Optional safe identifier used as {outputs.name} in later chain steps."})),outputSchema:f.Optional(Q),cwd:f.Optional(f.String()),output:f.Optional(K),outputMode:f.Optional(F),reads:f.Optional(M),progress:f.Optional(f.Boolean({description:"Enable progress.md tracking in {chain_dir}"})),skill:f.Optional(E),model:f.Optional(f.String({description:"Override model for this step"})),toolBudget:f.Optional(H),acceptance:f.Optional(G),parallel:f.Optional(f.Unsafe({anyOf:[f.Array(x,{minItems:1,description:"Tasks to run in parallel"}),I],description:"Static parallel tasks array, or a single dynamic fanout child template when expand/collect are present."})),expand:f.Optional(C),collect:f.Optional(W),concurrency:f.Optional(f.Number({description:"Max concurrent tasks (default: 4)"})),failFast:f.Optional(f.Boolean({description:"Stop on first failure (default: false)"})),worktree:f.Optional(f.Boolean({description:"Create isolated git worktrees for each parallel task."}))},{description:"Chain step: use {agent, task?, ...} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout.",additionalProperties:!1}),L=f.Object({enabled:f.Optional(f.Boolean({description:"Enable/disable subagent control attention tracking for this run"})),needsAttentionAfterMs:f.Optional(f.Integer({minimum:1,description:"No-observed-activity window before a run needs attention"})),activeNoticeAfterMs:f.Optional(f.Integer({minimum:1,description:"Active-long-running notice threshold by elapsed ms (default: 240000)"})),activeNoticeAfterTurns:f.Optional(f.Integer({minimum:1,description:"Optional active-long-running notice threshold by assistant turns (disabled by default)"})),activeNoticeAfterTokens:f.Optional(f.Integer({minimum:1,description:"Optional active-long-running notice threshold by total tokens (disabled by default)"})),failedToolAttemptsBeforeAttention:f.Optional(f.Integer({minimum:1,description:"Consecutive mutating-tool failures before escalating to needs_attention (default: 3)"})),notifyOn:f.Optional(f.Array(f.String({enum:["active_long_running","needs_attention"]}),{description:"Control event types that should notify the parent/orchestrator. Defaults to active_long_running and needs_attention."})),notifyChannels:f.Optional(f.Array(f.String({enum:["event","async","intercom"]}),{description:"Notification channels to use when available. Defaults to event, async, and intercom."}))}),N=f.Object({agent:f.Optional(f.String({description:"Agent name (SINGLE mode) or target for management get/update/delete. For generic SINGLE work, omit agent; task-only execution uses the bundled default."})),task:f.Optional(f.String({description:"Task (SINGLE mode, optional for self-contained agents)"})),action:f.Optional(f.String({description:"Management/control action only. Must be omitted for execution mode (single, parallel, or chain)."})),id:f.Optional(f.String({description:"Run id or prefix for action='status', action='interrupt', action='resume', action='steer', or action='append-step'."})),runId:f.Optional(f.String({description:"Target run ID for action='interrupt', action='resume', action='steer', or action='append-step'. Defaults to the most recently active controllable run for interrupt. Prefer id for new calls."})),dir:f.Optional(f.String({description:"Async run directory for action='status', action='resume', or action='steer'."})),index:f.Optional(f.Integer({minimum:0,description:"Zero-based child index for actions that target a specific child or transcript."})),view:f.Optional(f.String({enum:["fleet","transcript"],description:"Optional status view. Use view='fleet' for a read-only active foreground/async fleet surface, or view='transcript' with id/dir (and optional index) to tail a run transcript."})),lines:f.Optional(f.Integer({minimum:1,maximum:500,description:"Maximum transcript lines for action='status', view='transcript'. Defaults to 80."})),message:f.Optional(f.String({description:"Follow-up message for action='resume' or non-terminal guidance for action='steer'. Use index to choose a child from multi-child runs."})),schedule:f.Optional(f.String({description:"Explicit one-shot schedule for action='schedule'. Only honored when scheduledRuns.enabled is true. Use '+10m' or a future ISO timestamp with timezone; scheduled runs always launch async with fresh context."})),scheduleName:f.Optional(f.String({description:"Optional display name for action='schedule'."})),chainName:f.Optional(f.String({description:"Chain name for get/update/delete management actions"})),config:f.Optional(f.Unsafe({anyOf:[{type:"object",additionalProperties:!0},{type:"string"}],description:"Agent/chain config for create/update. Object or JSON string; presence of steps creates a chain."})),tasks:f.Optional(f.Array(g,{description:"PARALLEL mode: [{agent, task, count?, output?, outputMode?, reads?, progress?}, ...]"})),concurrency:f.Optional(f.Integer({minimum:1,description:"Top-level PARALLEL mode only: max concurrent tasks. Defaults to config.parallel.concurrency or 4."})),worktree:f.Optional(f.Boolean({description:"Create isolated git worktrees for parallel tasks; requires clean git state."})),chain:f.Optional(f.Array(B,{description:"CHAIN mode: sequential steps; each result becomes {previous}. append-step takes one tail step and may use {chain_dir}/{outputs.name}."})),context:f.Optional(f.String({enum:["fresh","fork"],description:"'fresh' or 'fork' to branch from parent session. Explicit context overrides every child in the invocation. If omitted, each requested agent uses its own defaultContext; agents without defaultContext: 'fork' run fresh."})),chainDir:f.Optional(f.String({description:"Persistent chain artifact directory; defaults to user-scoped temp storage."})),async:f.Optional(f.Boolean({description:"Run in background (default: false, or per config)"})),timeoutMs:f.Optional(f.Integer({minimum:1,description:"Optional run-level timeout in ms for foreground and async/background runs. Alias of maxRuntimeMs."})),maxRuntimeMs:f.Optional(f.Integer({minimum:1,description:"Alias of timeoutMs for optional run-level timeout in foreground and async/background runs."})),turnBudget:f.Optional(_),toolBudget:f.Optional(H),agentScope:f.Optional(f.String({description:"Agent discovery scope: 'user', 'project', or 'both' (default: 'both'; project wins on name collisions)"})),cwd:f.Optional(f.String()),artifacts:f.Optional(f.Boolean({description:"Write debug artifacts (default: true)"})),includeProgress:f.Optional(f.Boolean({description:"Include full progress in result (default: false)"})),share:f.Optional(f.Boolean({description:"Upload session to GitHub Gist for sharing (default: false)"})),sessionDir:f.Optional(f.String({description:"Directory to store session logs (default: temp; enables sessions even if share=false)"})),clarify:f.Optional(f.Boolean({description:"Show TUI to preview/edit before execution. Explicit clarify: true keeps the run foreground for the clarify UI; omitted clarify can still run in the background when async: true is set."})),control:f.Optional(L),output:f.Optional(f.Unsafe({anyOf:[{type:"string"},{type:"boolean"}],description:"Output file for single agent (string), or false to disable. Relative paths resolve against cwd."})),outputMode:f.Optional(F),skill:f.Optional(E),model:f.Optional(f.String({description:"Override model for single agent (e.g. 'anthropic/claude-sonnet-4')"})),acceptance:f.Optional(G)}),j=V(N),T=f.Object({id:f.Optional(f.String({description:"Run id or prefix to wait for one specific run. Omit to wait across every active async run started in this session."})),all:f.Optional(f.Boolean({description:"Wait for ALL active runs to finish. Default false: return as soon as the first run finishes, so a fleet manager can spawn a replacement and wait again. Ignored when id targets a single run."})),timeoutMs:f.Optional(f.Integer({minimum:1,description:"Give up waiting after this many milliseconds (the runs keep going regardless). Defaults to 1800000 (30 minutes)."}))}),D=V(T);export{D as WaitParams,j as SubagentParams};
@@ -8,7 +8,7 @@ import*as A from"node:fs";import*as _ from"node:path";import*as W from"node:fs";
8
8
 
9
9
  EXECUTION (use exactly ONE mode):
10
10
  • Before executing, use { action: "list" } to inspect configured agents/chains. Only execute agents listed as executable/non-disabled.
11
- • SINGLE: { agent, task? } - one task; omit task for self-contained agents
11
+ • SINGLE: { agent, task? } - one task; omit task for self-contained agents. For generic work, omit agent when task is present to use the bundled default. Do not invent agent names.
12
12
  • CHAIN: { chain: [{agent:"agent-a"}, {parallel:[{agent:"agent-b",count:3}]}] } - sequential pipeline with optional parallel fan-out
13
13
  • PARALLEL: { tasks: [{agent,task,count?,output?,reads?,progress?}, ...], concurrency?: number, worktree?: true } - concurrent execution (worktree: isolate each task in a git worktree)
14
14
  • Optional context: { context: "fresh" | "fork" } (explicit value overrides every child; when omitted, each requested agent uses its own defaultContext, otherwise "fresh"; inspect agent defaults via { action: "list" })
@@ -57,7 +57,7 @@ ${j}`,O=`Delegate to subagents or manage definitions. Use exactly one mode per c
57
57
 
58
58
  EXECUTE:
59
59
  • Before execution, call { action: "list" }; run only executable/non-disabled configured agents/chains.
60
- • SINGLE {agent, task?}; PARALLEL {tasks:[{agent,task,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{agent,task?},{parallel:[...]}]}.
60
+ • SINGLE {agent, task?}; omit agent for generic task-only calls, and do not invent agent names. PARALLEL {tasks:[{agent,task,count?,output?,reads?,progress?}], concurrency?, worktree?}; CHAIN {chain:[{agent,task?},{parallel:[...]}]}.
61
61
  • context can be "fresh" or "fork"; omitted uses each agent defaultContext, otherwise fresh. timeoutMs/maxRuntimeMs apply to foreground and async/background runs.
62
62
  • Chain templates may use {task}, {previous}, {chain_dir}, and named outputs. Parallel worktree isolation requires a clean git repo.
63
63
  • If list shows proactive skill subagent suggestions, use a small fresh-context fanout only when the task is broad enough.
@@ -1,5 +1,5 @@
1
- import{randomUUID as fj}from"node:crypto";import*as Y from"node:fs";import*as T from"node:path";import{Type as O}from"typebox";import*as L from"node:path";import{fileURLToPath as c}from"node:url";import*as A from"node:os";import*as W from"node:path";import*as _ from"node:os";import*as C from"node:path";function S(j){return j.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function p(j){let $=j?.env??process.env,f=j&&Object.hasOwn(j,"getuid")?j.getuid:process.getuid?.bind(process);if(typeof f==="function")return`uid-${f()}`;for(let Z of["USERNAME","USER","LOGNAME"]){let X=$[Z];if(X)return`user-${S(X)}`}let J=j&&Object.hasOwn(j,"userInfo")?j.userInfo:_.userInfo;try{let Z=J?.().username;if(Z)return`user-${S(Z)}`}catch{}let B=$.USERPROFILE??$.HOME;if(B)return`home-${S(B)}`;let U=j&&Object.hasOwn(j,"homedir")?j.homedir:_.homedir;try{let Z=U?.();if(Z)return`home-${S(Z)}`}catch{}return"shared"}var H=C.join(_.tmpdir(),`dm-subagents-${p()}`),Rj=C.join(H,"async-subagent-results"),Nj=C.join(H,"async-subagent-runs"),l=C.join(H,"chain-runs"),yj=C.join(H,"artifacts");var w=250;var aj=W.join(A.homedir(),".config","mcp","mcp.json"),ej={cursor:[W.join(A.homedir(),".cursor","mcp.json")],"claude-code":[W.join(A.homedir(),".claude","mcp.json"),W.join(A.homedir(),".claude.json"),W.join(A.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[W.join(A.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[W.join(A.homedir(),".codex","config.json")],windsurf:[W.join(A.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as f$}from"typebox/compile";var M$=L.join(L.dirname(c(import.meta.url)),"subagent-prompt-runtime.ts"),_$=L.join(L.dirname(c(import.meta.url)),"..","..","extension","fanout-child.ts");var q="DM_SUBAGENT_ORCHESTRATOR_TARGET",I="DM_SUBAGENT_ORCHESTRATOR_SESSION_ID",x="DM_SUBAGENT_SUPERVISOR_CHANNEL_DIR",v="DM_SUBAGENT_RUN_ID",D="DM_SUBAGENT_CHILD_AGENT",P="DM_SUBAGENT_CHILD_INDEX";import*as t from"node:fs";import*as V from"node:path";var s=[10,25,50,100,200,500,1000,2000,4000],i=new Set(["EACCES","EBUSY","EPERM"]),o=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,k=o?new Int32Array(o):void 0;function a(j){if(j<=0)return;if(k)try{Atomics.wait(k,0,0,j);return}catch{}let $=Date.now()+j;while(Date.now()<$);}function e(j){let $=j?.code;return typeof $==="string"&&i.has($)}function jj(j,$,f,J,B){for(let U=0;;U++)try{j.renameSync($,f);return}catch(Z){let X=J[U];if(X===void 0||!e(Z))throw Z;B(X)}}function $j(j={}){let $=j.fs??t,f=j.now??Date.now,J=j.pid??process.pid,B=j.random??Math.random,Z=j.retryRenameErrors??process.platform==="win32"?j.retryDelaysMs??s:[],X=j.wait??a;return(K,G)=>{$.mkdirSync(V.dirname(K),{recursive:!0});let Q=V.join(V.dirname(K),`.${V.basename(K)}.${J}.${f()}.${B().toString(36).slice(2)}.tmp`);try{$.writeFileSync(Q,JSON.stringify(G,null,2),"utf-8"),jj($,Q,K,Z,X)}finally{$.rmSync(Q,{force:!0})}}}var R=$j();var z=T.join(H,"supervisor-channels"),y="requests",m="replies",E="subagent_supervisor",Jj=65536,Bj=600000,Uj=Math.min(w,500),Zj=O.Object({reason:O.String({enum:["need_decision","interview_request","progress_update"]}),message:O.Optional(O.String()),interview:O.Optional(O.Unsafe({type:"object",additionalProperties:!0}))},{additionalProperties:!1}),g=O.Object({action:O.String({enum:["list","send","ask","reply","pending","status"]}),to:O.Optional(O.String()),message:O.Optional(O.String()),replyTo:O.Optional(O.String())},{additionalProperties:!1});function b(j){return j.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function R$(j,$,f){return T.join(z,`${b(j)}-${b($)}-${f}`)}function Qj(j){Y.mkdirSync(T.join(j,y),{recursive:!0,mode:448}),Y.mkdirSync(T.join(j,m),{recursive:!0,mode:448})}function Xj(j,$){return T.join(j,y,`${b($)}.json`)}function n(j,$){return T.join(j,m,`${b($)}.json`)}function M(j){let $=process.env[j]?.trim();return $?$:void 0}function d(){let j=M(x),$=M(v),f=M(D),J=M(P),B=M(I);if(!j||!$||!f||!B||J===void 0||!/^\d+$/.test(J))return;return{channelDir:j,runId:$,agent:f,childIndex:Number(J),orchestratorTarget:M(q),orchestratorSessionId:B,childTarget:M("DM_SUBAGENT_INTERCOM_SESSION_NAME")}}function Oj(j){if(j==="interview_request")return"Subagent requests a structured supervisor interview.";if(j==="progress_update")return"Subagent progress update.";return"Subagent needs a supervisor decision."}function Yj(j){let $=[Oj(j.reason),`Run: ${j.runId}`,`Agent: ${j.agent}`,`Child index: ${j.childIndex}`];if(j.childTarget)$.push(`Child intercom target: ${j.childTarget}`);if($.push(""),j.message?.trim())$.push(j.message.trim());if(j.reason==="interview_request"){if($.push("","Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape."),j.interview!==void 0)$.push(JSON.stringify(j.interview,null,"\t"))}return $.join(`
2
- `).trimEnd()}function Wj(j){let $=j.trim(),f=$.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)?.[1]?.trim();try{return{value:JSON.parse(f??$)}}catch(J){return{error:J instanceof Error?`${J.name}: ${J.message}`:String(J)}}}function Tj(){let j=Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);return Number.isFinite(j)&&j>0?j:Bj}function Kj(j,$){return new Promise((f,J)=>{if($?.aborted){J(Error("Supervisor request cancelled."));return}let B,U=()=>{if(B)clearTimeout(B);$?.removeEventListener("abort",Z)},Z=()=>{U(),J(Error("Supervisor request cancelled."))};B=setTimeout(()=>{U(),f()},j),$?.addEventListener("abort",Z,{once:!0})})}async function Gj(j,$,f){let J=n(j,$),B=Date.now()+Tj();while(Date.now()<=B){if(f?.aborted)throw Error("Supervisor request cancelled.");if(Y.existsSync(J)){let U=JSON.parse(Y.readFileSync(J,"utf-8"));if(U.type==="subagent.supervisor.reply"&&U.requestId===$&&typeof U.message==="string")return U}await Kj(250,f)}throw Error("Timed out waiting for supervisor reply.")}async function N(j,$){let f=d();if(!f)throw Error("Native supervisor channel is not available for this subagent.");if(j.reason!=="progress_update"&&!j.message?.trim()&&j.reason!=="interview_request")throw Error("message is required for supervisor decisions.");Qj(f.channelDir);let J=fj(),B=j.reason!=="progress_update",U=Yj({...f,reason:j.reason,message:j.message,interview:j.interview}),Z={type:"subagent.supervisor.request",id:J,createdAt:Date.now(),reason:j.reason,message:U,expectsReply:B,...f.orchestratorTarget?{orchestratorTarget:f.orchestratorTarget}:{},...f.orchestratorSessionId?{orchestratorSessionId:f.orchestratorSessionId}:{},runId:f.runId,agent:f.agent,childIndex:f.childIndex,...f.childTarget?{childTarget:f.childTarget}:{},...j.interview!==void 0?{interview:j.interview}:{}},X=JSON.stringify(Z,null,"\t");if(Buffer.byteLength(X,"utf-8")>Jj)throw Error("Supervisor request is too large.");if(R(Xj(f.channelDir,J),Z),!B)return{content:[{type:"text",text:"Supervisor progress update queued."}],details:{delivered:!0,requestId:J,reason:j.reason}};let K=await Gj(f.channelDir,J,$),G={requestId:J,reason:j.reason};if(j.reason==="interview_request"){let Q=Wj(K.message);if(Q.error)G.structuredReplyParseError=Q.error;else G.structuredReply=Q.value}return{content:[{type:"text",text:`**Reply from supervisor:**
3
- ${K.message}`}],details:G}}function F(j,$){try{return j.getAllTools?.().some((f)=>f.name===$)===!0}catch{return!1}}function N$(j,$={}){if(!d())return;let f=$.includeIntercomFallback!==!1;if(!F(j,"contact_supervisor")){let J={name:"contact_supervisor",label:"Contact Supervisor",description:"Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",parameters:Zj,execute(B,U,Z){return N(U,Z)}};j.registerTool(J)}if(f&&!F(j,"intercom")){let J={name:"intercom",label:"Intercom",description:"Native supervisor-channel intercom fallback for subagents. Prefer contact_supervisor when available.",parameters:g,async execute(B,U,Z){let X=U.action;if(X==="status")return{content:[{type:"text",text:"Native supervisor channel is active."}],details:{active:!0}};if(X==="list")return{content:[{type:"text",text:"Supervisor session available through contact_supervisor."}],details:{sessions:[]}};if(X==="send")return N({reason:"progress_update",message:U.message??""},Z);if(X==="ask")return N({reason:"need_decision",message:U.message??""},Z);throw Error("Native child intercom supports status, list, send, and ask. Use parent intercom reply from the supervisor session.")}};j.registerTool(J)}}function Aj(j,$){try{let f=JSON.parse(Y.readFileSync(j,"utf-8"));if(f.type!=="subagent.supervisor.request")return;if(typeof f.id!=="string"||!f.id)return;if(f.reason!=="need_decision"&&f.reason!=="interview_request"&&f.reason!=="progress_update")return;if(typeof f.message!=="string"||!f.message)return;if(typeof f.runId!=="string"||typeof f.agent!=="string"||typeof f.childIndex!=="number")return;return{...f,channelDir:$,requestFile:j}}catch{return}}function Hj(){let j;try{j=Y.readdirSync(z,{withFileTypes:!0})}catch(f){if(f.code==="ENOENT")return[];throw f}let $=[];for(let f of j){if(!f.isDirectory())continue;let J=T.join(z,f.name),B=T.join(J,y),U;try{U=Y.readdirSync(B,{withFileTypes:!0})}catch{continue}for(let Z of U)if(Z.isFile()&&Z.name.endsWith(".json"))$.push({channelDir:J,file:T.join(B,Z.name)})}return $}function Vj(j,$){try{let f=$.sessionManager.getSessionId();if(f)return f}catch{}return j.currentSessionId??void 0}function Mj(j,$,f){let J=Vj($,f);return Boolean(J&&j.orchestratorSessionId===J)}function _j(j){let $=j.expectsReply?` Reply: ${E}({ action: "reply", replyTo: "${j.id}", message: "..." })`:"";return`- ${j.id}: ${j.agent} [${j.runId}#${j.childIndex}] ${j.reason}.${$}`}function Cj(j){let $=[j.message];if(j.expectsReply)$.push("",`Reply with: ${E}({ action: "reply", replyTo: "${j.id}", message: "..." })`);return $.join(`
4
- `)}function Lj(j,$){if(!$.trim())throw Error("message is required for supervisor replies.");let f={type:"subagent.supervisor.reply",requestId:j.id,createdAt:Date.now(),message:$.trim()};R(n(j.channelDir,j.id),f);try{Y.rmSync(j.requestFile,{force:!0})}catch{}}function Sj(j,$){if($.replyTo){let J=j.get($.replyTo);if(!J)throw Error(`No pending supervisor request found for replyTo '${$.replyTo}'.`);return J}let f=[...j.values()].filter((J)=>J.expectsReply);if($.to){let J=$.to.toLowerCase(),B=f.filter((U)=>U.id.toLowerCase().startsWith(J)||U.agent.toLowerCase()===J||U.childTarget?.toLowerCase()===J);if(B.length===1)return B[0];if(B.length>1)throw Error(`Multiple pending supervisor requests match '${$.to}'. Use replyTo.`)}if(f.length===1)return f[0];if(f.length===0)throw Error("No pending supervisor requests need a reply.");throw Error("Multiple pending supervisor requests need replies. Use replyTo.")}function zj(j){return[...j.values()].map(($)=>({id:$.id,runId:$.runId,agent:$.agent,childIndex:$.childIndex,reason:$.reason,expectsReply:$.expectsReply}))}function h(j,$="intercom"){return{name:$,label:$==="intercom"?"Intercom":"Subagent Supervisor",description:$==="intercom"?"Native dm-subagents supervisor channel. Use reply/pending/status to answer child subagent requests.":"Native dm-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding the optional intercom compatibility extension.",parameters:g,async execute(f,J){let B=J;if(B.action==="status")return{content:[{type:"text",text:`Native supervisor channel active. Pending replies: ${j.size}.`}],details:{active:!0,pending:j.size,root:z}};if(B.action==="pending"||B.action==="list"){let U=[...j.values()].filter((Z)=>Z.expectsReply).map(_j);return{content:[{type:"text",text:U.length?U.join(`
5
- `):"No pending supervisor requests."}],details:{pending:zj(j)}}}if(B.action==="reply"){let U=Sj(j,B);return Lj(U,B.message??""),j.delete(U.id),{content:[{type:"text",text:`Replied to supervisor request ${U.id}.`}],details:{replyTo:U.id,runId:U.runId,agent:U.agent}}}if(B.action==="send"||B.action==="ask")throw Error("Native dm-subagents intercom currently handles supervisor replies. Child agents initiate asks with contact_supervisor.");throw Error(`Unsupported intercom action: ${B.action}`)}}}function y$(j,$){let f=new Map,J=new Set,B,U=()=>{if(!F(j,E))j.registerTool(h(f,E));if(!F(j,"intercom"))j.registerTool(h(f))},Z=()=>{let X=$.lastUiContext;if(!X)return;for(let{channelDir:K,file:G}of Hj()){if(J.has(G))continue;let Q=Aj(G,K);if(!Q||!Mj(Q,$,X))continue;if(J.add(G),Q.expectsReply)f.set(Q.id,Q);else try{Y.rmSync(Q.requestFile,{force:!0})}catch{}j.sendMessage({customType:"subagent_supervisor_request",content:Cj(Q),display:!0,details:{id:Q.id,reason:Q.reason,expectsReply:Q.expectsReply,runId:Q.runId,agent:Q.agent,childIndex:Q.childIndex}})}};return{start:()=>{if(B)return;U(),Z(),B=setInterval(Z,Uj),B.unref?.()},dispose:()=>{if(B)clearInterval(B);B=void 0,f.clear(),J.clear()},pending:f}}export{R$ as resolveSupervisorChannelDir,N$ as registerNativeSupervisorClient,Qj as ensureSupervisorChannelDir,y$ as createNativeSupervisorChannel,E as NATIVE_SUPERVISOR_TOOL_NAME};
1
+ import{randomUUID as Bj}from"node:crypto";import*as Y from"node:fs";import*as K from"node:path";import{Type as O}from"typebox";import*as z from"node:fs";import*as T from"node:path";import{fileURLToPath as s}from"node:url";import*as H from"node:os";import*as W from"node:path";import*as C from"node:os";import*as L from"node:path";function b(j){return j.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function l(j){let $=j?.env??process.env,f=j&&Object.hasOwn(j,"getuid")?j.getuid:process.getuid?.bind(process);if(typeof f==="function")return`uid-${f()}`;for(let Q of["USERNAME","USER","LOGNAME"]){let U=$[Q];if(U)return`user-${b(U)}`}let J=j&&Object.hasOwn(j,"userInfo")?j.userInfo:C.userInfo;try{let Q=J?.().username;if(Q)return`user-${b(Q)}`}catch{}let B=$.USERPROFILE??$.HOME;if(B)return`home-${b(B)}`;let Z=j&&Object.hasOwn(j,"homedir")?j.homedir:C.homedir;try{let Q=Z?.();if(Q)return`home-${b(Q)}`}catch{}return"shared"}var V=L.join(C.tmpdir(),`dm-subagents-${l()}`),yj=L.join(V,"async-subagent-results"),wj=L.join(V,"async-subagent-runs"),t=L.join(V,"chain-runs"),cj=L.join(V,"artifacts");var c=250;var j$=W.join(H.homedir(),".config","mcp","mcp.json"),$$={cursor:[W.join(H.homedir(),".cursor","mcp.json")],"claude-code":[W.join(H.homedir(),".claude","mcp.json"),W.join(H.homedir(),".claude.json"),W.join(H.homedir(),".claude","claude_desktop_config.json")],"claude-desktop":[W.join(H.homedir(),"Library","Application Support","Claude","claude_desktop_config.json")],codex:[W.join(H.homedir(),".codex","config.json")],windsurf:[W.join(H.homedir(),".windsurf","mcp.json")],vscode:[".vscode/mcp.json"]};import{Compile as B$}from"typebox/compile";function q(j,$){let f=s(j),J=T.extname(f),B=[".js",".mjs",".cjs",".ts",".mts",".cts"].includes(J)?J:".ts",Z=T.dirname(f);while(!z.existsSync(T.join(Z,"package.json"))){let Q=T.dirname(Z);if(Q===Z)throw Error(`Unable to resolve dm-subagents package root from ${f}`);Z=Q}return T.join(Z,`${$}${B}`)}var C$=q(import.meta.url,T.join("src","runs","shared","subagent-prompt-runtime")),L$=q(import.meta.url,T.join("src","extension","fanout-child"));var I="DM_SUBAGENT_ORCHESTRATOR_TARGET",x="DM_SUBAGENT_ORCHESTRATOR_SESSION_ID",D="DM_SUBAGENT_SUPERVISOR_CHANNEL_DIR",v="DM_SUBAGENT_RUN_ID",P="DM_SUBAGENT_CHILD_AGENT",k="DM_SUBAGENT_CHILD_INDEX";import*as i from"node:fs";import*as M from"node:path";var a=[10,25,50,100,200,500,1000,2000,4000],e=new Set(["EACCES","EBUSY","EPERM"]),o=typeof SharedArrayBuffer<"u"?new SharedArrayBuffer(4):void 0,h=o?new Int32Array(o):void 0;function jj(j){if(j<=0)return;if(h)try{Atomics.wait(h,0,0,j);return}catch{}let $=Date.now()+j;while(Date.now()<$);}function $j(j){let $=j?.code;return typeof $==="string"&&e.has($)}function fj(j,$,f,J,B){for(let Z=0;;Z++)try{j.renameSync($,f);return}catch(Q){let U=J[Z];if(U===void 0||!$j(Q))throw Q;B(U)}}function Jj(j={}){let $=j.fs??i,f=j.now??Date.now,J=j.pid??process.pid,B=j.random??Math.random,Q=j.retryRenameErrors??process.platform==="win32"?j.retryDelaysMs??a:[],U=j.wait??jj;return(G,A)=>{$.mkdirSync(M.dirname(G),{recursive:!0});let X=M.join(M.dirname(G),`.${M.basename(G)}.${J}.${f()}.${B().toString(36).slice(2)}.tmp`);try{$.writeFileSync(X,JSON.stringify(A,null,2),"utf-8"),fj($,X,G,Q,U)}finally{$.rmSync(X,{force:!0})}}}var N=Jj();var E=K.join(V,"supervisor-channels"),w="requests",m="replies",F="subagent_supervisor",Zj=65536,Qj=600000,Xj=Math.min(c,500),Uj=O.Object({reason:O.String({enum:["need_decision","interview_request","progress_update"]}),message:O.Optional(O.String()),interview:O.Optional(O.Unsafe({type:"object",additionalProperties:!0}))},{additionalProperties:!1}),n=O.Object({action:O.String({enum:["list","send","ask","reply","pending","status"]}),to:O.Optional(O.String()),message:O.Optional(O.String()),replyTo:O.Optional(O.String())},{additionalProperties:!1});function S(j){return j.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function y$(j,$,f){return K.join(E,`${S(j)}-${S($)}-${f}`)}function Oj(j){Y.mkdirSync(K.join(j,w),{recursive:!0,mode:448}),Y.mkdirSync(K.join(j,m),{recursive:!0,mode:448})}function Yj(j,$){return K.join(j,w,`${S($)}.json`)}function d(j,$){return K.join(j,m,`${S($)}.json`)}function _(j){let $=process.env[j]?.trim();return $?$:void 0}function u(){let j=_(D),$=_(v),f=_(P),J=_(k),B=_(x);if(!j||!$||!f||!B||J===void 0||!/^\d+$/.test(J))return;return{channelDir:j,runId:$,agent:f,childIndex:Number(J),orchestratorTarget:_(I),orchestratorSessionId:B,childTarget:_("DM_SUBAGENT_INTERCOM_SESSION_NAME")}}function Wj(j){if(j==="interview_request")return"Subagent requests a structured supervisor interview.";if(j==="progress_update")return"Subagent progress update.";return"Subagent needs a supervisor decision."}function Tj(j){let $=[Wj(j.reason),`Run: ${j.runId}`,`Agent: ${j.agent}`,`Child index: ${j.childIndex}`];if(j.childTarget)$.push(`Child intercom target: ${j.childTarget}`);if($.push(""),j.message?.trim())$.push(j.message.trim());if(j.reason==="interview_request"){if($.push("","Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape."),j.interview!==void 0)$.push(JSON.stringify(j.interview,null,"\t"))}return $.join(`
2
+ `).trimEnd()}function Kj(j){let $=j.trim(),f=$.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)?.[1]?.trim();try{return{value:JSON.parse(f??$)}}catch(J){return{error:J instanceof Error?`${J.name}: ${J.message}`:String(J)}}}function Gj(){let j=Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);return Number.isFinite(j)&&j>0?j:Qj}function Aj(j,$){return new Promise((f,J)=>{if($?.aborted){J(Error("Supervisor request cancelled."));return}let B,Z=()=>{if(B)clearTimeout(B);$?.removeEventListener("abort",Q)},Q=()=>{Z(),J(Error("Supervisor request cancelled."))};B=setTimeout(()=>{Z(),f()},j),$?.addEventListener("abort",Q,{once:!0})})}async function Hj(j,$,f){let J=d(j,$),B=Date.now()+Gj();while(Date.now()<=B){if(f?.aborted)throw Error("Supervisor request cancelled.");if(Y.existsSync(J)){let Z=JSON.parse(Y.readFileSync(J,"utf-8"));if(Z.type==="subagent.supervisor.reply"&&Z.requestId===$&&typeof Z.message==="string")return Z}await Aj(250,f)}throw Error("Timed out waiting for supervisor reply.")}async function y(j,$){let f=u();if(!f)throw Error("Native supervisor channel is not available for this subagent.");if(j.reason!=="progress_update"&&!j.message?.trim()&&j.reason!=="interview_request")throw Error("message is required for supervisor decisions.");Oj(f.channelDir);let J=Bj(),B=j.reason!=="progress_update",Z=Tj({...f,reason:j.reason,message:j.message,interview:j.interview}),Q={type:"subagent.supervisor.request",id:J,createdAt:Date.now(),reason:j.reason,message:Z,expectsReply:B,...f.orchestratorTarget?{orchestratorTarget:f.orchestratorTarget}:{},...f.orchestratorSessionId?{orchestratorSessionId:f.orchestratorSessionId}:{},runId:f.runId,agent:f.agent,childIndex:f.childIndex,...f.childTarget?{childTarget:f.childTarget}:{},...j.interview!==void 0?{interview:j.interview}:{}},U=JSON.stringify(Q,null,"\t");if(Buffer.byteLength(U,"utf-8")>Zj)throw Error("Supervisor request is too large.");if(N(Yj(f.channelDir,J),Q),!B)return{content:[{type:"text",text:"Supervisor progress update queued."}],details:{delivered:!0,requestId:J,reason:j.reason}};let G=await Hj(f.channelDir,J,$),A={requestId:J,reason:j.reason};if(j.reason==="interview_request"){let X=Kj(G.message);if(X.error)A.structuredReplyParseError=X.error;else A.structuredReply=X.value}return{content:[{type:"text",text:`**Reply from supervisor:**
3
+ ${G.message}`}],details:A}}function R(j,$){try{return j.getAllTools?.().some((f)=>f.name===$)===!0}catch{return!1}}function w$(j,$={}){if(!u())return;let f=$.includeIntercomFallback!==!1;if(!R(j,"contact_supervisor")){let J={name:"contact_supervisor",label:"Contact Supervisor",description:"Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",parameters:Uj,execute(B,Z,Q){return y(Z,Q)}};j.registerTool(J)}if(f&&!R(j,"intercom")){let J={name:"intercom",label:"Intercom",description:"Native supervisor-channel intercom fallback for subagents. Prefer contact_supervisor when available.",parameters:n,async execute(B,Z,Q){let U=Z.action;if(U==="status")return{content:[{type:"text",text:"Native supervisor channel is active."}],details:{active:!0}};if(U==="list")return{content:[{type:"text",text:"Supervisor session available through contact_supervisor."}],details:{sessions:[]}};if(U==="send")return y({reason:"progress_update",message:Z.message??""},Q);if(U==="ask")return y({reason:"need_decision",message:Z.message??""},Q);throw Error("Native child intercom supports status, list, send, and ask. Use parent intercom reply from the supervisor session.")}};j.registerTool(J)}}function Vj(j,$){try{let f=JSON.parse(Y.readFileSync(j,"utf-8"));if(f.type!=="subagent.supervisor.request")return;if(typeof f.id!=="string"||!f.id)return;if(f.reason!=="need_decision"&&f.reason!=="interview_request"&&f.reason!=="progress_update")return;if(typeof f.message!=="string"||!f.message)return;if(typeof f.runId!=="string"||typeof f.agent!=="string"||typeof f.childIndex!=="number")return;return{...f,channelDir:$,requestFile:j}}catch{return}}function Mj(){let j;try{j=Y.readdirSync(E,{withFileTypes:!0})}catch(f){if(f.code==="ENOENT")return[];throw f}let $=[];for(let f of j){if(!f.isDirectory())continue;let J=K.join(E,f.name),B=K.join(J,w),Z;try{Z=Y.readdirSync(B,{withFileTypes:!0})}catch{continue}for(let Q of Z)if(Q.isFile()&&Q.name.endsWith(".json"))$.push({channelDir:J,file:K.join(B,Q.name)})}return $}function _j(j,$){try{let f=$.sessionManager.getSessionId();if(f)return f}catch{}return j.currentSessionId??void 0}function Cj(j,$,f){let J=_j($,f);return Boolean(J&&j.orchestratorSessionId===J)}function Lj(j){let $=j.expectsReply?` Reply: ${F}({ action: "reply", replyTo: "${j.id}", message: "..." })`:"";return`- ${j.id}: ${j.agent} [${j.runId}#${j.childIndex}] ${j.reason}.${$}`}function zj(j){let $=[j.message];if(j.expectsReply)$.push("",`Reply with: ${F}({ action: "reply", replyTo: "${j.id}", message: "..." })`);return $.join(`
4
+ `)}function bj(j,$){if(!$.trim())throw Error("message is required for supervisor replies.");let f={type:"subagent.supervisor.reply",requestId:j.id,createdAt:Date.now(),message:$.trim()};N(d(j.channelDir,j.id),f);try{Y.rmSync(j.requestFile,{force:!0})}catch{}}function Ej(j,$){if($.replyTo){let J=j.get($.replyTo);if(!J)throw Error(`No pending supervisor request found for replyTo '${$.replyTo}'.`);return J}let f=[...j.values()].filter((J)=>J.expectsReply);if($.to){let J=$.to.toLowerCase(),B=f.filter((Z)=>Z.id.toLowerCase().startsWith(J)||Z.agent.toLowerCase()===J||Z.childTarget?.toLowerCase()===J);if(B.length===1)return B[0];if(B.length>1)throw Error(`Multiple pending supervisor requests match '${$.to}'. Use replyTo.`)}if(f.length===1)return f[0];if(f.length===0)throw Error("No pending supervisor requests need a reply.");throw Error("Multiple pending supervisor requests need replies. Use replyTo.")}function Fj(j){return[...j.values()].map(($)=>({id:$.id,runId:$.runId,agent:$.agent,childIndex:$.childIndex,reason:$.reason,expectsReply:$.expectsReply}))}function g(j,$="intercom"){return{name:$,label:$==="intercom"?"Intercom":"Subagent Supervisor",description:$==="intercom"?"Native dm-subagents supervisor channel. Use reply/pending/status to answer child subagent requests.":"Native dm-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding the optional intercom compatibility extension.",parameters:n,async execute(f,J){let B=J;if(B.action==="status")return{content:[{type:"text",text:`Native supervisor channel active. Pending replies: ${j.size}.`}],details:{active:!0,pending:j.size,root:E}};if(B.action==="pending"||B.action==="list"){let Z=[...j.values()].filter((Q)=>Q.expectsReply).map(Lj);return{content:[{type:"text",text:Z.length?Z.join(`
5
+ `):"No pending supervisor requests."}],details:{pending:Fj(j)}}}if(B.action==="reply"){let Z=Ej(j,B);return bj(Z,B.message??""),j.delete(Z.id),{content:[{type:"text",text:`Replied to supervisor request ${Z.id}.`}],details:{replyTo:Z.id,runId:Z.runId,agent:Z.agent}}}if(B.action==="send"||B.action==="ask")throw Error("Native dm-subagents intercom currently handles supervisor replies. Child agents initiate asks with contact_supervisor.");throw Error(`Unsupported intercom action: ${B.action}`)}}}function c$(j,$){let f=new Map,J=new Set,B,Z=()=>{if(!R(j,F))j.registerTool(g(f,F));if(!R(j,"intercom"))j.registerTool(g(f))},Q=()=>{let U=$.lastUiContext;if(!U)return;for(let{channelDir:G,file:A}of Mj()){if(J.has(A))continue;let X=Vj(A,G);if(!X||!Cj(X,$,U))continue;if(J.add(A),X.expectsReply)f.set(X.id,X);else try{Y.rmSync(X.requestFile,{force:!0})}catch{}j.sendMessage({customType:"subagent_supervisor_request",content:zj(X),display:!0,details:{id:X.id,reason:X.reason,expectsReply:X.expectsReply,runId:X.runId,agent:X.agent,childIndex:X.childIndex}})}};return{start:()=>{if(B)return;Z(),Q(),B=setInterval(Q,Xj),B.unref?.()},dispose:()=>{if(B)clearInterval(B);B=void 0,f.clear(),J.clear()},pending:f}}export{y$ as resolveSupervisorChannelDir,w$ as registerNativeSupervisorClient,Oj as ensureSupervisorChannelDir,c$ as createNativeSupervisorChannel,F as NATIVE_SUPERVISOR_TOOL_NAME};