@pi-ohm/subagents 0.6.4-dev.22597423022.1.b5a2ebf → 0.6.4-dev.22615359904.1.ffd8ea1

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 (2) hide show
  1. package/dist/extension.js +21 -21
  2. package/package.json +4 -4
package/dist/extension.js CHANGED
@@ -1,4 +1,4 @@
1
- import{getSubagentConfiguredModel as e,loadOhmRuntimeConfig as t,registerOhmSettings as n,resolveOhmConfigDir as r,resolveOhmConfigPaths as i}from"@pi-ohm/config";import{Result as a,TaggedError as o}from"better-result";import{getSubagentConfiguredModel as s,getSubagentProfileRuntimeConfig as c,resolveSubagentProfileRuntimeConfig as l,resolveSubagentVariantPattern as u}from"@pi-ohm/config/subagents";import{createSubagentTaskTreeComponent as d,renderSubagentTaskTreeLines as f}from"@pi-ohm/tui";import{Text as p,TruncatedText as m}from"@mariozechner/pi-tui";import{Type as h}from"@sinclair/typebox";import g,{dirname as _,join as ee}from"node:path";import{resolveOhmAgentDataHome as te}from"@pi-ohm/core/paths";import v from"node:fs/promises";import y,{existsSync as ne,mkdirSync as re,readFileSync as ie,renameSync as ae,writeFileSync as oe}from"node:fs";import{fileURLToPath as se}from"node:url";import{spawn as ce}from"node:child_process";import{SessionManager as le,SettingsManager as ue,createAgentSession as de,createBashTool as fe,createEditTool as pe,createExtensionRuntime as me,createReadTool as he,createWriteTool as ge}from"@mariozechner/pi-coding-agent";import _e from"node:os";import{z as b}from"zod";import{Value as ve}from"@sinclair/typebox/value";import{finalizeToolResult as ye,resolveLookupSnapshot as be,toToolRuntimeContext as xe}from"@pi-ohm/core/toolkit";const x=[{id:`librarian`,name:`Librarian`,description:`A specialized codebase understanding agent that helps you answer questions about large, complex codebases. Works by reading from temporary local github checkouts. Works as your personal, multi-repository codebase expert, providing thorough analysis and comprehensive explanations across repositories`,primary:!0,whenToUse:[`Understanding complex multi-repository codebases and how they work`,`Exploring relationships between different repositories`,`Analyzing architectural patterns across large open-source projects`,`Finding specific implementations across multiple codebases`,`Understanding code evolution and commit history`,`Getting comprehensive explanations of how major features work`,`Exploring how systems are designed end-to-end across repositories`],whenNotToUse:[`Simple local file reading (use Read directly)`,`Local codebase searches (use finder)`,`Code modifications or implementations (use other tools)`,`Questions not related to understanding existing repositories`],usageGuidelines:[`1. Be specific about what repositories or projects you want to understand`,`2. Provide context about what you're trying to achieve`,`3. The Librarian will explore thoroughly across repositories before providing comprehensive answers`,`4. Expect detailed, documentation-quality responses suitable for sharing`,`5. When getting an answer from the Librarian, show it to the user in full, do not summarize it`],examples:[`How does authentication work in the Kubernetes codebase?`,`Explain the architecture of the React rendering system`,`Find how database migrations are handled in Rails`,`Understand the plugin system in the VSCode codebase`,`Compare how different web frameworks handle routing`,`What changed in commit abc123 in my private repository?`,`Show me the diff for commit fb492e2 in github.com/mycompany/private-repo`,`Read the README from the main API repo on our Bitbucket Enterprise instance`]},{id:`oracle`,name:`Oracle`,primary:!0,description:`Reasoning-heavy advisor for code review, architecture feedback, complex debugging, and planning.`,whenToUse:[`Code reviews and architecture feedback`,`Finding difficult bugs in codepaths that flow across many files`,`Planning complex implementations or refactors`,`Answering complex technical questions that require deep technical reasoning`,`Providing an alternative point of view when you are struggling to solve a problem`],whenNotToUse:[`File reads or simple keyword searches (use bash tools directly)`,`Codebase searches (use Finder subagent or bash tools directly)`,`Web browsing and searching`,`Basic code modifications and when you need to execute code changes (do it yourself)`],usageGuidelines:[`Be specific about what you want the oracle to review, plan, or debug`,`Provide relevant context about what you're trying to achieve. If you know that 3 files are involved, list them and they will be attached.`]},{id:`finder`,name:`Finder`,primary:!0,description:`Intelligently search your codebase: Use it for complex, multi-step search tasks where you need to find code based on functionality or concepts rather than exact matches. Anytime you want to chain multiple grep calls you should use this tool.`,whenToUse:[`You must locate code by behavior or concept`,`You need to run multiple greps in sequence`,`You must correlate or look for connection between several areas of the codebase`,`You must filter broad terms ("config", "logger", "cache") by context.`,`You need answers to questions such as "Where do we validate JWT authentication headers?" or "Which module handles file-watcher retry logic"`],whenNotToUse:[`When you know the exact file path - use bash tools directly`,`When looking for specific symbols or exact strings`,`When you need to create, modify files, or run terminal commands`],usageGuidelines:[`1. Always spawn multiple search agents in parallel to maximise speed`,`2. Formulate your query as a precise engineering request: Good - Find every place we build an HTTP error response; Bad - error handling search`,`3. Name concrete artifacts, patterns, or APIs to narrow scope (e.g., "Express middleware", "fs.watch debounce")`,`4. State explicit success criteria so the agent knows when to stop (e.g., "Return file paths and line numbers for all JWT verification calls")`,`5. Never issue vague or exploratory commands - be definitive and goal-oriented`]}];function Se(e){let t=e.trim().toLowerCase();return x.find(e=>e.id===t)}function S(e){return e.description&&e.description.trim().length>0?e.description:e.summary&&e.summary.trim().length>0?e.summary:`Subagent profile`}function Ce(e){return e instanceof Error&&e.message.trim().length>0?e.message:typeof e==`string`&&e.trim().length>0?e:String(e)}var we=class extends o(`SubagentValidationError`)(){constructor(e){let t=e.message??(e.cause?`Validation failed (${e.code}): ${Ce(e.cause)}`:`Validation failed (${e.code})`);super({code:e.code,path:e.path,cause:e.cause,meta:e.meta,message:t})}},Te=class extends o(`SubagentPolicyError`)(){constructor(e){let t=e.message??(e.cause?`Policy denied (${e.code}): ${Ce(e.cause)}`:`Policy denied (${e.code})`);super({code:e.code,action:e.action,cause:e.cause,meta:e.meta,message:t})}},C=class extends o(`SubagentRuntimeError`)(){constructor(e){let t=e.message??(e.cause?`Runtime failure (${e.code}): ${Ce(e.cause)}`:`Runtime failure (${e.code})`);super({code:e.code,stage:e.stage,cause:e.cause,meta:e.meta,message:t})}},w=class extends o(`SubagentPersistenceError`)(){constructor(e){let t=e.message??(e.cause?`Persistence failure (${e.code}): ${Ce(e.cause)}`:`Persistence failure (${e.code})`);super({code:e.code,resource:e.resource,cause:e.cause,meta:e.meta,message:t})}};function Ee(e){if(e===`allow`||e===`deny`)return e;if(e===`ask`)return`deny`}function De(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=[];for(let[n,r]of Object.entries(e)){let e=n.trim().toLowerCase();if(e.length===0)continue;let i=Ee(r);i&&t.push([e,i])}return Object.fromEntries(t)}function Oe(e){let t=e.subagents?.permissions;return{defaultDecision:Ee(t?.default)??`allow`,perSubagent:De(t?.subagents),allowInternalRouting:typeof t?.allowInternalRouting==`boolean`?t.allowInternalRouting:!1}}function ke(e,t){let n=Oe(t);return n.perSubagent[e.id]||n.defaultDecision}function Ae(e,t){return e.internal?Oe(t).allowInternalRouting:!0}function je(e,t){let n=Oe(t);if(e.internal&&!n.allowInternalRouting)return a.err(new Te({code:`task_internal_subagent_hidden`,action:`task.invoke`,message:`Subagent '${e.id}' is internal and unavailable by current policy`,meta:{subagentId:e.id,allowInternalRouting:n.allowInternalRouting}}));let r=ke(e,t);return r===`allow`?a.ok(!0):a.err(new Te({code:`task_permission_denied`,action:`task.invoke`,message:`Subagent '${e.id}' is denied by task permission policy`,meta:{subagentId:e.id,decision:r}}))}function Me(e){let t=e.split(/[-_\s]+/u).map(e=>e.trim()).filter(e=>e.length>0);return t.length===0?`Custom Subagent`:t.map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1).toLowerCase()}`).join(` `)}function Ne(e){return[`Use '${e}' for specialized delegated tasks configured in subagents profile.`]}function Pe(e){let t=l({config:e.config,subagentId:e.base.id,modelPattern:e.modelPattern});return t?{...e.base,...t.description?{description:t.description,summary:t.description}:{},...t.whenToUse?{whenToUse:[...t.whenToUse]}:{},...t.prompt?{scaffoldPrompt:t.prompt}:{}}:e.base}function Fe(e){let t=l({config:e.config,subagentId:e.subagentId,modelPattern:e.modelPattern});if(!t)return;let n=e.subagentId.trim().toLowerCase();if(n.length!==0)return{id:n,name:Me(n),description:t.description??`User-defined subagent '${n}' loaded from runtime configuration.`,summary:t.description??`User-defined subagent '${n}' loaded from runtime configuration.`,whenToUse:t.whenToUse??Ne(n),...t.prompt?{scaffoldPrompt:t.prompt}:{}}}function Ie(e){let t=e.subagentId.trim().toLowerCase();if(t.length===0)return;let n=Se(t);if(n){let r=c(e.config,t);return Pe({base:n,config:e.config,modelPattern:e.modelPattern??r?.model})}let r=c(e.config,t);return Fe({subagentId:t,config:e.config,modelPattern:e.modelPattern??r?.model})}function Le(e){let t=x.map(t=>Pe({base:t,config:e,modelPattern:c(e,t.id)?.model})),n=[];for(let t of Object.keys(e.subagents?.profiles??{})){if(Se(t))continue;let r=Fe({subagentId:t,config:e,modelPattern:c(e,t)?.model});r&&n.push(r)}return n.sort((e,t)=>e.id.localeCompare(t.id)),[...t,...n]}function Re(e){let t=process.env[e];if(!t)return;let n=Number.parseInt(t,10);if(!(Number.isNaN(n)||n<=0))return n}function ze(e){if(e===`off`||e===`compact`||e===`verbose`)return e}let Be=ze(process.env.OHM_SUBAGENTS_UI_MODE)??`off`;function Ve(){return Be}function He(e){Be=e}function Ue(e){return ze(e.trim().toLowerCase())}function We(e,t,n,r){if(t===`off`)return;let i=(t===`verbose`?e.widgetEntries:e.compactWidgetEntries).slice(0,Math.max(0,n));if(i.length===0)return;let a=t===`verbose`?{compact:!1}:{compact:!0,maxPromptLines:2**53-1,maxToolCalls:r?2**53-1:2,maxResultLines:2};return{signature:JSON.stringify({mode:t,toolsExpanded:r,entries:i}),entries:i,componentOptions:a}}function Ge(e,t={}){let n=t.key??`ohm-subagents`,r=t.updateIntervalMs??Re(`OHM_SUBAGENTS_UI_UPDATE_MS`)??150,i=t.idleGraceMs??Re(`OHM_SUBAGENTS_UI_IDLE_GRACE_MS`)??2e3,a=t.maxWidgetItems??3,o=t.resolveMode??(()=>t.mode??Ve()),s=t.resolveToolsExpanded??(()=>e.getToolsExpanded?.()??!1),c,l,u,f,p=0,h,g=s(),_,ee=``,te,v=()=>{u&&=(clearTimeout(u),void 0)},y=(t,r)=>{e.setHeader?(te!==t&&(e.setHeader(t===void 0?void 0:()=>new m(t,0,0)),te=t),_!==void 0&&(e.setStatus(n,void 0),_=void 0)):_!==t&&(e.setStatus(n,t),_=t);let i=r?.signature??``;ee!==i&&(e.setWidget(n,r?()=>d({entries:r.entries,options:r.componentOptions}):void 0,{placement:`aboveEditor`}),ee=i)},ne=()=>{if(i<=0){y(void 0,void 0),h=void 0;return}u||=setTimeout(()=>{u=void 0,y(void 0,void 0),h=void 0},i)},re=()=>{l&&=(clearTimeout(l),void 0);let e=c;if(!e)return;c=void 0,p=Date.now();let t=o();if(t===`off`){v(),y(void 0,void 0),h=void 0;return}let n=s();g=n;let r=We(e,t,a,n);if(y(e.statusLine,r),h=e,e.hasActiveTasks){v();return}ne()},ie=()=>{if(l)return;let e=Date.now()-p;if(e>=r){re();return}l=setTimeout(re,r-e)};return f=setInterval(()=>{let e=h;if(!e)return;let t=s();if(t===g)return;g=t;let n=o();if(n===`off`){v(),y(void 0,void 0),h=void 0;return}let r=We(e,n,a,t);y(e.statusLine,r)},Math.max(60,Math.floor(r))),{publish(e){c=e,ie()},clear(){c=void 0,h=void 0,v(),l&&=(clearTimeout(l),void 0),y(void 0,void 0)},dispose(){f&&=(clearInterval(f),void 0),this.clear()}}}const Ke={librarian:{defaultPromptFile:`librarian.general.txt`,variants:{"*gemini*":`librarian.gemini.txt`,"*gpt*":`librarian.gpt.txt`,"*claude*":`librarian.claude.txt`}},oracle:{defaultPromptFile:`oracle.general.txt`,variants:{"*gemini*":`oracle.gemini.txt`,"*gpt*":`oracle.gpt.txt`,"*claude*":`oracle.claude.txt`}},finder:{defaultPromptFile:`finder.general.txt`,variants:{"*gemini*":`finder.gemini.txt`,"*gpt*":`finder.gpt.txt`,"*claude*":`finder.claude.txt`}}};function qe(e){try{return y.statSync(e).isDirectory()}catch{return!1}}function Je(e){try{return y.statSync(e).isFile()}catch{return!1}}function Ye(e){let t=[g.resolve(e,`prompts`)],n=e;for(;;){t.push(g.resolve(n,`src/runtime/backend/prompts`)),t.push(g.resolve(n,`runtime/backend/prompts`));let e=g.dirname(n);if(e===n)break;n=e}for(let e of t)if(qe(e)&&Je(g.join(e,`finder.general.txt`)))return e}function Xe(e){return`{file:${e}}`}function Ze(e){if(!e.baseDir)return;let t=g.join(e.baseDir,e.fileName);if(Je(t))return Xe(t)}function Qe(e){let t=Ke[e.subagentId];if(!t)return;let n=Ye(e.moduleDir??g.dirname(se(import.meta.url))),r=u({variants:Object.fromEntries(Object.keys(t.variants).map(e=>[e,{}])),modelPattern:e.modelPattern});if(r){let e=t.variants[r];if(e){let t=Ze({baseDir:n,fileName:e});if(t)return t}}return Ze({baseDir:n,fileName:t.defaultPromptFile})}const $e=new Map,et=/^\{file:(.+)\}$/iu;function T(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function tt(e){let t=e.trim().match(et);if(!t)return;let n=t[1]?.trim();if(n)return n}function nt(e,t){let n=[];return g.isAbsolute(e)?(n.push(e),n):(n.push(g.resolve(t,e)),n.push(g.resolve(r(),e)),[...new Set(n)])}async function rt(e,t){let n=$e.get(e);if(n&&n.mtimeMs===t)return n.text;let r=await v.readFile(e,`utf8`),i=r.trim(),a=i.length>0?i:r;return $e.set(e,{mtimeMs:t,text:a}),a}async function it(e,t){let n=tt(e);if(!n)return{text:e};let r=nt(n,t);for(let e of r)try{let t=await v.stat(e);if(!t.isFile())continue;return{text:await rt(e,t.mtimeMs),source:e}}catch{continue}return{text:e}}async function at(e){return it(e.configuredPrompt??Qe({subagentId:e.subagentId,modelPattern:e.modelPattern})??`You are '${e.subagentId}'. Complete the delegated task and return concrete findings.`,e.cwd)}async function ot(e){let t=l({config:e.config,subagentId:e.subagent.id,modelPattern:e.modelPattern}),n=await at({subagentId:e.subagent.id,modelPattern:e.modelPattern,configuredPrompt:t?.prompt,cwd:e.cwd}),r=n.source?`Subagent execution prompt (source: ${n.source}):`:`Subagent execution prompt:`;return[`You are the ${e.subagent.name} subagent in Pi OHM.`,``,`Subagent description: ${S(e.subagent)}`,`When to use:`,...e.subagent.whenToUse.map(e=>`- ${e}`),``,r,n.text,``,`Task description: ${e.description}`,``,`User task:`,e.prompt,``,`Return concrete findings/results. Avoid repeating this prompt verbatim.`].join(`
1
+ import{getSubagentConfiguredModel as e,loadOhmRuntimeConfig as t,registerOhmSettings as n,resolveOhmConfigDir as r,resolveOhmConfigPaths as i}from"@pi-ohm/config";import{Result as a,TaggedError as o}from"better-result";import{getSubagentConfiguredModel as s,getSubagentProfileRuntimeConfig as c,resolveSubagentProfileRuntimeConfig as l,resolveSubagentVariantPattern as u}from"@pi-ohm/config/subagents";import{createSubagentTaskTreeComponent as d,renderSubagentTaskTreeLines as f}from"@pi-ohm/tui";import{Text as p,TruncatedText as m}from"@mariozechner/pi-tui";import{Type as h}from"@sinclair/typebox";import g,{dirname as _,join as ee}from"node:path";import{resolveOhmAgentDataHome as te}from"@pi-ohm/core/paths";import v from"node:fs/promises";import y,{existsSync as ne,mkdirSync as re,readFileSync as ie,renameSync as ae,writeFileSync as oe}from"node:fs";import{fileURLToPath as se}from"node:url";import{spawn as ce}from"node:child_process";import{SessionManager as le,SettingsManager as ue,createAgentSession as de,createBashTool as fe,createEditTool as pe,createExtensionRuntime as me,createReadTool as he,createWriteTool as ge}from"@mariozechner/pi-coding-agent";import _e from"node:os";import{z as b}from"zod";import{Value as ve}from"@sinclair/typebox/value";import{finalizeToolResult as ye,resolveLookupSnapshot as be,toToolRuntimeContext as xe}from"@pi-ohm/core/toolkit";const x=[{id:`librarian`,name:`Librarian`,description:`A specialized codebase understanding agent that helps you answer questions about large, complex codebases. Works by reading from temporary local github checkouts. Works as your personal, multi-repository codebase expert, providing thorough analysis and comprehensive explanations across repositories`,primary:!0,whenToUse:[`Understanding complex multi-repository codebases and how they work`,`Exploring relationships between different repositories`,`Analyzing architectural patterns across large open-source projects`,`Finding specific implementations across multiple codebases`,`Understanding code evolution and commit history`,`Getting comprehensive explanations of how major features work`,`Exploring how systems are designed end-to-end across repositories`],whenNotToUse:[`Simple local file reading (use Read directly)`,`Local codebase searches (use finder)`,`Code modifications or implementations (use other tools)`,`Questions not related to understanding existing repositories`],usageGuidelines:[`1. Be specific about what repositories or projects you want to understand`,`2. Provide context about what you're trying to achieve`,`3. The Librarian will explore thoroughly across repositories before providing comprehensive answers`,`4. Expect detailed, documentation-quality responses suitable for sharing`,`5. When getting an answer from the Librarian, show it to the user in full, do not summarize it`],examples:[`How does authentication work in the Kubernetes codebase?`,`Explain the architecture of the React rendering system`,`Find how database migrations are handled in Rails`,`Understand the plugin system in the VSCode codebase`,`Compare how different web frameworks handle routing`,`What changed in commit abc123 in my private repository?`,`Show me the diff for commit fb492e2 in github.com/mycompany/private-repo`,`Read the README from the main API repo on our Bitbucket Enterprise instance`]},{id:`oracle`,name:`Oracle`,primary:!0,description:`Reasoning-heavy advisor for code review, architecture feedback, complex debugging, and planning.`,whenToUse:[`Code reviews and architecture feedback`,`Finding difficult bugs in codepaths that flow across many files`,`Planning complex implementations or refactors`,`Answering complex technical questions that require deep technical reasoning`,`Providing an alternative point of view when you are struggling to solve a problem`],whenNotToUse:[`File reads or simple keyword searches (use bash tools directly)`,`Codebase searches (use Finder subagent or bash tools directly)`,`Web browsing and searching`,`Basic code modifications and when you need to execute code changes (do it yourself)`],usageGuidelines:[`Be specific about what you want the oracle to review, plan, or debug`,`Provide relevant context about what you're trying to achieve. If you know that 3 files are involved, list them and they will be attached.`]},{id:`finder`,name:`Finder`,primary:!0,description:`Intelligently search your codebase: Use it for complex, multi-step search tasks where you need to find code based on functionality or concepts rather than exact matches. Anytime you want to chain multiple grep calls you should use this tool.`,whenToUse:[`You must locate code by behavior or concept`,`You need to run multiple greps in sequence`,`You must correlate or look for connection between several areas of the codebase`,`You must filter broad terms ("config", "logger", "cache") by context.`,`You need answers to questions such as "Where do we validate JWT authentication headers?" or "Which module handles file-watcher retry logic"`],whenNotToUse:[`When you know the exact file path - use bash tools directly`,`When looking for specific symbols or exact strings`,`When you need to create, modify files, or run terminal commands`],usageGuidelines:[`1. Always spawn multiple search agents in parallel to maximise speed`,`2. Formulate your query as a precise engineering request: Good - Find every place we build an HTTP error response; Bad - error handling search`,`3. Name concrete artifacts, patterns, or APIs to narrow scope (e.g., "Express middleware", "fs.watch debounce")`,`4. State explicit success criteria so the agent knows when to stop (e.g., "Return file paths and line numbers for all JWT verification calls")`,`5. Never issue vague or exploratory commands - be definitive and goal-oriented`]}];function Se(e){let t=e.trim().toLowerCase();return x.find(e=>e.id===t)}function S(e){return e.description&&e.description.trim().length>0?e.description:e.summary&&e.summary.trim().length>0?e.summary:`Subagent profile`}function Ce(e){return e instanceof Error&&e.message.trim().length>0?e.message:typeof e==`string`&&e.trim().length>0?e:String(e)}var we=class extends o(`SubagentValidationError`)(){constructor(e){let t=e.message??(e.cause?`Validation failed (${e.code}): ${Ce(e.cause)}`:`Validation failed (${e.code})`);super({code:e.code,path:e.path,cause:e.cause,meta:e.meta,message:t})}},Te=class extends o(`SubagentPolicyError`)(){constructor(e){let t=e.message??(e.cause?`Policy denied (${e.code}): ${Ce(e.cause)}`:`Policy denied (${e.code})`);super({code:e.code,action:e.action,cause:e.cause,meta:e.meta,message:t})}},C=class extends o(`SubagentRuntimeError`)(){constructor(e){let t=e.message??(e.cause?`Runtime failure (${e.code}): ${Ce(e.cause)}`:`Runtime failure (${e.code})`);super({code:e.code,stage:e.stage,cause:e.cause,meta:e.meta,message:t})}},w=class extends o(`SubagentPersistenceError`)(){constructor(e){let t=e.message??(e.cause?`Persistence failure (${e.code}): ${Ce(e.cause)}`:`Persistence failure (${e.code})`);super({code:e.code,resource:e.resource,cause:e.cause,meta:e.meta,message:t})}};function Ee(e){if(e===`allow`||e===`deny`)return e;if(e===`ask`)return`deny`}function De(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=[];for(let[n,r]of Object.entries(e)){let e=n.trim().toLowerCase();if(e.length===0)continue;let i=Ee(r);i&&t.push([e,i])}return Object.fromEntries(t)}function Oe(e){let t=e.subagents?.permissions;return{defaultDecision:Ee(t?.default)??`allow`,perSubagent:De(t?.subagents),allowInternalRouting:typeof t?.allowInternalRouting==`boolean`?t.allowInternalRouting:!1}}function ke(e,t){let n=Oe(t);return n.perSubagent[e.id]||n.defaultDecision}function Ae(e,t){return e.internal?Oe(t).allowInternalRouting:!0}function je(e,t){let n=Oe(t);if(e.internal&&!n.allowInternalRouting)return a.err(new Te({code:`task_internal_subagent_hidden`,action:`task.invoke`,message:`Subagent '${e.id}' is internal and unavailable by current policy`,meta:{subagentId:e.id,allowInternalRouting:n.allowInternalRouting}}));let r=ke(e,t);return r===`allow`?a.ok(!0):a.err(new Te({code:`task_permission_denied`,action:`task.invoke`,message:`Subagent '${e.id}' is denied by task permission policy`,meta:{subagentId:e.id,decision:r}}))}function Me(e){let t=e.split(/[-_\s]+/u).map(e=>e.trim()).filter(e=>e.length>0);return t.length===0?`Custom Subagent`:t.map(e=>`${e.slice(0,1).toUpperCase()}${e.slice(1).toLowerCase()}`).join(` `)}function Ne(e){return[`Use '${e}' for specialized delegated tasks configured in subagents profile.`]}function Pe(e){let t=l({config:e.config,subagentId:e.base.id,modelPattern:e.modelPattern});return t?{...e.base,...t.description?{description:t.description,summary:t.description}:{},...t.whenToUse?{whenToUse:[...t.whenToUse]}:{},...t.prompt?{scaffoldPrompt:t.prompt}:{}}:e.base}function Fe(e){let t=l({config:e.config,subagentId:e.subagentId,modelPattern:e.modelPattern});if(!t)return;let n=e.subagentId.trim().toLowerCase();if(n.length!==0)return{id:n,name:Me(n),description:t.description??`User-defined subagent '${n}' loaded from runtime configuration.`,summary:t.description??`User-defined subagent '${n}' loaded from runtime configuration.`,whenToUse:t.whenToUse??Ne(n),...t.prompt?{scaffoldPrompt:t.prompt}:{}}}function Ie(e){let t=e.subagentId.trim().toLowerCase();if(t.length===0)return;let n=Se(t);if(n){let r=c(e.config,t);return Pe({base:n,config:e.config,modelPattern:e.modelPattern??r?.model})}let r=c(e.config,t);return Fe({subagentId:t,config:e.config,modelPattern:e.modelPattern??r?.model})}function Le(e){let t=x.map(t=>Pe({base:t,config:e,modelPattern:c(e,t.id)?.model})),n=[];for(let t of Object.keys(e.subagents?.profiles??{})){if(Se(t))continue;let r=Fe({subagentId:t,config:e,modelPattern:c(e,t)?.model});r&&n.push(r)}return n.sort((e,t)=>e.id.localeCompare(t.id)),[...t,...n]}function Re(e){let t=process.env[e];if(!t)return;let n=Number.parseInt(t,10);if(!(Number.isNaN(n)||n<=0))return n}function ze(e){if(e===`off`||e===`compact`||e===`verbose`)return e}let Be=ze(process.env.OHM_SUBAGENTS_UI_MODE)??`off`;function Ve(){return Be}function He(e){Be=e}function Ue(e){return ze(e.trim().toLowerCase())}function We(e,t,n,r){if(t===`off`)return;let i=(t===`verbose`?e.widgetEntries:e.compactWidgetEntries).slice(0,Math.max(0,n));if(i.length===0)return;let a=t===`verbose`?{compact:!1}:{compact:!0,maxPromptLines:r?16:2,maxToolCalls:r?2**53-1:2,maxResultLines:2};return{signature:JSON.stringify({mode:t,toolsExpanded:r,entries:i}),entries:i,componentOptions:a}}function Ge(e,t={}){let n=t.key??`ohm-subagents`,r=t.updateIntervalMs??Re(`OHM_SUBAGENTS_UI_UPDATE_MS`)??150,i=t.idleGraceMs??Re(`OHM_SUBAGENTS_UI_IDLE_GRACE_MS`)??2e3,a=t.maxWidgetItems??3,o=t.resolveMode??(()=>t.mode??Ve()),s=t.resolveToolsExpanded??(()=>e.getToolsExpanded?.()??!1),c,l,u,f,p=0,h,g=s(),_,ee=``,te,v=()=>{u&&=(clearTimeout(u),void 0)},y=(t,r)=>{e.setHeader?(te!==t&&(e.setHeader(t===void 0?void 0:()=>new m(t,0,0)),te=t),_!==void 0&&(e.setStatus(n,void 0),_=void 0)):_!==t&&(e.setStatus(n,t),_=t);let i=r?.signature??``;ee!==i&&(e.setWidget(n,r?()=>d({entries:r.entries,options:r.componentOptions}):void 0,{placement:`aboveEditor`}),ee=i)},ne=()=>{if(i<=0){y(void 0,void 0),h=void 0;return}u||=setTimeout(()=>{u=void 0,y(void 0,void 0),h=void 0},i)},re=()=>{l&&=(clearTimeout(l),void 0);let e=c;if(!e)return;c=void 0,p=Date.now();let t=o();if(t===`off`){v(),y(void 0,void 0),h=void 0;return}let n=s();g=n;let r=We(e,t,a,n);if(y(e.statusLine,r),h=e,e.hasActiveTasks){v();return}ne()},ie=()=>{if(l)return;let e=Date.now()-p;if(e>=r){re();return}l=setTimeout(re,r-e)};return f=setInterval(()=>{let e=h;if(!e)return;let t=s();if(t===g)return;g=t;let n=o();if(n===`off`){v(),y(void 0,void 0),h=void 0;return}let r=We(e,n,a,t);y(e.statusLine,r)},Math.max(60,Math.floor(r))),{publish(e){c=e,ie()},clear(){c=void 0,h=void 0,v(),l&&=(clearTimeout(l),void 0),y(void 0,void 0)},dispose(){f&&=(clearInterval(f),void 0),this.clear()}}}const Ke={librarian:{defaultPromptFile:`librarian.general.txt`,variants:{"*gemini*":`librarian.gemini.txt`,"*gpt*":`librarian.gpt.txt`,"*claude*":`librarian.claude.txt`}},oracle:{defaultPromptFile:`oracle.general.txt`,variants:{"*gemini*":`oracle.gemini.txt`,"*gpt*":`oracle.gpt.txt`,"*claude*":`oracle.claude.txt`}},finder:{defaultPromptFile:`finder.general.txt`,variants:{"*gemini*":`finder.gemini.txt`,"*gpt*":`finder.gpt.txt`,"*claude*":`finder.claude.txt`}}};function qe(e){try{return y.statSync(e).isDirectory()}catch{return!1}}function Je(e){try{return y.statSync(e).isFile()}catch{return!1}}function Ye(e){let t=[g.resolve(e,`prompts`)],n=e;for(;;){t.push(g.resolve(n,`src/runtime/backend/prompts`)),t.push(g.resolve(n,`runtime/backend/prompts`));let e=g.dirname(n);if(e===n)break;n=e}for(let e of t)if(qe(e)&&Je(g.join(e,`finder.general.txt`)))return e}function Xe(e){return`{file:${e}}`}function Ze(e){if(!e.baseDir)return;let t=g.join(e.baseDir,e.fileName);if(Je(t))return Xe(t)}function Qe(e){let t=Ke[e.subagentId];if(!t)return;let n=Ye(e.moduleDir??g.dirname(se(import.meta.url))),r=u({variants:Object.fromEntries(Object.keys(t.variants).map(e=>[e,{}])),modelPattern:e.modelPattern});if(r){let e=t.variants[r];if(e){let t=Ze({baseDir:n,fileName:e});if(t)return t}}return Ze({baseDir:n,fileName:t.defaultPromptFile})}const $e=new Map,et=/^\{file:(.+)\}$/iu;function T(e,t){return e.length<=t?e:e.slice(0,t-1)+`…`}function tt(e){let t=e.trim().match(et);if(!t)return;let n=t[1]?.trim();if(n)return n}function nt(e,t){let n=[];return g.isAbsolute(e)?(n.push(e),n):(n.push(g.resolve(t,e)),n.push(g.resolve(r(),e)),[...new Set(n)])}async function rt(e,t){let n=$e.get(e);if(n&&n.mtimeMs===t)return n.text;let r=await v.readFile(e,`utf8`),i=r.trim(),a=i.length>0?i:r;return $e.set(e,{mtimeMs:t,text:a}),a}async function it(e,t){let n=tt(e);if(!n)return{text:e};let r=nt(n,t);for(let e of r)try{let t=await v.stat(e);if(!t.isFile())continue;return{text:await rt(e,t.mtimeMs),source:e}}catch{continue}return{text:e}}async function at(e){return it(e.configuredPrompt??Qe({subagentId:e.subagentId,modelPattern:e.modelPattern})??`You are '${e.subagentId}'. Complete the delegated task and return concrete findings.`,e.cwd)}async function ot(e){let t=l({config:e.config,subagentId:e.subagent.id,modelPattern:e.modelPattern}),n=await at({subagentId:e.subagent.id,modelPattern:e.modelPattern,configuredPrompt:t?.prompt,cwd:e.cwd}),r=n.source?`Subagent execution prompt (source: ${n.source}):`:`Subagent execution prompt:`;return[`You are the ${e.subagent.name} subagent in Pi OHM.`,``,`Subagent description: ${S(e.subagent)}`,`When to use:`,...e.subagent.whenToUse.map(e=>`- ${e}`),``,r,n.text,``,`Task description: ${e.description}`,``,`User task:`,e.prompt,``,`Return concrete findings/results. Avoid repeating this prompt verbatim.`].join(`
2
2
  `)}function st(e){let t=[e.initialPrompt,...e.followUpPrompts].map((e,t)=>`${t+1}. ${e}`).join(`
3
3
  `);return[`You are continuing the ${e.subagent.name} subagent task.`,`Task description: ${e.description}`,``,`Task history:`,t,``,`Latest follow-up request:`,e.prompt,``,`Return only the updated findings/result.`].join(`
4
4
  `)}function ct(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function E(e,t){let n=Reflect.get(e,t);if(typeof n==`string`)return n}function lt(e,t){let n=Reflect.get(e,t);if(typeof n==`boolean`)return n}function ut(e){if(e!==void 0){if(typeof e==`string`){let t=e.trim();return t.length>0?t:void 0}try{let t=JSON.stringify(e);if(!t)return;let n=t.trim();return n.length>0?n:void 0}catch{return e===null?`null`:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:typeof e==`symbol`?e.description?`symbol(${e.description})`:`symbol`:typeof e==`function`?`function`:`(unserializable)`}}}function D(e,t){return{code:`invalid_task_execution_event`,message:t,eventType:e}}function dt(e,t=Date.now()){if(!ct(e))return a.ok(void 0);let n=E(e,`type`);if(!n)return a.ok(void 0);if(n===`message_update`){let r=Reflect.get(e,`assistantMessageEvent`);if(!ct(r))return a.err(D(n,`message_update event is missing assistantMessageEvent`));if(E(r,`type`)!==`text_delta`)return a.ok(void 0);let i=E(r,`delta`);return i===void 0?a.err(D(n,`text_delta event is missing string delta`)):i.length===0?a.ok(void 0):a.ok({type:`assistant_text_delta`,delta:i,atEpochMs:t})}if(n===`tool_execution_start`){let r=E(e,`toolName`),i=E(e,`toolCallId`);return!r||!i?a.err(D(n,`tool_execution_start requires toolName + toolCallId`)):a.ok({type:`tool_start`,toolCallId:i,toolName:r,argsText:ut(Reflect.get(e,`args`)),atEpochMs:t})}if(n===`tool_execution_update`){let r=E(e,`toolName`),i=E(e,`toolCallId`);return!r||!i?a.err(D(n,`tool_execution_update requires toolName + toolCallId`)):a.ok({type:`tool_update`,toolCallId:i,toolName:r,partialText:ut(Reflect.get(e,`partialResult`)),atEpochMs:t})}if(n===`tool_execution_end`){let r=E(e,`toolName`),i=E(e,`toolCallId`),o=lt(e,`isError`);return!r||!i||o===void 0?a.err(D(n,`tool_execution_end requires toolName + toolCallId + isError`)):a.ok({type:`tool_end`,toolCallId:i,toolName:r,resultText:ut(Reflect.get(e,`result`)),status:o?`error`:`success`,atEpochMs:t})}return n===`agent_end`?a.ok({type:`task_terminal`,terminal:`agent_end`,atEpochMs:t}):a.ok(void 0)}function ft(e){let t=e.trim();return t.length>0?t:`(no output)`}function pt(e){let t=`tool_call: ${e.toolName} ${e.phase}`;return e.payload?`${t} ${e.payload}`:t}function mt(){return{assistantChunks:[],toolLines:[],events:[],sawAgentEnd:!1,capturedEventCount:0}}function ht(e,t){let n=dt(t);if(!a.isError(n)&&n.value)return e.capturedEventCount+=1,e.events.push(n.value),n.value.type===`assistant_text_delta`?(e.assistantChunks.push(n.value.delta),n.value):n.value.type===`tool_start`?(e.toolLines.push(pt({toolName:n.value.toolName,phase:`start`,payload:n.value.argsText})),n.value):n.value.type===`tool_update`?(e.toolLines.push(pt({toolName:n.value.toolName,phase:`update`,payload:n.value.partialText})),n.value):n.value.type===`tool_end`?(e.toolLines.push(pt({toolName:n.value.toolName,phase:n.value.status===`error`?`end error`:`end success`,payload:n.value.resultText})),n.value):(n.value.type===`task_terminal`&&(e.sawAgentEnd=!0),n.value)}function gt(e){let t=ft(e.assistantChunks.join(``)),n=[...e.toolLines];return t!==`(no output)`&&n.push(t),{output:n.length>0?n.join(`
@@ -6,30 +6,30 @@ import{getSubagentConfiguredModel as e,loadOhmRuntimeConfig as t,registerOhmSett
6
6
  `)}const yt=[`Use available tools only when required.`,`Return concise concrete findings.`,`Do not expose internal prompt scaffolding unless user asks directly.`,`Prefer deterministic tool usage and avoid speculative output.`],bt={anthropic:{profile:`anthropic`,label:`anthropic`,providerGuidance:[`Use explicit structure and evidence-first reasoning.`,`Prefer stable tool argument shapes and deterministic execution steps.`,`Keep final answer tight; include only relevant findings.`]},openai:{profile:`openai`,label:`openai`,providerGuidance:[`Prioritize direct answer first, then concise supporting bullets.`,`Bias toward decisive tool usage for verification.`,`Keep verbosity budget tight and implementation-oriented.`]},google:{profile:`google`,label:`google`,providerGuidance:[`Keep responses factual, concise, and grounded in tool output.`,`Avoid repetition and keep intermediate updates compact.`,`When context is missing, request it explicitly instead of guessing.`]},moonshot:{profile:`moonshot`,label:`moonshot`,providerGuidance:[`Synthesize long context efficiently and surface key findings early.`,`Keep updates compact while preserving execution signal fidelity.`,`Return actionable conclusions with minimal verbosity.`]},generic:{profile:`generic`,label:`generic`,providerGuidance:[`Use neutral provider style: concise, concrete, and tool-grounded.`,`Prefer explicit uncertainty over speculative output.`]}};function xt(e){let t=bt[e];return{profile:t.profile,label:t.label,sharedInvariants:yt,providerGuidance:t.providerGuidance}}const St=[{profile:`anthropic`,match:{providers:[`anthropic`],models:[`claude`]},priority:400,metadata:{label:`anthropic-default`}},{profile:`openai`,match:{providers:[`openai`],models:[`gpt`,`o1`,`o3`,`o4`]},priority:300,metadata:{label:`openai-default`}},{profile:`google`,match:{providers:[`google`],models:[`gemini`]},priority:200,metadata:{label:`google-default`}},{profile:`moonshot`,match:{providers:[`moonshot`,`moonshotai`,`moonshot.ai`],models:[`kimi`]},priority:100,metadata:{label:`moonshot-default`}}],Ct=new Set([`off`,`minimal`,`low`,`medium`,`high`,`xhigh`]);function O(e){return e?e.trim().toLowerCase():``}function wt(e){let t=e.trim();if(t.length===0)return``;let n=t.lastIndexOf(`:`);if(n<=0||n>=t.length-1)return t;let r=O(t.slice(n+1));return Ct.has(r)?t.slice(0,n).trim():t}function Tt(e){let t=O(e);if(t.length===0)return;let n=t.indexOf(`/`);if(n<=0||n>=t.length-1)return;let r=t.slice(0,n),i=O(wt(t.slice(n+1)));if(!(r.length===0||i.length===0))return{provider:r,modelId:i}}function Et(e){let t=O(e.provider),n=O(wt(e.modelId??``));if(!(t.length===0||n.length===0))return{provider:t,modelId:n}}function Dt(e,t){return!e||!t?!1:e.provider===t.provider&&e.modelId===t.modelId}function Ot(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function kt(e){return e===`anthropic`||e===`openai`||e===`google`||e===`moonshot`||e===`generic`}function At(e){let t=[];for(let n of e){let e=O(n);e.length!==0&&(t.includes(e)||t.push(e))}return t}function jt(e){if(!kt(e.profile)||e.profile===`generic`)return;let t=At(e.match.providers),n=At(e.match.models);if(t.length===0&&n.length===0)return;let r=Number.isFinite(e.priority)?Math.trunc(e.priority):0;return{profile:e.profile,match:{providers:t,models:n},priority:r,metadata:e.metadata}}function Mt(e){let t=(e&&e.length>0?e:St).map(e=>jt(e)).filter(e=>e!==void 0).sort((e,t)=>t.priority-e.priority);return t.length>0?t:St}function Nt(e){return!!(Ot(e.provider,e.rule.match.providers)||Ot(e.modelId,e.rule.match.models)||Ot(e.providerOrModel,e.rule.match.providers)||Ot(e.providerOrModel,e.rule.match.models))}function k(e,t,n){let r=`${e} ${t}`.trim();for(let i of n)if(Nt({provider:e,modelId:t,providerOrModel:r,rule:i}))return i.profile;return`generic`}function Pt(e){return new Set(e.filter(e=>e!==`generic`)).size>1}function Ft(e){let t=e.filter(e=>e!==`generic`);if(t.length===0||Pt(t))return`generic`;let[n]=t;return n||`generic`}function It(e){if(e.scopedModels.length===0)return{profile:`generic`,reason:`scoped_no_match`};let t=e.scopedModels.find(t=>t.provider===e.candidate.provider&&t.modelId===e.candidate.modelId);if(t){let n=k(t.provider,t.modelId,e.profileRules);if(n!==`generic`)return{profile:n,reason:`scoped_exact_match`}}let n=e.scopedModels.filter(t=>t.modelId===e.candidate.modelId).map(t=>k(t.provider,t.modelId,e.profileRules)),r=Ft(n);if(r!==`generic`)return{profile:r,reason:`scoped_model_consensus`};let i=e.scopedModels.filter(t=>t.provider===e.candidate.provider).map(t=>k(t.provider,t.modelId,e.profileRules)),a=Ft(i);return a===`generic`?{profile:`generic`,reason:Pt(n)||Pt(i)?`scoped_conflict`:`scoped_no_match`}:{profile:a,reason:`scoped_provider_consensus`}}function Lt(e,t){if(t===`scoped_exact_match`)return e===`active_model`?`active_model_scoped_exact_match`:`explicit_model_pattern_scoped_exact_match`;if(t===`scoped_model_consensus`)return e===`active_model`?`active_model_scoped_model_consensus`:`explicit_model_pattern_scoped_model_consensus`;if(t===`scoped_provider_consensus`)return e===`active_model`?`active_model_scoped_provider_consensus`:`explicit_model_pattern_scoped_provider_consensus`}function Rt(e){let t=Mt(e.profileRules),n=Et({provider:e.provider,modelId:e.modelId}),r=Tt(e.modelPattern);if(n){let e=k(n.provider,n.modelId,t);if(e!==`generic`)return{profile:e,source:`active_model`,reason:`active_model_direct_match`}}if(r){let e=k(r.provider,r.modelId,t);if(e!==`generic`)return{profile:e,source:`explicit_model_pattern`,reason:`explicit_model_pattern_direct_match`}}let i=e.scopedModels??[],a=!1;if(n){let e=It({candidate:n,scopedModels:i,profileRules:t}),r=Lt(`active_model`,e.reason);if(e.profile!==`generic`&&r)return{profile:e.profile,source:`scoped_model_catalog`,reason:r};e.reason===`scoped_conflict`&&(a=!0)}if(r&&!Dt(n,r)){let e=It({candidate:r,scopedModels:i,profileRules:t}),n=Lt(`explicit_model_pattern`,e.reason);if(e.profile!==`generic`&&n)return{profile:e.profile,source:`scoped_model_catalog`,reason:n};e.reason===`scoped_conflict`&&(a=!0)}return!n&&!r?{profile:`generic`,source:`generic_fallback`,reason:`no_active_model_or_explicit_pattern`}:i.length===0?{profile:`generic`,source:`generic_fallback`,reason:`no_scoped_models_available`}:a?{profile:`generic`,source:`generic_fallback`,reason:`scoped_models_conflict`}:{profile:`generic`,source:`generic_fallback`,reason:`no_profile_match`}}function zt(e){let t=xt(Rt(e).profile);return vt({runtimeLabel:`Pi OHM subagent runtime`,providerProfileLabel:t.label,sharedConstraints:t.sharedInvariants,providerGuidance:t.providerGuidance})}const Bt=new Map;function A(e){return typeof e==`object`&&!!e}function Vt(){return St.map(e=>({profile:e.profile,match:{providers:[...e.match.providers],models:[...e.match.models]},priority:e.priority,metadata:e.metadata?{...e.metadata}:void 0}))}function Ht(e){return e.trim().toLowerCase()}function Ut(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=Ht(n);e.length!==0&&(t.includes(e)||t.push(e))}return t}function Wt(e){if(!A(e))return;let t=e.label,n=e.notes,r=typeof t==`string`?t.trim():``,i=typeof n==`string`?n.trim():``,a=r.length>0?r:void 0,o=i.length>0?i:void 0;if(!(!a&&!o))return{...a?{label:a}:{},...o?{notes:o}:{}}}function Gt(e){return typeof e!=`number`||!Number.isFinite(e)?0:Math.trunc(e)}function Kt(e,t,n){if(!A(e)){t.push(`promptProfiles.rules[${n}] must be an object.`);return}let r=e.profile;if(!kt(r)||r===`generic`){t.push(`promptProfiles.rules[${n}] has invalid profile '${String(r)}'. Expected anthropic|openai|google|moonshot.`);return}let i=e.match;if(!A(i)){t.push(`promptProfiles.rules[${n}] match must be an object.`);return}let a=Ut(i.providers),o=Ut(i.models);if(!a||!o){t.push(`promptProfiles.rules[${n}] match.providers and match.models must be string arrays.`);return}if(a.length===0&&o.length===0){t.push(`promptProfiles.rules[${n}] must include at least one provider or model token.`);return}return{profile:r,match:{providers:a,models:o},priority:Gt(e.priority),metadata:Wt(e.metadata)}}function qt(e){let t=[];if(!Array.isArray(e))return t.push(`subagents.promptProfiles.rules must be an array.`),{rules:[],diagnostics:t};let n=[];for(let[r,i]of e.entries()){let e=Kt(i,t,r);e&&n.push(e)}return n.sort((e,t)=>t.priority-e.priority),{rules:n,diagnostics:t}}function Jt(e){if(!A(e))return{rules:[],diagnostics:[`providers config must be a top-level object.`]};let t=e.subagents;if(!A(t))return{rules:[],diagnostics:[]};let n=t.promptProfiles;return A(n)?qt(n.rules):{rules:[],diagnostics:[]}}async function Yt(e){try{let t=await v.stat(e);return t.isFile()?t.mtimeMs:void 0}catch{return}}async function Xt(e,t){let n=Bt.get(e);if(n&&n.mtimeMs===t)return n.parsed;try{let n=await v.readFile(e,`utf8`),r=Jt(JSON.parse(n)),i=r.diagnostics.map(t=>`${e}: ${t}`),a=r.rules.length>0?{rules:r.rules,diagnostics:i,sourcePath:e}:{rules:Vt(),diagnostics:[...i,`${e}: no valid prompt profile rules found; using defaults.`],sourcePath:e};return Bt.set(e,{mtimeMs:t,parsed:a}),a}catch(n){let r=n instanceof Error&&n.message.trim().length>0?n.message.trim():`invalid JSON`,i={rules:Vt(),diagnostics:[`${e}: ${r}`,`${e}: using default prompt profile rules.`],sourcePath:e};return Bt.set(e,{mtimeMs:t,parsed:i}),i}}async function Zt(e){let t=i(e).providersConfigFile,n=await Yt(t);return n===void 0?{rules:Vt(),diagnostics:[]}:Xt(t,n)}const Qt=`settings.json`,$t=new Set([`off`,`minimal`,`low`,`medium`,`high`,`xhigh`]),en=new Map;function tn(e){return typeof e==`object`&&!!e}function nn(e){return e.trim().toLowerCase()}function rn(e){let t=e.trim();if(t.length===0)return``;let n=t.lastIndexOf(`:`);if(n<=0||n>=t.length-1)return t;let r=nn(t.slice(n+1));return $t.has(r)?t.slice(0,n).trim():t}function an(e){let t=e.trim();if(t.length===0)return;let n=t.indexOf(`/`);if(n<=0||n>=t.length-1)return;let r=nn(t.slice(0,n)),i=nn(rn(t.slice(n+1).trim()));if(!(r.length===0||i.length===0))return{provider:r,modelId:i,pattern:`${r}/${i}`}}function on(e){return e===`~`?_e.homedir():e.startsWith(`~/`)?g.join(_e.homedir(),e.slice(2)):e}function sn(e){if(!e)return;let t=e.trim();if(t.length!==0)return on(t)}function cn(e){return g.join(e,Qt)}function j(e,t,n,r){r&&(t.has(r)||(t.add(r),e.push({source:n,filePath:r})))}function ln(e){let t=[],n=new Set;j(t,n,`project_local`,g.join(e,`.pi`,`agent`,Qt));let i=sn(process.env.PI_CONFIG_DIR),a=sn(process.env.PI_CODING_AGENT_DIR),o=sn(process.env.PI_AGENT_DIR);return j(t,n,`env_pi_config_dir`,i?cn(i):void 0),j(t,n,`env_pi_coding_agent_dir`,a?cn(a):void 0),j(t,n,`env_pi_agent_dir`,o?cn(o):void 0),j(t,n,`resolved_agent_dir`,cn(r())),j(t,n,`home_default`,g.join(_e.homedir(),`.pi`,`agent`,Qt)),t}async function un(e){try{let t=await v.stat(e);return t.isFile()?t.mtimeMs:void 0}catch{return}}function dn(e){if(e===void 0)return[];if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)continue;let e=an(r);if(!e)continue;let i=`${e.provider}/${e.modelId}`;n.has(i)||(n.add(i),t.push(e))}return t}async function fn(e,t){let n=en.get(e);if(n&&n.mtimeMs===t)return n.parsed;try{let n=await v.readFile(e,`utf8`),r=JSON.parse(n);if(!tn(r)){let n={ok:!1,message:`Settings file must contain a top-level JSON object.`};return en.set(e,{mtimeMs:t,parsed:n}),n}let i=dn(r.enabledModels);if(!i){let n={ok:!1,message:`Settings file field 'enabledModels' must be a string array when present.`};return en.set(e,{mtimeMs:t,parsed:n}),n}let a={ok:!0,models:i};return en.set(e,{mtimeMs:t,parsed:a}),a}catch(n){let r={ok:!1,message:n instanceof Error&&n.message.trim().length>0?n.message.trim():`invalid JSON`};return en.set(e,{mtimeMs:t,parsed:r}),r}}async function pn(e){let t=[],n=ln(e);for(let e of n){let n=await un(e.filePath);if(n===void 0)continue;let r=await fn(e.filePath,n);if(!r.ok){t.push(`${e.filePath}: ${r.message}`);continue}return r.models.length===0&&t.push(`${e.filePath}: no valid enabledModels entries found.`),{models:r.models,sourcePath:e.filePath,source:e.source,diagnostics:t}}return{models:[],diagnostics:t}}function mn(e){let t=e.trim();if(t.length===0)return;let n=t.indexOf(`/`);if(n<=0||n>=t.length-1)return;let r=t.slice(0,n).trim().toLowerCase(),i=t.slice(n+1).trim();if(!(r.length===0||i.length===0))return{provider:r,modelId:i}}function hn(e){return e===`off`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`}function gn(e){let t=mn(e.modelPattern);if(!t)return{ok:!1,reason:`invalid_format`,message:`Invalid subagent model '${e.modelPattern}'. Expected '<provider>/<model>' or '<provider>/<model>:<thinking>'.`};let n=t.modelId;if(e.hasModel(t.provider,n))return{ok:!0,value:{provider:t.provider,modelId:n}};let r=n.lastIndexOf(`:`);if(r<=0||r>=n.length-1)return{ok:!1,reason:`model_not_found`,message:`Configured subagent model '${e.modelPattern}' was not found.`};let i=n.slice(r+1).trim().toLowerCase();if(!hn(i))return{ok:!1,reason:`invalid_thinking_level`,message:`Invalid subagent thinking level '${i}' in '${e.modelPattern}'.`};let a=n.slice(0,r).trim();return a.length===0?{ok:!1,reason:`invalid_format`,message:`Invalid subagent model '${e.modelPattern}'. Expected '<provider>/<model>' or '<provider>/<model>:<thinking>'.`}:e.hasModel(t.provider,a)?{ok:!0,value:{provider:t.provider,modelId:a,thinkingLevel:i}}:{ok:!1,reason:`model_not_found`,message:`Configured subagent model '${e.modelPattern}' was not found.`}}function _n(e,t){let n=e.trim();if(n.length>0)return n;let r=t.trim();return r.length>0?r:`(no output)`}function vn(e){let t=e.split(/\r?\n/u),n=[],r=`unavailable`,i=`unavailable`,a=`pi-cli`;for(let e of t){let t=e.match(/^\s*(backend|provider|model|runtime|route)\s*:\s*(.+)\s*$/iu);if(!t){n.push(e);continue}let o=t[1]?.toLowerCase(),s=t[2]?.trim()??``;if(s.length!==0){if(o===`provider`){r=s;continue}if(o===`model`){i=s;continue}if(o===`runtime`||o===`backend`){a=s;continue}}}let o=n.join(`
7
7
  `).trim();return{output:o.length>0?o:`(no output)`,provider:r,model:i,runtime:a}}const yn=`pi-sdk`,M=`interactive-sdk`,N=`interactive-shell`;function bn(e){let t=me();return{getExtensions:()=>({extensions:[],errors:[],runtime:t}),getSkills:()=>({skills:[],diagnostics:[]}),getPrompts:()=>({prompts:[],diagnostics:[]}),getThemes:()=>({themes:[],diagnostics:[]}),getAgentsFiles:()=>({agentsFiles:[]}),getSystemPrompt:()=>e,getAppendSystemPrompt:()=>[],getPathMetadata:()=>new Map,extendResources:()=>{},reload:async()=>{}}}function xn(e){let t=e.trim();return t.length>0?t:`(no output)`}function Sn(e){let t=e.trim();if(t.length===0)return;let n=t.indexOf(`/`);if(n<=0||n>=t.length-1)return;let r=t.slice(0,n).trim().toLowerCase(),i=t.slice(n+1).trim();if(!(r.length===0||i.length===0))return{provider:r,modelId:i}}function Cn(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:`unknown backend error`}if(typeof e==`string`){let t=e.trim();return t.length>0?t:`unknown backend error`}return`unknown backend error`}async function wn(e){try{await e.abort()}catch{}}const Tn=async e=>{if(e.signal?.aborted)return{output:``,events:[],timedOut:!1,aborted:!0};let t=mt(),n=!1,r=!1,i,a,o=`unavailable`,s=`unavailable`,c=`generic`,l=`generic_fallback`,u=`no_profile_match`,d=await pn(e.cwd),f=await Zt(e.cwd);try{let t=zt({modelPattern:e.modelPattern,scopedModels:d.models,profileRules:f.rules});a=(await de({cwd:e.cwd,resourceLoader:bn(t),tools:[he(e.cwd),fe(e.cwd),pe(e.cwd),ge(e.cwd)],sessionManager:le.inMemory(),settingsManager:ue.inMemory({compaction:{enabled:!1},retry:{enabled:!1}})})).session;let n=a;if(e.modelPattern){let t=gn({modelPattern:e.modelPattern,hasModel:(e,t)=>n.modelRegistry.find(e,t)!==void 0});if(!t.ok){let r=Sn(e.modelPattern),i=r?n.modelRegistry.getAll().filter(e=>e.provider===r.provider).map(e=>e.id).slice(0,8):[],a=t.reason===`model_not_found`&&i.length>0?` Available for '${r?.provider??``}': ${i.join(`, `)}.`:``;return n.dispose(),{output:``,events:[],timedOut:!1,aborted:!1,error:`${t.message}${a}`}}let r=n.modelRegistry.find(t.value.provider,t.value.modelId);if(!r)return n.dispose(),{output:``,events:[],timedOut:!1,aborted:!1,error:`Configured subagent model '${e.modelPattern}' was not found.`};await n.setModel(r),t.value.thinkingLevel&&n.setThinkingLevel(t.value.thinkingLevel),o=r.provider,s=r.id}let r=n.model;r&&(o=r.provider,s=r.id),n.agent.setSystemPrompt(zt({provider:o,modelId:s,modelPattern:e.modelPattern,scopedModels:d.models,profileRules:f.rules}));let i=Rt({provider:o,modelId:s,modelPattern:e.modelPattern,scopedModels:d.models,profileRules:f.rules});c=i.profile,l=i.source,u=i.reason,e.onObservability?.({provider:o,model:s,runtime:yn,route:M,promptProfile:c,promptProfileSource:l,promptProfileReason:u})}catch(e){return{output:``,events:[],timedOut:!1,aborted:!1,error:Cn(e)}}if(!a)return{output:``,events:[],timedOut:!1,aborted:!1,error:`Failed to create subagent sdk session`};let p=a.subscribe(n=>{let r=ht(t,n);r&&e.onEvent?.(r)}),m,h=()=>{r=!0,wn(a)};e.signal&&e.signal.addEventListener(`abort`,h,{once:!0}),m=setTimeout(()=>{n=!0,wn(a)},e.timeoutMs);try{await a.prompt(e.prompt)}catch(e){i=Cn(e)}finally{clearTimeout(m),e.signal&&e.signal.removeEventListener(`abort`,h),p(),a.dispose()}if(r||e.signal?.aborted)return{output:``,events:[...t.events],timedOut:!1,aborted:!0};if(n)return{output:``,events:[...t.events],timedOut:!0,aborted:!1};if(i)return{output:``,events:[...t.events],timedOut:!1,aborted:!1,error:i};let g=gt(t);return{output:g.output,events:g.events,provider:o,model:s,runtime:yn,promptProfile:c,promptProfileSource:l,promptProfileReason:u,timedOut:!1,aborted:!1}},En=async e=>e.signal?.aborted?{exitCode:130,stdout:``,stderr:``,timedOut:!1,aborted:!0}:new Promise(t=>{let n=[`--print`,`--no-session`,`--no-extensions`,`--tools`,`read,bash,edit,write,grep,find,ls`];e.modelPattern&&n.push(`--model`,e.modelPattern),n.push(e.prompt);let r=ce(`pi`,n,{cwd:e.cwd,shell:!1,stdio:[`ignore`,`pipe`,`pipe`]}),i=``,a=``,o=!1,s=!1,c=!1,l=setTimeout(()=>{o=!0,r.kill(`SIGTERM`),setTimeout(()=>{r.killed||r.kill(`SIGKILL`)},1e3)},e.timeoutMs),u=n=>{c||(c=!0,clearTimeout(l),e.signal&&e.signal.removeEventListener(`abort`,d),t(n))},d=()=>{s=!0,r.kill(`SIGTERM`),setTimeout(()=>{r.killed||r.kill(`SIGKILL`)},1e3)};e.signal&&e.signal.addEventListener(`abort`,d,{once:!0}),r.stdout.on(`data`,e=>{i+=e.toString()}),r.stderr.on(`data`,e=>{a+=e.toString()}),r.on(`error`,e=>{let t=`${a}\n${e.message}`.trim();u({exitCode:1,stdout:i,stderr:t,timedOut:o,aborted:s})}),r.on(`close`,e=>{u({exitCode:typeof e==`number`?e:1,stdout:i,stderr:a,timedOut:o,aborted:s})})});function Dn(e){if(!e)return;let t=Number.parseInt(e,10);if(!(!Number.isFinite(t)||t<=0))return t}function On(){return Dn(process.env.OHM_SUBAGENTS_BACKEND_TIMEOUT_MS)??18e4}function kn(e){let t=`OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_${e.trim().toUpperCase()}`;return Dn(process.env[t])}function An(e){let t=kn(e.subagent.id);if(t!==void 0)return t;let n=On(),r=n>0?n:e.fallbackTimeoutMs;return e.subagent.id===`librarian`?Math.max(r,3e5):e.subagent.id===`oracle`?Math.max(r,36e5):r}function jn(e){let t=s(e.config,e.subagent.id);return l({config:e.config,subagentId:e.subagent.id,modelPattern:t})?.model??t}function Mn(e,t){return new C({code:`task_aborted`,stage:t,message:`Task ${e} was aborted before execution`,meta:{taskId:e}})}function Nn(e){let t=Math.max(1,Math.round(e.timeoutMs/1e3)),n=e.modelPattern?` (model: ${e.modelPattern})`:``,r=e.subagentId===`oracle`?`Narrow oracle task scope/context/files or raise OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_ORACLE.`:`Narrow task scope or raise OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_${e.subagentId.toUpperCase()} (or OHM_SUBAGENTS_BACKEND_TIMEOUT_MS).`;return new C({code:`task_backend_timeout`,stage:e.stage,message:`Task ${e.taskId} timed out after ${t}s while waiting for '${e.subagentId}' backend response${n}. ${r}`,meta:{taskId:e.taskId,timeoutMs:e.timeoutMs,timeoutSeconds:t,subagentId:e.subagentId,modelPattern:e.modelPattern}})}function Pn(e){let t=e.stderr.trim(),n=t.length>0?T(t,260):`subagent backend exited non-zero`;return new C({code:`task_backend_execution_failed`,stage:e.stage,message:`Task ${e.taskId} backend failed: ${n}`,meta:{taskId:e.taskId,exitCode:e.exitCode,stderr:t}})}var Fn=class{id=`interactive-sdk`;constructor(e=Tn,t=On()){this.runner=e,this.timeoutMs=t}resolveBackendId(e){return e.subagentBackend===`none`?`scaffold`:e.subagentBackend===`custom-plugin`?`custom-plugin`:this.id}async executeStart(e){if(e.signal?.aborted)return a.err(Mn(e.taskId,`execute_start`));let t=jn({config:e.config,subagent:e.subagent}),n=An({fallbackTimeoutMs:this.timeoutMs,subagent:e.subagent}),r=await this.runner({cwd:e.cwd,prompt:await ot({...e,modelPattern:t}),modelPattern:t,signal:e.signal,timeoutMs:n,onEvent:e.onEvent,onObservability:e.onObservability});if(r.aborted||e.signal?.aborted)return a.err(Mn(e.taskId,`execute_start`));if(r.timedOut)return a.err(Nn({taskId:e.taskId,stage:`execute_start`,timeoutMs:n,subagentId:e.subagent.id,modelPattern:t}));if(r.error)return a.err(Pn({taskId:e.taskId,stage:`execute_start`,exitCode:1,stderr:r.error}));let i=`${e.subagent.name}: ${T(e.description,72)}`;return a.ok({summary:i,output:xn(r.output),provider:r.provider??`unavailable`,model:r.model??`unavailable`,runtime:r.runtime??yn,route:M,...r.promptProfile?{promptProfile:r.promptProfile}:{},...r.promptProfileSource?{promptProfileSource:r.promptProfileSource}:{},...r.promptProfileReason?{promptProfileReason:r.promptProfileReason}:{},events:r.events})}async executeSend(e){if(e.signal?.aborted)return a.err(Mn(e.taskId,`execute_send`));let t=jn({config:e.config,subagent:e.subagent}),n=An({fallbackTimeoutMs:this.timeoutMs,subagent:e.subagent}),r=await this.runner({cwd:e.cwd,prompt:st(e),modelPattern:t,signal:e.signal,timeoutMs:n,onEvent:e.onEvent,onObservability:e.onObservability});if(r.aborted||e.signal?.aborted)return a.err(Mn(e.taskId,`execute_send`));if(r.timedOut)return a.err(Nn({taskId:e.taskId,stage:`execute_send`,timeoutMs:n,subagentId:e.subagent.id,modelPattern:t}));if(r.error)return a.err(Pn({taskId:e.taskId,stage:`execute_send`,exitCode:1,stderr:r.error}));let i=`${e.subagent.name} follow-up: ${T(e.prompt,72)}`;return a.ok({summary:i,output:xn(r.output),provider:r.provider??`unavailable`,model:r.model??`unavailable`,runtime:r.runtime??yn,route:M,...r.promptProfile?{promptProfile:r.promptProfile}:{},...r.promptProfileSource?{promptProfileSource:r.promptProfileSource}:{},...r.promptProfileReason?{promptProfileReason:r.promptProfileReason}:{},events:r.events})}},In=class{id=`scaffold`;async executeStart(e){if(e.signal?.aborted)return a.err(new C({code:`task_aborted`,stage:`execute_start`,message:`Task execution aborted before start`}));let t=`${e.subagent.name}: ${T(e.description,72)}`,n=[`subagent: ${e.subagent.id}`,`backend: ${this.id}`,`mode: ${e.config.defaultMode}`,`description: ${e.description}`,`prompt: ${e.prompt}`].join(`
8
8
  `);return a.ok({summary:t,output:n,provider:`unavailable`,model:`unavailable`,runtime:this.id,route:this.id})}async executeSend(e){if(e.signal?.aborted)return a.err(new C({code:`task_aborted`,stage:`execute_send`,message:`Task execution aborted before send`}));let t=`${e.subagent.name} follow-up: ${T(e.prompt,72)}`,n=[`subagent: ${e.subagent.id}`,`backend: ${this.id}`,`mode: ${e.config.defaultMode}`,`description: ${e.description}`,`initial_prompt: ${e.initialPrompt}`,`follow_up_prompt: ${e.prompt}`,`follow_up_count: ${e.followUpPrompts.length}`].join(`
9
- `);return a.ok({summary:t,output:n,provider:`unavailable`,model:`unavailable`,runtime:this.id,route:this.id})}};function Ln(e){if(!e)return;let t=Number.parseInt(e,10);if(!(!Number.isFinite(t)||t<=0))return t}function Rn(){return Ln(process.env.OHM_SUBAGENTS_BACKEND_TIMEOUT_MS)??18e4}function zn(e){let t=`OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_${e.trim().toUpperCase()}`;return Ln(process.env[t])}function Bn(e){let t=zn(e.subagent.id);if(t!==void 0)return t;let n=Rn(),r=n>0?n:e.fallbackTimeoutMs;return e.subagent.id===`librarian`?Math.max(r,3e5):e.subagent.id===`oracle`?Math.max(r,36e5):r}function Vn(){let e=process.env.OHM_SUBAGENTS_SDK_FALLBACK_TO_CLI;if(!e)return!1;let t=e.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}function Hn(e,t){return new C({code:`task_aborted`,stage:t,message:`Task ${e} was aborted before execution`,meta:{taskId:e}})}function Un(e,t){return new C({code:`unsupported_subagent_backend`,stage:t,message:`Configured subagent backend is not implemented in @pi-ohm/subagents`,meta:{taskId:e,backend:`custom-plugin`}})}function Wn(e){let t=Math.max(1,Math.round(e.timeoutMs/1e3)),n=e.modelPattern?` (model: ${e.modelPattern})`:``,r=e.subagentId===`oracle`?`Narrow oracle task scope/context/files or raise OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_ORACLE.`:`Narrow task scope or raise OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_${e.subagentId.toUpperCase()} (or OHM_SUBAGENTS_BACKEND_TIMEOUT_MS).`;return new C({code:`task_backend_timeout`,stage:e.stage,message:`Task ${e.taskId} timed out after ${t}s while waiting for '${e.subagentId}' backend response${n}. ${r}`,meta:{taskId:e.taskId,timeoutMs:e.timeoutMs,timeoutSeconds:t,subagentId:e.subagentId,modelPattern:e.modelPattern}})}function Gn(e){let t=e.stderr.trim(),n=t.length>0?T(t,260):`subagent backend exited non-zero`;return new C({code:`task_backend_execution_failed`,stage:e.stage,message:`Task ${e.taskId} backend failed: ${n}`,meta:{taskId:e.taskId,exitCode:e.exitCode,stderr:t}})}function Kn(e){let t=s(e.config,e.subagent.id);return l({config:e.config,subagentId:e.subagent.id,modelPattern:t})?.model??t}function qn(e){if(!e)return;let t=e.trim();if(t.length===0)return;let n=t.indexOf(`/`);if(n<=0||n>=t.length-1)return;let r=t.slice(0,n).trim().toLowerCase(),i=t.slice(n+1).trim().toLowerCase(),a=i.endsWith(`:off`)||i.endsWith(`:minimal`)||i.endsWith(`:low`)||i.endsWith(`:medium`)||i.endsWith(`:high`)||i.endsWith(`:xhigh`)?i.slice(0,i.lastIndexOf(`:`)):i;if(!(r.length===0||a.length===0))return{provider:r,model:a}}var Jn=class{id=M;scaffoldBackend=new In;constructor(e=En,t=Rn(),n=new Fn){this.runner=e,this.timeoutMs=t,this.sdkBackend=n}resolveBackendId(e){return e.subagentBackend===`none`?this.scaffoldBackend.id:e.subagentBackend===`interactive-shell`?N:e.subagentBackend===`interactive-sdk`?M:e.subagentBackend===`custom-plugin`?`custom-plugin`:this.id}shouldFallbackToCli(e){return!(!Vn()||e.code!==`task_backend_execution_failed`)}async executeCliStart(e){let t=Kn({config:e.config,subagent:e.subagent}),n=Bn({fallbackTimeoutMs:this.timeoutMs,subagent:e.subagent}),r=qn(t);e.onObservability?.({provider:r?.provider??`unavailable`,model:r?.model??`unavailable`,runtime:`pi-cli`,route:N});let i=await this.runner({cwd:e.cwd,prompt:await ot({...e,modelPattern:t}),modelPattern:t,signal:e.signal,timeoutMs:n});if(i.aborted||e.signal?.aborted)return a.err(Hn(e.taskId,`execute_start`));if(i.timedOut)return a.err(Wn({taskId:e.taskId,stage:`execute_start`,timeoutMs:n,subagentId:e.subagent.id,modelPattern:t}));if(i.exitCode!==0)return a.err(Gn({taskId:e.taskId,stage:`execute_start`,exitCode:i.exitCode,stderr:i.stderr}));let o=vn(_n(i.stdout,i.stderr)),s=`${e.subagent.name}: ${T(e.description,72)}`;return a.ok({summary:s,output:o.output,provider:o.provider,model:o.model,runtime:o.runtime,route:N})}async executeCliSend(e){let t=Kn({config:e.config,subagent:e.subagent}),n=Bn({fallbackTimeoutMs:this.timeoutMs,subagent:e.subagent}),r=qn(t);e.onObservability?.({provider:r?.provider??`unavailable`,model:r?.model??`unavailable`,runtime:`pi-cli`,route:N});let i=await this.runner({cwd:e.cwd,prompt:st(e),modelPattern:t,signal:e.signal,timeoutMs:n});if(i.aborted||e.signal?.aborted)return a.err(Hn(e.taskId,`execute_send`));if(i.timedOut)return a.err(Wn({taskId:e.taskId,stage:`execute_send`,timeoutMs:n,subagentId:e.subagent.id,modelPattern:t}));if(i.exitCode!==0)return a.err(Gn({taskId:e.taskId,stage:`execute_send`,exitCode:i.exitCode,stderr:i.stderr}));let o=vn(_n(i.stdout,i.stderr)),s=`${e.subagent.name} follow-up: ${T(e.prompt,72)}`;return a.ok({summary:s,output:o.output,provider:o.provider,model:o.model,runtime:o.runtime,route:N})}async executeStart(e){if(e.signal?.aborted)return a.err(Hn(e.taskId,`execute_start`));if(e.config.subagentBackend===`none`)return this.scaffoldBackend.executeStart(e);if(e.config.subagentBackend===`custom-plugin`)return a.err(Un(e.taskId,`execute_start`));if(e.config.subagentBackend===`interactive-shell`)return this.executeCliStart(e);if(e.config.subagentBackend===`interactive-sdk`){let t=await this.sdkBackend.executeStart(e);return a.isOk(t)||!this.shouldFallbackToCli(t.error)?t:this.executeCliStart(e)}let t=await this.sdkBackend.executeStart(e);return a.isOk(t)||!this.shouldFallbackToCli(t.error)?t:this.executeCliStart(e)}async executeSend(e){if(e.signal?.aborted)return a.err(Hn(e.taskId,`execute_send`));if(e.config.subagentBackend===`none`)return this.scaffoldBackend.executeSend(e);if(e.config.subagentBackend===`custom-plugin`)return a.err(Un(e.taskId,`execute_send`));if(e.config.subagentBackend===`interactive-shell`)return this.executeCliSend(e);if(e.config.subagentBackend===`interactive-sdk`){let t=await this.sdkBackend.executeSend(e);return a.isOk(t)||!this.shouldFallbackToCli(t.error)?t:this.executeCliSend(e)}let t=await this.sdkBackend.executeSend(e);return a.isOk(t)||!this.shouldFallbackToCli(t.error)?t:this.executeCliSend(e)}};function Yn(){return new Jn}const Xn=b.core.version.major;function Zn(){return Xn===4?a.ok(!0):a.err(new C({code:`unsupported_zod_major`,stage:`schema`,message:`Expected Zod v4 but found v`+String(Xn),meta:{detectedMajor:Xn}}))}function Qn(e,t,n,r){return new we({code:e,path:n,message:n?`${t}: ${n}`:t,cause:r})}function $n(e){let[t]=e;if(t&&t.path.length!==0)return t.path.map(e=>e.toString()).filter(e=>e.length>0).join(`.`)}function er(e){if(!e||e.length===0)return;let t=e.replace(/^\//u,``).replaceAll(`/`,`.`);if(t.length!==0)return t}const tr=b.strictObject({id:b.string().trim().min(1),subagentType:b.string().trim().min(1),description:b.string().trim().min(1),prompt:b.string().trim().min(1),totalToolCalls:b.int().nonnegative(),activeToolCalls:b.int().nonnegative(),startedAtEpochMs:b.int().nonnegative(),updatedAtEpochMs:b.int().nonnegative()}),nr=tr.extend({state:b.enum([`queued`,`running`]),endedAtEpochMs:b.undefined().optional(),lastErrorCode:b.undefined().optional(),lastErrorMessage:b.undefined().optional()}),rr=tr.extend({state:b.enum([`succeeded`,`failed`,`cancelled`]),endedAtEpochMs:b.int().nonnegative(),lastErrorCode:b.string().trim().min(1).optional(),lastErrorMessage:b.string().trim().min(1).optional()}).superRefine((e,t)=>{e.activeToolCalls!==0&&t.addIssue({code:`custom`,message:`Terminal task records must have activeToolCalls = 0`,path:[`activeToolCalls`]}),e.endedAtEpochMs<e.startedAtEpochMs&&t.addIssue({code:`custom`,message:`endedAtEpochMs must be >= startedAtEpochMs`,path:[`endedAtEpochMs`]}),e.state===`failed`&&!e.lastErrorMessage&&t.addIssue({code:`custom`,message:`Failed task records require lastErrorMessage`,path:[`lastErrorMessage`]})}),ir=b.discriminatedUnion(`state`,[nr,rr]);function ar(e){let t=Zn();if(a.isError(t))return t;let n=ir.safeParse(e);if(n.success)return a.ok(n.data);let r=$n(n.error.issues);return a.err(Qn(`invalid_task_record`,`Task record failed validation`,r,n.error))}function or(e){return typeof e==`object`&&!!e}function sr(e){if(e===`task-routed`||e===`primary-tool`)return e}function P(e){if(typeof e==`string`&&e.trim().length!==0)return e}function F(e){if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)return t}function cr(e){if(typeof e==`number`&&Number.isFinite(e)&&!(e<0))return e}function lr(e){if(!or(e))return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted task event must be an object`}));let t=F(e.type);if(!t)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted task event missing type`}));let n=cr(e.atEpochMs);if(n===void 0)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted task event missing valid atEpochMs`}));if(t===`assistant_text_delta`){let r=F(e.delta);return r?a.ok({type:t,delta:r,atEpochMs:n}):a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`assistant_text_delta event missing delta`}))}if(t===`tool_start`){let r=F(e.toolCallId),i=F(e.toolName);return!r||!i?a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`tool_start event missing toolCallId/toolName`})):a.ok({type:t,toolCallId:r,toolName:i,argsText:P(e.argsText),atEpochMs:n})}if(t===`tool_update`){let r=F(e.toolCallId),i=F(e.toolName);return!r||!i?a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`tool_update event missing toolCallId/toolName`})):a.ok({type:t,toolCallId:r,toolName:i,partialText:P(e.partialText),atEpochMs:n})}if(t===`tool_end`){let r=F(e.toolCallId),i=F(e.toolName),o=e.status;return!r||!i||o!==`success`&&o!==`error`?a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`tool_end event missing fields or invalid status`})):a.ok({type:t,toolCallId:r,toolName:i,resultText:P(e.resultText),status:o,atEpochMs:n})}return t===`task_terminal`?e.terminal===`agent_end`?a.ok({type:t,terminal:`agent_end`,atEpochMs:n}):a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`task_terminal event has invalid terminal marker`})):a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Unsupported persisted task event type '${t}'`}))}function ur(e,t){return e.length<=t?[...e]:e.slice(e.length-t)}function dr(e,t){if(e===void 0)return a.ok([]);if(!Array.isArray(e))return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted task events must be an array`}));let n=[];for(let t of e){let e=lr(t);if(a.isError(e))return e;n.push(e.value)}return a.ok(ur(n,t))}function fr(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n.trim();e.length!==0&&t.push(e)}return t}function pr(e,t){return{provider:t?.provider??`unavailable`,model:t?.model??`unavailable`,runtime:t?.runtime??e,route:t?.route??e,promptProfile:t?.promptProfile,promptProfileSource:t?.promptProfileSource,promptProfileReason:t?.promptProfileReason}}function mr(e,t){if(!or(e))return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry must be an object`}));let n=P(e.summary);if(!n)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry missing non-empty summary`}));let r=P(e.backend);if(!r)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry missing non-empty backend`}));let i=sr(e.invocation);if(!i)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry has invalid invocation mode`}));let o=ar(e.record);if(a.isError(o))return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry has invalid task record`,cause:o.error}));let s=dr(e.events,t);return a.isError(s)?a.err(s.error):a.ok({record:o.value,summary:n,backend:r,...pr(r,{provider:P(e.provider),model:P(e.model),runtime:P(e.runtime),route:P(e.route),promptProfile:P(e.promptProfile),promptProfileSource:P(e.promptProfileSource),promptProfileReason:P(e.promptProfileReason)}),invocation:i,output:P(e.output),errorCode:P(e.errorCode),errorMessage:P(e.errorMessage),followUpPrompts:fr(e.followUpPrompts),events:s.value})}function hr(e,t){if(!or(e))return a.err(new w({code:`task_persistence_invalid_shape`,resource:`task-registry`,message:`Task persistence file must contain an object root`}));if(e.schemaVersion!==1)return a.err(new w({code:`task_persistence_invalid_schema_version`,resource:`task-registry`,message:`Task persistence schema version mismatch. Expected 1.`}));if(!Array.isArray(e.entries))return a.err(new w({code:`task_persistence_invalid_shape`,resource:`task-registry`,message:`Task persistence snapshot missing 'entries' array`}));let n=[];for(let r of e.entries){let e=mr(r,t);if(a.isError(e))return a.err(new w({code:`task_persistence_entry_invalid`,resource:`task-registry`,message:e.error.message,cause:e.error}));n.push(e.value)}return a.ok(n)}function gr(e,t){let n=`${e}.corrupt-${t()}`,r=a.try({try:()=>ae(e,n),catch:()=>void 0});if(!a.isError(r))return n}function _r(e){return{filePath:e,load(){if(!ne(e))return a.ok({entries:[]});let t=a.try({try:()=>ie(e,`utf8`),catch:t=>new w({code:`task_persistence_read_failed`,resource:e,message:`Failed reading task registry at ${e}`,cause:t})});if(a.isError(t))return t;let n=a.try({try:()=>JSON.parse(t.value),catch:()=>void 0});if(a.isError(n)||n.value===void 0)return a.ok({entries:[],recoveredCorruptFilePath:gr(e,Date.now)});let r=hr(n.value,2**53-1);return a.isError(r)?a.ok({entries:[],recoveredCorruptFilePath:gr(e,Date.now)}):a.ok({entries:r.value})},save(t){let n=a.try({try:()=>(re(_(e),{recursive:!0}),oe(e,`${JSON.stringify(t,null,2)}\n`,`utf8`),!0),catch:t=>new w({code:`task_persistence_write_failed`,resource:e,message:`Failed writing task registry at ${e}`,cause:t})});return a.isError(n)?n:a.ok(!0)}}}function vr(e,t){return e===`queued`?t===`running`||t===`cancelled`:e===`running`?t===`succeeded`||t===`failed`||t===`cancelled`:!1}function I(e){return e===`succeeded`||e===`failed`||e===`cancelled`}function yr(e,t){return new C({code:`task_record_validation_failed`,stage:`task_runtime_store`,message:`Invalid task record for '${e}'`,cause:t,meta:{taskId:e}})}function br(e){return new C({code:`unknown_task_id`,stage:`task_runtime_store`,message:`Unknown task id '${e}'`,meta:{taskId:e}})}function xr(e,t){return new C({code:`task_expired`,stage:`task_runtime_store`,message:t,meta:{taskId:e}})}function Sr(e,t,n){return new C({code:`illegal_task_state_transition`,stage:`task_runtime_store`,message:`Illegal task transition for '${e}': ${t} -> ${n}`,meta:{taskId:e,from:t,to:n}})}function Cr(e,t){return new C({code:`task_not_resumable`,stage:`task_runtime_store`,message:`Task '${e}' is terminal (${t}) and cannot be resumed`,meta:{taskId:e,state:t}})}function wr(e,t){return new C({code:`task_not_running`,stage:`task_runtime_store`,message:`Task '${e}' is '${t}' and cannot complete follow-up interaction`,meta:{taskId:e,state:t}})}function L(e){return{id:e.record.id,state:e.record.state,subagentType:e.record.subagentType,description:e.record.description,prompt:e.record.prompt,followUpPrompts:e.followUpPrompts,summary:e.summary,output:e.output,backend:e.backend,provider:e.provider,model:e.model,runtime:e.runtime,route:e.route,...e.promptProfile?{promptProfile:e.promptProfile}:{},...e.promptProfileSource?{promptProfileSource:e.promptProfileSource}:{},...e.promptProfileReason?{promptProfileReason:e.promptProfileReason}:{},invocation:e.invocation,totalToolCalls:e.record.totalToolCalls,activeToolCalls:e.record.activeToolCalls,startedAtEpochMs:e.record.startedAtEpochMs,updatedAtEpochMs:e.record.updatedAtEpochMs,endedAtEpochMs:e.record.endedAtEpochMs,errorCode:e.errorCode,errorMessage:e.errorMessage,events:e.events}}function Tr(e){let t=Math.max(e.record.startedAtEpochMs,e.nowEpochMs);return{...e.record,state:`failed`,activeToolCalls:0,updatedAtEpochMs:t,endedAtEpochMs:t,lastErrorCode:`task_rehydrated_incomplete`,lastErrorMessage:`Task '${e.record.id}' restored from persistence in non-terminal state '${e.record.state}' and was marked failed`}}function R(e){let t=ar(e);return a.isError(t)?a.err(yr(e.id,t.error)):a.ok(t.value)}function Er(e,t){return e.length<=t?[...e]:e.slice(e.length-t)}function Dr(e,t){return{provider:t?.provider??`unavailable`,model:t?.model??`unavailable`,runtime:t?.runtime??e,route:t?.route??e,promptProfile:t?.promptProfile,promptProfileSource:t?.promptProfileSource,promptProfileReason:t?.promptProfileReason}}var Or=class{tasks=new Map;expiredTasks=new Map;persistenceDiagnostics=[];now;retentionMs;persistence;maxEventsPerTask;maxTasks;maxExpiredTasks;persistenceDebounceMs;pendingPersistenceTimer;constructor(e={}){this.now=e.now??(()=>Date.now()),this.retentionMs=e.retentionMs!==void 0&&e.retentionMs>0?e.retentionMs:864e5,this.persistence=e.persistence,this.maxEventsPerTask=e.maxEventsPerTask!==void 0&&e.maxEventsPerTask>0?e.maxEventsPerTask:120,this.maxTasks=e.maxTasks!==void 0&&e.maxTasks>0?e.maxTasks:200,this.maxExpiredTasks=e.maxExpiredTasks!==void 0&&e.maxExpiredTasks>0?e.maxExpiredTasks:500,this.persistenceDebounceMs=e.persistenceDebounceMs!==void 0&&e.persistenceDebounceMs>=0?Math.floor(e.persistenceDebounceMs):0,this.hydrateFromPersistence(),this.pruneExpiredTerminalTasks()}createTask(e){if(this.pruneExpiredTerminalTasks(),this.tasks.has(e.taskId))return a.err(new C({code:`duplicate_task_id`,stage:`task_runtime_store`,message:`Task id '${e.taskId}' already exists`,meta:{taskId:e.taskId}}));this.expiredTasks.delete(e.taskId);let t=this.now(),n=R({id:e.taskId,subagentType:e.subagent.id,description:e.description,prompt:e.prompt,state:`queued`,totalToolCalls:0,activeToolCalls:0,startedAtEpochMs:t,updatedAtEpochMs:t});if(a.isError(n))return n;let r={record:n.value,summary:`Queued ${e.subagent.name}: ${e.description}`,backend:e.backend,...Dr(e.backend,e.observability),invocation:e.invocation,followUpPrompts:[],events:[]};return this.tasks.set(e.taskId,r),this.pruneTaskCapacity(),this.requestPersist({immediate:!0}),a.ok(L(r))}markRunning(e,t){return this.transition(e,`running`,{summary:t,activeToolCalls:1,totalToolCallsDelta:1})}markInteractionRunning(e,t,n){this.pruneExpiredTerminalTasks();let r=this.getMutableEntry(e);if(a.isError(r))return r;let i=r.value;if(I(i.record.state))return a.err(Cr(e,i.record.state));let o=this.now(),s=R({id:i.record.id,subagentType:i.record.subagentType,description:i.record.description,prompt:i.record.prompt,state:`running`,totalToolCalls:i.record.totalToolCalls+1,activeToolCalls:1,startedAtEpochMs:i.record.startedAtEpochMs,updatedAtEpochMs:o});if(a.isError(s))return s;let c=n.trim(),l=c.length>0?[...i.followUpPrompts,c]:[...i.followUpPrompts],u={...i,record:s.value,summary:t,followUpPrompts:l};return this.tasks.set(e,u),this.requestPersist({immediate:!1}),a.ok(L(u))}markInteractionComplete(e,t,n,r){this.pruneExpiredTerminalTasks();let i=this.getMutableEntry(e);if(a.isError(i))return i;let o=i.value;if(o.record.state!==`running`)return a.err(wr(e,o.record.state));let s=this.now(),c=R({id:o.record.id,subagentType:o.record.subagentType,description:o.record.description,prompt:o.record.prompt,state:`running`,totalToolCalls:o.record.totalToolCalls,activeToolCalls:0,startedAtEpochMs:o.record.startedAtEpochMs,updatedAtEpochMs:s});if(a.isError(c))return c;let l={...o,record:c.value,summary:t,output:n,...Dr(o.backend,{provider:r?.provider??o.provider,model:r?.model??o.model,runtime:r?.runtime??o.runtime,route:r?.route??o.route,promptProfile:r?.promptProfile??o.promptProfile,promptProfileSource:r?.promptProfileSource??o.promptProfileSource,promptProfileReason:r?.promptProfileReason??o.promptProfileReason})};return this.tasks.set(e,l),this.requestPersist({immediate:!1}),a.ok(L(l))}markSucceeded(e,t,n,r){return this.transition(e,`succeeded`,{summary:t,output:n,observability:r,activeToolCalls:0,totalToolCallsDelta:0})}markFailed(e,t,n,r){return this.transition(e,`failed`,{summary:t,activeToolCalls:0,totalToolCallsDelta:0,errorCode:n,errorMessage:r})}markCancelled(e,t){this.pruneExpiredTerminalTasks();let n=this.tasks.get(e);if(!n){let t=this.expiredTasks.get(e);return t?a.err(xr(e,t)):a.err(br(e))}if(I(n.record.state))return a.ok(L(n));let r=n.abortController,i=this.transition(e,`cancelled`,{summary:t,activeToolCalls:0,totalToolCallsDelta:0});return a.isError(i)||r?.abort(),i}getTask(e){this.pruneExpiredTerminalTasks();let t=this.tasks.get(e);if(t)return L(t)}listTasks(){return this.pruneExpiredTerminalTasks(),[...this.tasks.values()].map(e=>L(e))}getTasks(e){return this.pruneExpiredTerminalTasks(),e.map(e=>{let t=this.tasks.get(e);if(t)return{id:e,found:!0,snapshot:L(t)};let n=this.expiredTasks.get(e);return n?{id:e,found:!1,errorCode:`task_expired`,errorMessage:n}:{id:e,found:!1,errorCode:`unknown_task_id`,errorMessage:`Unknown task id '${e}'`}})}updateObservability(e,t){this.pruneExpiredTerminalTasks();let n=this.getMutableEntry(e);if(a.isError(n))return n;let r=n.value,i={...r,...Dr(r.backend,{provider:t.provider??r.provider,model:t.model??r.model,runtime:t.runtime??r.runtime,route:t.route??r.route,promptProfile:t.promptProfile??r.promptProfile,promptProfileSource:t.promptProfileSource??r.promptProfileSource,promptProfileReason:t.promptProfileReason??r.promptProfileReason})};return this.tasks.set(e,i),this.requestPersist({immediate:!1}),a.ok(L(i))}setAbortController(e,t){let n=this.getMutableEntry(e);if(a.isError(n))return n;let r=n.value;return this.tasks.set(e,{...r,abortController:t}),a.ok(!0)}getAbortController(e){return this.tasks.get(e)?.abortController}setExecutionPromise(e,t){let n=this.getMutableEntry(e);if(a.isError(n))return n;let r=n.value;return this.tasks.set(e,{...r,executionPromise:t}),a.ok(!0)}getExecutionPromise(e){return this.tasks.get(e)?.executionPromise}appendEvents(e,t){this.pruneExpiredTerminalTasks();let n=this.getMutableEntry(e);if(a.isError(n))return n;let r=n.value;if(t.length===0)return a.ok(L(r));let i=Er([...r.events,...t],this.maxEventsPerTask),o={...r,events:i};return this.tasks.set(e,o),this.requestPersist({immediate:!1}),a.ok(L(o))}getPersistenceDiagnostics(){return this.persistenceDiagnostics}getMutableEntry(e){let t=this.tasks.get(e);if(t)return a.ok(t);let n=this.expiredTasks.get(e);return n?a.err(xr(e,n)):a.err(br(e))}transition(e,t,n){this.pruneExpiredTerminalTasks();let r=this.getMutableEntry(e);if(a.isError(r))return r;let i=r.value;if(!vr(i.record.state,t))return a.err(Sr(e,i.record.state,t));let o=this.now(),s=i.record.totalToolCalls+n.totalToolCallsDelta,c={id:i.record.id,subagentType:i.record.subagentType,description:i.record.description,prompt:i.record.prompt,state:t,totalToolCalls:s,activeToolCalls:n.activeToolCalls,startedAtEpochMs:i.record.startedAtEpochMs,updatedAtEpochMs:o},l=R(t===`queued`||t===`running`?{...c,state:t}:{...c,state:t,endedAtEpochMs:o,lastErrorCode:n.errorCode,lastErrorMessage:n.errorMessage});if(a.isError(l))return l;let u={...i,record:l.value,summary:n.summary,output:n.output,...Dr(i.backend,{provider:n.observability?.provider??i.provider,model:n.observability?.model??i.model,runtime:n.observability?.runtime??i.runtime,route:n.observability?.route??i.route,promptProfile:n.observability?.promptProfile??i.promptProfile,promptProfileSource:n.observability?.promptProfileSource??i.promptProfileSource,promptProfileReason:n.observability?.promptProfileReason??i.promptProfileReason}),errorCode:n.errorCode,errorMessage:n.errorMessage,abortController:I(t)?void 0:i.abortController,executionPromise:I(t)?void 0:i.executionPromise};return this.tasks.set(e,u),this.requestPersist({immediate:I(t)}),a.ok(L(u))}hydrateFromPersistence(){if(!this.persistence)return;let e=this.persistence.load();if(a.isError(e)){this.persistenceDiagnostics.push(e.error.message);return}e.value.recoveredCorruptFilePath&&this.persistenceDiagnostics.push(`Recovered corrupt task registry snapshot: ${e.value.recoveredCorruptFilePath}`);let t=!1;for(let n of e.value.entries){let e=R(n.record.state===`queued`||n.record.state===`running`?Tr({record:n.record,nowEpochMs:this.now()}):n.record);if(a.isError(e)){this.persistenceDiagnostics.push(e.error.message);continue}let r=n.record.state!==e.value.state;r&&(t=!0,this.persistenceDiagnostics.push(`Task '${n.record.id}' restored from non-terminal '${n.record.state}' state and marked failed`));let i={record:e.value,summary:r?`Task '${n.record.id}' recovered from non-terminal state and marked failed`:n.summary,output:n.output,backend:n.backend,provider:n.provider,model:n.model,runtime:n.runtime,route:n.route,promptProfile:n.promptProfile,promptProfileSource:n.promptProfileSource,promptProfileReason:n.promptProfileReason,invocation:n.invocation,followUpPrompts:n.followUpPrompts,events:Er(n.events,this.maxEventsPerTask),errorCode:r?`task_rehydrated_incomplete`:n.errorCode,errorMessage:r?`Task '${n.record.id}' restored from persistence in non-terminal state '${n.record.state}' and was marked failed`:n.errorMessage};this.tasks.set(e.value.id,i)}let n=this.tasks.size;this.pruneTaskCapacity(),this.tasks.size!==n&&(t=!0),t&&this.requestPersist({immediate:!0})}pruneExpiredTerminalTasks(){let e=!1,t=this.now();for(let[n,r]of this.tasks.entries())I(r.record.state)&&r.record.endedAtEpochMs!==void 0&&(t-r.record.endedAtEpochMs<this.retentionMs||(this.tasks.delete(n),this.rememberExpiredTask(n,`Task id '${n}' expired by retention policy after ${this.retentionMs}ms`),e=!0));e&&this.requestPersist({immediate:!1})}rememberExpiredTask(e,t){for(this.expiredTasks.delete(e),this.expiredTasks.set(e,t);this.expiredTasks.size>this.maxExpiredTasks;){let e=this.expiredTasks.keys().next();if(e.done)return;this.expiredTasks.delete(e.value)}}pruneTaskCapacity(){if(this.tasks.size<=this.maxTasks)return;let e=[...this.tasks.entries()].filter(([,e])=>I(e.record.state)).sort((e,t)=>(e[1].record.endedAtEpochMs??e[1].record.updatedAtEpochMs)-(t[1].record.endedAtEpochMs??t[1].record.updatedAtEpochMs));for(let[t]of e){if(this.tasks.size<=this.maxTasks)return;this.tasks.delete(t),this.rememberExpiredTask(t,`Task id '${t}' evicted by capacity policy after reaching max ${this.maxTasks} tasks`)}}requestPersist(e){if(!this.persistence)return;if(e.immediate||this.persistenceDebounceMs===0){this.flushPendingPersistenceTimer(),this.persistCurrentState();return}if(this.pendingPersistenceTimer)return;let t=setTimeout(()=>{this.pendingPersistenceTimer=void 0,this.persistCurrentState()},this.persistenceDebounceMs);t.unref?.(),this.pendingPersistenceTimer=t}flushPendingPersistenceTimer(){this.pendingPersistenceTimer&&=(clearTimeout(this.pendingPersistenceTimer),void 0)}persistCurrentState(){if(!this.persistence)return;let e={schemaVersion:1,savedAtEpochMs:this.now(),entries:[...this.tasks.values()].map(e=>({record:e.record,summary:e.summary,output:e.output,backend:e.backend,provider:e.provider,model:e.model,runtime:e.runtime,route:e.route,promptProfile:e.promptProfile,promptProfileSource:e.promptProfileSource,promptProfileReason:e.promptProfileReason,invocation:e.invocation,followUpPrompts:e.followUpPrompts,errorCode:e.errorCode,errorMessage:e.errorMessage,events:e.events}))},t=this.persistence.save(e);a.isError(t)&&this.persistenceDiagnostics.push(t.error.message)}};function kr(e={}){return new Or(e)}function z(e){let t=process.env[e];if(!t)return;let n=Number.parseInt(t,10);if(!(Number.isNaN(n)||n<=0))return n}function Ar(e){let t=process.env[e];if(!t)return;let n=Number.parseInt(t,10);if(!(Number.isNaN(n)||n<0))return n}function jr(){return z(`OHM_SUBAGENTS_TASK_RETENTION_MS`)}function Mr(){return z(`OHM_SUBAGENTS_TASK_MAX_EVENTS`)}function Nr(){return z(`OHM_SUBAGENTS_TASK_MAX_ENTRIES`)}function Pr(){return z(`OHM_SUBAGENTS_TASK_MAX_EXPIRED_ENTRIES`)}function Fr(){let e=Ar(`OHM_SUBAGENTS_TASK_PERSIST_DEBOUNCE_MS`);return e===void 0?90:e}function Ir(e){let t=process.env[e];if(!t)return;let n=t.trim();if(n.length!==0)return n}function Lr(){let e=z(`OHM_SUBAGENTS_ONUPDATE_THROTTLE_MS`);return e===void 0?120:e}function Rr(){return Ir(`OHM_SUBAGENTS_TASK_PERSIST_PATH`)||ee(te(),`ohm.subagents.tasks.json`)}const zr=kr({persistence:_r(Rr()),retentionMs:jr(),maxEventsPerTask:Mr(),maxTasks:Nr(),maxExpiredTasks:Pr(),persistenceDebounceMs:Fr()});let Br=0;function Vr(e=Date.now()){return Br+=1,`task_${e}_${Br.toString().padStart(4,`0`)}`}function Hr(){return{loadConfig:t,backend:Yn(),findSubagentById:Se,subagents:x,createTaskId:Vr,taskStore:zr}}const B=h.String({minLength:1}),Ur=h.Integer({minimum:1}),Wr=h.Object({subagent_type:B,description:B,prompt:B,async:h.Optional(h.Boolean())},{additionalProperties:!1}),Gr=h.Object({op:h.Literal(`start`),subagent_type:B,description:B,prompt:B,async:h.Optional(h.Boolean())},{additionalProperties:!1}),Kr=h.Object({op:h.Literal(`start`),tasks:h.Array(Wr,{minItems:1}),parallel:h.Optional(h.Boolean()),async:h.Optional(h.Boolean())},{additionalProperties:!1}),qr=h.Object({op:h.Literal(`status`),ids:h.Array(B,{minItems:1})},{additionalProperties:!1}),Jr=h.Object({op:h.Literal(`wait`),ids:h.Array(B,{minItems:1}),timeout_ms:h.Optional(Ur)},{additionalProperties:!1}),Yr=h.Object({op:h.Literal(`send`),id:B,prompt:B},{additionalProperties:!1}),Xr=h.Object({op:h.Literal(`cancel`),id:B},{additionalProperties:!1}),Zr=h.Union([Gr,Kr,qr,Jr,Yr,Xr]),Qr=h.Object({op:B,subagent_type:h.Optional(B),description:h.Optional(B),prompt:h.Optional(B),async:h.Optional(h.Boolean()),tasks:h.Optional(h.Array(Wr,{minItems:1})),parallel:h.Optional(h.Boolean()),ids:h.Optional(h.Array(B,{minItems:1})),timeout_ms:h.Optional(Ur),id:h.Optional(B)},{additionalProperties:!1}),$r=[Gr,Kr,qr,Jr,Yr,Xr];function ei(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ti(e){if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)return t}function ni(e){if(Array.isArray(e)){let t=e.map(e=>ti(e)).filter(e=>typeof e==`string`);return t.length===0?void 0:t}let t=ti(e);if(t)return[t]}function ri(e){if(typeof e==`boolean`)return e}function ii(e){if(typeof e==`number`&&Number.isInteger(e))return e}function ai(e){return ei(e)?{subagent_type:Reflect.get(e,`subagent_type`),description:Reflect.get(e,`description`),prompt:Reflect.get(e,`prompt`),async:ri(Reflect.get(e,`async`))}:e}function oi(e){if(!ei(e))return e;let t=ti(Reflect.get(e,`op`));if(!t)return e;let n=t===`result`?`status`:t;if(n===`start`){let t=Reflect.get(e,`tasks`);return Array.isArray(t)?{op:`start`,tasks:t.map(e=>ai(e)),parallel:ri(Reflect.get(e,`parallel`)),async:ri(Reflect.get(e,`async`))}:{op:`start`,subagent_type:Reflect.get(e,`subagent_type`),description:Reflect.get(e,`description`),prompt:Reflect.get(e,`prompt`),async:ri(Reflect.get(e,`async`))}}return n===`status`?{op:`status`,ids:ni(Reflect.get(e,`ids`)??Reflect.get(e,`id`))}:n===`wait`?{op:`wait`,ids:ni(Reflect.get(e,`ids`)??Reflect.get(e,`id`)),timeout_ms:ii(Reflect.get(e,`timeout_ms`))}:n===`send`?{op:`send`,id:Reflect.get(e,`id`),prompt:Reflect.get(e,`prompt`)}:n===`cancel`?{op:`cancel`,id:Reflect.get(e,`id`)}:e}function si(e){let t=er(ve.Errors(Zr,e).First()?.path);if(t)return t;let n,r=-1;for(let t of $r){let i=er(ve.Errors(t,e).First()?.path);if(!i)continue;let a=i.split(`.`).length;a>r&&(r=a,n=i)}return n}function ci(e){let t=oi(e);if(!ve.Check(Zr,t)){let e=si(t);return a.err(new we({code:`invalid_task_tool_payload`,path:e,message:e?`Task tool payload failed validation at ${e}`:`Task tool payload failed validation`}))}return a.ok(ve.Decode(Zr,t))}function li(e){return e.length===0?`tool`:`${e[0]?.toUpperCase()??``}${e.slice(1)}`}function ui(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)return t}function di(e,t=88){let n=e.trim();return n.length<=t?n:`${n.slice(0,Math.max(t-1,1))}…`}function fi(e){let t=V(e);if(t&&t.startsWith(`{`))try{let e=JSON.parse(t);return ui(e)?e:void 0}catch{return}}function pi(e,t){let n=Reflect.get(e,t);if(typeof n==`number`&&!(!Number.isInteger(n)||n<=0))return n}function mi(e,t){let n=fi(t),r=e.trim().toLowerCase();if(!n){if(r===`bash`){let e=V(t);return e?di(e):void 0}return}if(r===`bash`){let e=V(Reflect.get(n,`command`));return e?di(e):void 0}if(r===`read`||r===`write`||r===`edit`){let e=V(Reflect.get(n,`path`));if(!e)return;let t=pi(n,`offset`),r=pi(n,`limit`);return t!==void 0&&r!==void 0?`${e} @${t}-${t+r-1}`:t===void 0?e:`${e} @${t}`}if(r===`grep`){let e=V(Reflect.get(n,`pattern`))??V(Reflect.get(n,`query`));return e?di(e):void 0}if(r===`glob`||r===`find`||r===`ls`){let e=V(Reflect.get(n,`pattern`))??V(Reflect.get(n,`path`))??V(Reflect.get(n,`query`));return e?di(e):void 0}}function hi(e){return mi(e.toolName,e.argsText)}function gi(e){let t=e.match(/^tool_call:\s*(\S+)\s+(start|update|end success|end error)\s*(.*)$/iu);if(!t)return;let n=t[1]?.trim(),r=t[2]?.trim().toLowerCase(),i=V(t[3]);if(!(!n||!r)&&!(r!==`start`&&r!==`update`&&r!==`end success`&&r!==`end error`))return{toolName:n,phase:r,payload:i}}function _i(e){let t=[];for(let n of e){let e=gi(n);if(!e)continue;if(e.phase===`start`){t.push({toolName:e.toolName,outcome:`running`,detail:mi(e.toolName,e.payload)});continue}let r=(()=>{for(let n=t.length-1;n>=0;--n){let r=t[n];if(r&&r.toolName===e.toolName&&r.outcome===`running`)return n}return-1})();if(r<0){t.push({toolName:e.toolName,outcome:e.phase===`end error`?`error`:`running`});continue}let i=t[r];if(i){if(e.phase===`end success`){i.outcome=`success`;continue}if(e.phase===`end error`){i.outcome=`error`;continue}i.detail||=mi(e.toolName,e.payload)}}return t.map(e=>{let t=e.outcome===`success`?`✓`:e.outcome===`error`?`✕`:`○`,n=e.detail?` ${e.detail}`:``;return`${t} ${li(e.toolName)}${n}`})}function vi(e){let t=[],n=new Map;for(let r of e){if(r.type!==`tool_start`&&r.type!==`tool_update`&&r.type!==`tool_end`)continue;let e=n.get(r.toolCallId);if(!e){t.push(r.toolCallId),n.set(r.toolCallId,{toolName:r.toolName,outcome:r.type===`tool_end`?r.status===`error`?`error`:`success`:`running`,detail:r.type===`tool_start`?hi(r):void 0});continue}if(r.type===`tool_start`){n.set(r.toolCallId,{toolName:e.toolName,outcome:e.outcome,detail:e.detail??hi(r)});continue}r.type===`tool_end`&&n.set(r.toolCallId,{toolName:e.toolName,outcome:r.status===`error`?`error`:`success`,detail:e.detail})}return t.map(e=>{let t=n.get(e);if(!t)return`○ Tool`;let r=t.outcome===`success`?`✓`:t.outcome===`error`?`✕`:`○`,i=t.detail?` ${t.detail}`:``;return`${r} ${li(t.toolName)}${i}`})}function yi(e){let t=e.filter(e=>e.type===`assistant_text_delta`).map(e=>e.delta);if(t.length===0)return;let n=t.join(``).trim();if(n.length!==0)return n}function bi(e){return e.replace(/^(assistant|user|system)\s*[:>]\s*/iu,``).trim().replace(/^tool(?:\([^)]+\))?\s*[:>]\s*/iu,``).trim()}function xi(e){return!!(/^[✓✕○•…⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]\s+/u.test(e)||/^(Read|Glob|Grep|Find|Search|Bash|Edit|Write|Ls)\b/u.test(e)||/^tool_call\s*[:>]/iu.test(e)||/^\$\s+.+/u.test(e))}function Si(e){let t=e.trim();return t.length===0?`✓ (empty tool line)`:/^[✓✕○•…⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]\s+/u.test(t)?t:`✓ ${t}`}function Ci(e,t={}){let n=e.split(/\r?\n/u).map(e=>bi(e.trim())).filter(e=>e.length>0);if(n.length===0)return{toolCalls:[],narrativeLines:[]};let r=t.normalizeDetectedToolCalls??!1,i=[],a=[],o=[];for(let e of n){if(gi(e)){a.push(e);continue}if(xi(e)){i.push(r?Si(e):e);continue}o.push(e)}let s=_i(a);return{toolCalls:s.length>0?[...s,...i]:i,narrativeLines:o}}function wi(e){return e===`unknown_task_id`||e===`task_expired`||e.includes(`not_found`)?`not_found`:e.startsWith(`invalid_`)||e.includes(`validation`)||e.includes(`payload`)||e.includes(`unknown_operation`)?`validation`:e.includes(`permission`)||e.includes(`policy`)||e.includes(`internal_subagent`)?`policy`:e.includes(`persistence`)||e.includes(`corrupt`)||e.includes(`retention`)?`persistence`:`runtime`}function Ti(e){return!e.error_code||e.error_category?e:{...e,error_category:wi(e.error_code)}}function Ei(e){return!e.error_code||e.error_category?e:{...e,error_category:wi(e.error_code)}}function Di(e){return{...e,provider:e.provider??`unavailable`,model:e.model??`unavailable`,runtime:e.runtime??e.backend,route:e.route??e.backend}}function Oi(e){return{...e,provider:e.provider??`unavailable`,model:e.model??`unavailable`,runtime:e.runtime??e.backend??`unavailable`,route:e.route??e.backend??`unavailable`}}function H(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}function ki(e){if(!e)return;let t=Ci(e);if(t.narrativeLines.length!==0)return t.narrativeLines.join(`
10
- `)}function Ai(e){if(!e.found)return e.error_message??e.summary;let t=e.output_available&&e.output?ki(e.output):void 0;if(t&&t.length>0)return t;let n=e.assistant_text?.trim();return n&&n.length>0?n:e.error_message&&e.error_message.length>0?e.error_message:e.summary}function ji(e){let t=e.output_available&&e.output?ki(e.output):void 0;if(t&&t.length>0)return t;let n=e.assistant_text?.trim();if(n&&n.length>0)return n;if(e.items&&e.items.length===1){let[t]=e.items;if(t&&t.found)return Ai(t)}return e.error_message&&e.error_message.length>0?e.error_message:e.summary}function Mi(e){let t=new Set,n=e=>{if(!e)return;let n=e.trim();n.length!==0&&t.add(n)};n(e.task_id);for(let t of e.items??[])n(t.id);return[...t]}function Ni(e){let[t]=Mi(e);return t||`unavailable`}function Pi(e){if(!e.items||e.items.length===0)return;let t;for(let n of e.items){let r=n.ended_at_epoch_ms??n.updated_at_epoch_ms??e.ended_at_epoch_ms;typeof r!=`number`||!Number.isFinite(r)||(t=t===void 0?r:Math.max(t,r))}return H(t)}function Fi(e){let t=H(e.ended_at_epoch_ms)??H(e.updated_at_epoch_ms);if(t)return t;let n=Pi(e);if(n)return n;if(e.items&&e.items.length===1){let[t]=e.items;if(t){let e=H(t.ended_at_epoch_ms)??H(t.updated_at_epoch_ms);if(e)return e}}return`unavailable`}function Ii(e,t){let n=e.found?e.status??`failed`:`failed`,r=e.subagent_type??`unknown`,i=e.description?` · ${e.description}`:``,a=Ai(e).split(`
11
- `),o=[`- ${t+1}. ${e.id} [${n}] ${r}${i}`];if(a.length<=1)return o.push(` result: ${a[0]??``}`),o;o.push(` result:`);for(let e of a)o.push(` ${e}`);return o}function Li(e){let t=Mi(e),n=Ni(e),r=Fi(e),i=ji(e),a=[`task_id: ${n}`,...t.length>1?[`task_ids: ${t.join(`, `)}`]:[],`status: ${e.status}`,...e.subagent_type?[`subagent: ${e.subagent_type}`]:[],`backend: ${e.backend}`,`provider: ${e.provider??`unavailable`}`,`model: ${e.model??`unavailable`}`,`runtime: ${e.runtime??e.backend}`,`route: ${e.route??e.backend}`,`timestamp: ${r}`,`result:`,i];if(e.items&&e.items.length>1){a.push(`items:`);for(let[t,n]of e.items.entries())a.push(...Ii(n,t))}return a.join(`
12
- `)}function Ri(e){return Li(e)}function zi(){let e=process.env.OHM_DEBUG?.trim().toLowerCase();return e?e===`1`||e===`true`:!1}function Bi(){if(zi())return!0;let e=process.env.OHM_SUBAGENTS_PROMPT_PROFILE_DEBUG?.trim().toLowerCase();return e?e===`1`||e===`true`:!1}function Vi(e){return e===`queued`?`queued`:e===`running`?`running`:e===`succeeded`?`succeeded`:e===`failed`?`failed`:`cancelled`}function Hi(e){return e.length===0?e:`${e[0]?.toUpperCase()??``}${e.slice(1)}`}function Ui(e){return Ci(e,{normalizeDetectedToolCalls:!0})}function Wi(e){if(e.sections.narrativeLines.length>0)return e.expanded?e.sections.narrativeLines.join(`
9
+ `);return a.ok({summary:t,output:n,provider:`unavailable`,model:`unavailable`,runtime:this.id,route:this.id})}};function Ln(e){if(!e)return;let t=Number.parseInt(e,10);if(!(!Number.isFinite(t)||t<=0))return t}function Rn(){return Ln(process.env.OHM_SUBAGENTS_BACKEND_TIMEOUT_MS)??18e4}function zn(e){let t=`OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_${e.trim().toUpperCase()}`;return Ln(process.env[t])}function Bn(e){let t=zn(e.subagent.id);if(t!==void 0)return t;let n=Rn(),r=n>0?n:e.fallbackTimeoutMs;return e.subagent.id===`librarian`?Math.max(r,3e5):e.subagent.id===`oracle`?Math.max(r,36e5):r}function Vn(){let e=process.env.OHM_SUBAGENTS_SDK_FALLBACK_TO_CLI;if(!e)return!1;let t=e.trim().toLowerCase();return t===`1`||t===`true`||t===`yes`||t===`on`}function Hn(e,t){return new C({code:`task_aborted`,stage:t,message:`Task ${e} was aborted before execution`,meta:{taskId:e}})}function Un(e,t){return new C({code:`unsupported_subagent_backend`,stage:t,message:`Configured subagent backend is not implemented in @pi-ohm/subagents`,meta:{taskId:e,backend:`custom-plugin`}})}function Wn(e){let t=Math.max(1,Math.round(e.timeoutMs/1e3)),n=e.modelPattern?` (model: ${e.modelPattern})`:``,r=e.subagentId===`oracle`?`Narrow oracle task scope/context/files or raise OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_ORACLE.`:`Narrow task scope or raise OHM_SUBAGENTS_BACKEND_TIMEOUT_MS_${e.subagentId.toUpperCase()} (or OHM_SUBAGENTS_BACKEND_TIMEOUT_MS).`;return new C({code:`task_backend_timeout`,stage:e.stage,message:`Task ${e.taskId} timed out after ${t}s while waiting for '${e.subagentId}' backend response${n}. ${r}`,meta:{taskId:e.taskId,timeoutMs:e.timeoutMs,timeoutSeconds:t,subagentId:e.subagentId,modelPattern:e.modelPattern}})}function Gn(e){let t=e.stderr.trim(),n=t.length>0?T(t,260):`subagent backend exited non-zero`;return new C({code:`task_backend_execution_failed`,stage:e.stage,message:`Task ${e.taskId} backend failed: ${n}`,meta:{taskId:e.taskId,exitCode:e.exitCode,stderr:t}})}function Kn(e){let t=s(e.config,e.subagent.id);return l({config:e.config,subagentId:e.subagent.id,modelPattern:t})?.model??t}function qn(e){if(!e)return;let t=e.trim();if(t.length===0)return;let n=t.indexOf(`/`);if(n<=0||n>=t.length-1)return;let r=t.slice(0,n).trim().toLowerCase(),i=t.slice(n+1).trim().toLowerCase(),a=i.endsWith(`:off`)||i.endsWith(`:minimal`)||i.endsWith(`:low`)||i.endsWith(`:medium`)||i.endsWith(`:high`)||i.endsWith(`:xhigh`)?i.slice(0,i.lastIndexOf(`:`)):i;if(!(r.length===0||a.length===0))return{provider:r,model:a}}var Jn=class{id=M;scaffoldBackend=new In;constructor(e=En,t=Rn(),n=new Fn){this.runner=e,this.timeoutMs=t,this.sdkBackend=n}resolveBackendId(e){return e.subagentBackend===`none`?this.scaffoldBackend.id:e.subagentBackend===`interactive-shell`?N:e.subagentBackend===`interactive-sdk`?M:e.subagentBackend===`custom-plugin`?`custom-plugin`:this.id}shouldFallbackToCli(e){return!(!Vn()||e.code!==`task_backend_execution_failed`)}async executeCliStart(e){let t=Kn({config:e.config,subagent:e.subagent}),n=Bn({fallbackTimeoutMs:this.timeoutMs,subagent:e.subagent}),r=qn(t);e.onObservability?.({provider:r?.provider??`unavailable`,model:r?.model??`unavailable`,runtime:`pi-cli`,route:N});let i=await this.runner({cwd:e.cwd,prompt:await ot({...e,modelPattern:t}),modelPattern:t,signal:e.signal,timeoutMs:n});if(i.aborted||e.signal?.aborted)return a.err(Hn(e.taskId,`execute_start`));if(i.timedOut)return a.err(Wn({taskId:e.taskId,stage:`execute_start`,timeoutMs:n,subagentId:e.subagent.id,modelPattern:t}));if(i.exitCode!==0)return a.err(Gn({taskId:e.taskId,stage:`execute_start`,exitCode:i.exitCode,stderr:i.stderr}));let o=vn(_n(i.stdout,i.stderr)),s=`${e.subagent.name}: ${T(e.description,72)}`;return a.ok({summary:s,output:o.output,provider:o.provider,model:o.model,runtime:o.runtime,route:N})}async executeCliSend(e){let t=Kn({config:e.config,subagent:e.subagent}),n=Bn({fallbackTimeoutMs:this.timeoutMs,subagent:e.subagent}),r=qn(t);e.onObservability?.({provider:r?.provider??`unavailable`,model:r?.model??`unavailable`,runtime:`pi-cli`,route:N});let i=await this.runner({cwd:e.cwd,prompt:st(e),modelPattern:t,signal:e.signal,timeoutMs:n});if(i.aborted||e.signal?.aborted)return a.err(Hn(e.taskId,`execute_send`));if(i.timedOut)return a.err(Wn({taskId:e.taskId,stage:`execute_send`,timeoutMs:n,subagentId:e.subagent.id,modelPattern:t}));if(i.exitCode!==0)return a.err(Gn({taskId:e.taskId,stage:`execute_send`,exitCode:i.exitCode,stderr:i.stderr}));let o=vn(_n(i.stdout,i.stderr)),s=`${e.subagent.name} follow-up: ${T(e.prompt,72)}`;return a.ok({summary:s,output:o.output,provider:o.provider,model:o.model,runtime:o.runtime,route:N})}async executeStart(e){if(e.signal?.aborted)return a.err(Hn(e.taskId,`execute_start`));if(e.config.subagentBackend===`none`)return this.scaffoldBackend.executeStart(e);if(e.config.subagentBackend===`custom-plugin`)return a.err(Un(e.taskId,`execute_start`));if(e.config.subagentBackend===`interactive-shell`)return this.executeCliStart(e);if(e.config.subagentBackend===`interactive-sdk`){let t=await this.sdkBackend.executeStart(e);return a.isOk(t)||!this.shouldFallbackToCli(t.error)?t:this.executeCliStart(e)}let t=await this.sdkBackend.executeStart(e);return a.isOk(t)||!this.shouldFallbackToCli(t.error)?t:this.executeCliStart(e)}async executeSend(e){if(e.signal?.aborted)return a.err(Hn(e.taskId,`execute_send`));if(e.config.subagentBackend===`none`)return this.scaffoldBackend.executeSend(e);if(e.config.subagentBackend===`custom-plugin`)return a.err(Un(e.taskId,`execute_send`));if(e.config.subagentBackend===`interactive-shell`)return this.executeCliSend(e);if(e.config.subagentBackend===`interactive-sdk`){let t=await this.sdkBackend.executeSend(e);return a.isOk(t)||!this.shouldFallbackToCli(t.error)?t:this.executeCliSend(e)}let t=await this.sdkBackend.executeSend(e);return a.isOk(t)||!this.shouldFallbackToCli(t.error)?t:this.executeCliSend(e)}};function Yn(){return new Jn}const Xn=b.core.version.major;function Zn(){return Xn===4?a.ok(!0):a.err(new C({code:`unsupported_zod_major`,stage:`schema`,message:`Expected Zod v4 but found v`+String(Xn),meta:{detectedMajor:Xn}}))}function Qn(e,t,n,r){return new we({code:e,path:n,message:n?`${t}: ${n}`:t,cause:r})}function $n(e){let[t]=e;if(t&&t.path.length!==0)return t.path.map(e=>e.toString()).filter(e=>e.length>0).join(`.`)}function er(e){if(!e||e.length===0)return;let t=e.replace(/^\//u,``).replaceAll(`/`,`.`);if(t.length!==0)return t}const tr=b.strictObject({id:b.string().trim().min(1),subagentType:b.string().trim().min(1),description:b.string().trim().min(1),prompt:b.string().trim().min(1),totalToolCalls:b.int().nonnegative(),activeToolCalls:b.int().nonnegative(),startedAtEpochMs:b.int().nonnegative(),updatedAtEpochMs:b.int().nonnegative()}),nr=tr.extend({state:b.enum([`queued`,`running`]),endedAtEpochMs:b.undefined().optional(),lastErrorCode:b.undefined().optional(),lastErrorMessage:b.undefined().optional()}),rr=tr.extend({state:b.enum([`succeeded`,`failed`,`cancelled`]),endedAtEpochMs:b.int().nonnegative(),lastErrorCode:b.string().trim().min(1).optional(),lastErrorMessage:b.string().trim().min(1).optional()}).superRefine((e,t)=>{e.activeToolCalls!==0&&t.addIssue({code:`custom`,message:`Terminal task records must have activeToolCalls = 0`,path:[`activeToolCalls`]}),e.endedAtEpochMs<e.startedAtEpochMs&&t.addIssue({code:`custom`,message:`endedAtEpochMs must be >= startedAtEpochMs`,path:[`endedAtEpochMs`]}),e.state===`failed`&&!e.lastErrorMessage&&t.addIssue({code:`custom`,message:`Failed task records require lastErrorMessage`,path:[`lastErrorMessage`]})}),ir=b.discriminatedUnion(`state`,[nr,rr]);function ar(e){let t=Zn();if(a.isError(t))return t;let n=ir.safeParse(e);if(n.success)return a.ok(n.data);let r=$n(n.error.issues);return a.err(Qn(`invalid_task_record`,`Task record failed validation`,r,n.error))}function or(e){return typeof e==`object`&&!!e}function sr(e){if(e===`task-routed`||e===`primary-tool`)return e}function P(e){if(typeof e==`string`&&e.trim().length!==0)return e}function F(e){if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)return t}function cr(e){if(typeof e==`number`&&Number.isFinite(e)&&!(e<0))return e}function lr(e){if(!or(e))return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted task event must be an object`}));let t=F(e.type);if(!t)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted task event missing type`}));let n=cr(e.atEpochMs);if(n===void 0)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted task event missing valid atEpochMs`}));if(t===`assistant_text_delta`){let r=F(e.delta);return r?a.ok({type:t,delta:r,atEpochMs:n}):a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`assistant_text_delta event missing delta`}))}if(t===`tool_start`){let r=F(e.toolCallId),i=F(e.toolName);return!r||!i?a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`tool_start event missing toolCallId/toolName`})):a.ok({type:t,toolCallId:r,toolName:i,argsText:P(e.argsText),atEpochMs:n})}if(t===`tool_update`){let r=F(e.toolCallId),i=F(e.toolName);return!r||!i?a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`tool_update event missing toolCallId/toolName`})):a.ok({type:t,toolCallId:r,toolName:i,partialText:P(e.partialText),atEpochMs:n})}if(t===`tool_end`){let r=F(e.toolCallId),i=F(e.toolName),o=e.status;return!r||!i||o!==`success`&&o!==`error`?a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`tool_end event missing fields or invalid status`})):a.ok({type:t,toolCallId:r,toolName:i,resultText:P(e.resultText),status:o,atEpochMs:n})}return t===`task_terminal`?e.terminal===`agent_end`?a.ok({type:t,terminal:`agent_end`,atEpochMs:n}):a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`task_terminal event has invalid terminal marker`})):a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Unsupported persisted task event type '${t}'`}))}function ur(e,t){return e.length<=t?[...e]:e.slice(e.length-t)}function dr(e,t){if(e===void 0)return a.ok([]);if(!Array.isArray(e))return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted task events must be an array`}));let n=[];for(let t of e){let e=lr(t);if(a.isError(e))return e;n.push(e.value)}return a.ok(ur(n,t))}function fr(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n.trim();e.length!==0&&t.push(e)}return t}function pr(e,t){return{provider:t?.provider??`unavailable`,model:t?.model??`unavailable`,runtime:t?.runtime??e,route:t?.route??e,promptProfile:t?.promptProfile,promptProfileSource:t?.promptProfileSource,promptProfileReason:t?.promptProfileReason}}function mr(e,t){if(!or(e))return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry must be an object`}));let n=P(e.summary);if(!n)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry missing non-empty summary`}));let r=P(e.backend);if(!r)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry missing non-empty backend`}));let i=sr(e.invocation);if(!i)return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry has invalid invocation mode`}));let o=ar(e.record);if(a.isError(o))return a.err(new C({code:`task_persistence_entry_invalid`,stage:`task_persistence`,message:`Persisted entry has invalid task record`,cause:o.error}));let s=dr(e.events,t);return a.isError(s)?a.err(s.error):a.ok({record:o.value,summary:n,backend:r,...pr(r,{provider:P(e.provider),model:P(e.model),runtime:P(e.runtime),route:P(e.route),promptProfile:P(e.promptProfile),promptProfileSource:P(e.promptProfileSource),promptProfileReason:P(e.promptProfileReason)}),invocation:i,output:P(e.output),errorCode:P(e.errorCode),errorMessage:P(e.errorMessage),followUpPrompts:fr(e.followUpPrompts),events:s.value})}function hr(e,t){if(!or(e))return a.err(new w({code:`task_persistence_invalid_shape`,resource:`task-registry`,message:`Task persistence file must contain an object root`}));if(e.schemaVersion!==1)return a.err(new w({code:`task_persistence_invalid_schema_version`,resource:`task-registry`,message:`Task persistence schema version mismatch. Expected 1.`}));if(!Array.isArray(e.entries))return a.err(new w({code:`task_persistence_invalid_shape`,resource:`task-registry`,message:`Task persistence snapshot missing 'entries' array`}));let n=[];for(let r of e.entries){let e=mr(r,t);if(a.isError(e))return a.err(new w({code:`task_persistence_entry_invalid`,resource:`task-registry`,message:e.error.message,cause:e.error}));n.push(e.value)}return a.ok(n)}function gr(e,t){let n=`${e}.corrupt-${t()}`,r=a.try({try:()=>ae(e,n),catch:()=>void 0});if(!a.isError(r))return n}function _r(e){return{filePath:e,load(){if(!ne(e))return a.ok({entries:[]});let t=a.try({try:()=>ie(e,`utf8`),catch:t=>new w({code:`task_persistence_read_failed`,resource:e,message:`Failed reading task registry at ${e}`,cause:t})});if(a.isError(t))return t;let n=a.try({try:()=>JSON.parse(t.value),catch:()=>void 0});if(a.isError(n)||n.value===void 0)return a.ok({entries:[],recoveredCorruptFilePath:gr(e,Date.now)});let r=hr(n.value,2**53-1);return a.isError(r)?a.ok({entries:[],recoveredCorruptFilePath:gr(e,Date.now)}):a.ok({entries:r.value})},save(t){let n=a.try({try:()=>(re(_(e),{recursive:!0}),oe(e,`${JSON.stringify(t,null,2)}\n`,`utf8`),!0),catch:t=>new w({code:`task_persistence_write_failed`,resource:e,message:`Failed writing task registry at ${e}`,cause:t})});return a.isError(n)?n:a.ok(!0)}}}function vr(e,t){return e===`queued`?t===`running`||t===`cancelled`:e===`running`?t===`succeeded`||t===`failed`||t===`cancelled`:!1}function I(e){return e===`succeeded`||e===`failed`||e===`cancelled`}function yr(e,t){return new C({code:`task_record_validation_failed`,stage:`task_runtime_store`,message:`Invalid task record for '${e}'`,cause:t,meta:{taskId:e}})}function br(e){return new C({code:`unknown_task_id`,stage:`task_runtime_store`,message:`Unknown task id '${e}'`,meta:{taskId:e}})}function xr(e,t){return new C({code:`task_expired`,stage:`task_runtime_store`,message:t,meta:{taskId:e}})}function Sr(e,t,n){return new C({code:`illegal_task_state_transition`,stage:`task_runtime_store`,message:`Illegal task transition for '${e}': ${t} -> ${n}`,meta:{taskId:e,from:t,to:n}})}function Cr(e,t){return new C({code:`task_not_resumable`,stage:`task_runtime_store`,message:`Task '${e}' is terminal (${t}) and cannot be resumed`,meta:{taskId:e,state:t}})}function wr(e,t){return new C({code:`task_not_running`,stage:`task_runtime_store`,message:`Task '${e}' is '${t}' and cannot complete follow-up interaction`,meta:{taskId:e,state:t}})}function L(e){return{id:e.record.id,state:e.record.state,subagentType:e.record.subagentType,description:e.record.description,prompt:e.record.prompt,followUpPrompts:e.followUpPrompts,summary:e.summary,output:e.output,backend:e.backend,provider:e.provider,model:e.model,runtime:e.runtime,route:e.route,...e.promptProfile?{promptProfile:e.promptProfile}:{},...e.promptProfileSource?{promptProfileSource:e.promptProfileSource}:{},...e.promptProfileReason?{promptProfileReason:e.promptProfileReason}:{},invocation:e.invocation,totalToolCalls:e.record.totalToolCalls,activeToolCalls:e.record.activeToolCalls,startedAtEpochMs:e.record.startedAtEpochMs,updatedAtEpochMs:e.record.updatedAtEpochMs,endedAtEpochMs:e.record.endedAtEpochMs,errorCode:e.errorCode,errorMessage:e.errorMessage,events:e.events}}function Tr(e){let t=Math.max(e.record.startedAtEpochMs,e.nowEpochMs);return{...e.record,state:`failed`,activeToolCalls:0,updatedAtEpochMs:t,endedAtEpochMs:t,lastErrorCode:`task_rehydrated_incomplete`,lastErrorMessage:`Task '${e.record.id}' restored from persistence in non-terminal state '${e.record.state}' and was marked failed`}}function R(e){let t=ar(e);return a.isError(t)?a.err(yr(e.id,t.error)):a.ok(t.value)}function Er(e,t){return e.length<=t?[...e]:e.slice(e.length-t)}function Dr(e,t){return{provider:t?.provider??`unavailable`,model:t?.model??`unavailable`,runtime:t?.runtime??e,route:t?.route??e,promptProfile:t?.promptProfile,promptProfileSource:t?.promptProfileSource,promptProfileReason:t?.promptProfileReason}}var Or=class{tasks=new Map;expiredTasks=new Map;persistenceDiagnostics=[];now;retentionMs;persistence;maxEventsPerTask;maxTasks;maxExpiredTasks;persistenceDebounceMs;pendingPersistenceTimer;constructor(e={}){this.now=e.now??(()=>Date.now()),this.retentionMs=e.retentionMs!==void 0&&e.retentionMs>0?e.retentionMs:864e5,this.persistence=e.persistence,this.maxEventsPerTask=e.maxEventsPerTask!==void 0&&e.maxEventsPerTask>0?e.maxEventsPerTask:120,this.maxTasks=e.maxTasks!==void 0&&e.maxTasks>0?e.maxTasks:200,this.maxExpiredTasks=e.maxExpiredTasks!==void 0&&e.maxExpiredTasks>0?e.maxExpiredTasks:500,this.persistenceDebounceMs=e.persistenceDebounceMs!==void 0&&e.persistenceDebounceMs>=0?Math.floor(e.persistenceDebounceMs):0,this.hydrateFromPersistence(),this.pruneExpiredTerminalTasks()}createTask(e){if(this.pruneExpiredTerminalTasks(),this.tasks.has(e.taskId))return a.err(new C({code:`duplicate_task_id`,stage:`task_runtime_store`,message:`Task id '${e.taskId}' already exists`,meta:{taskId:e.taskId}}));this.expiredTasks.delete(e.taskId);let t=this.now(),n=R({id:e.taskId,subagentType:e.subagent.id,description:e.description,prompt:e.prompt,state:`queued`,totalToolCalls:0,activeToolCalls:0,startedAtEpochMs:t,updatedAtEpochMs:t});if(a.isError(n))return n;let r={record:n.value,summary:`Queued ${e.subagent.name}: ${e.description}`,backend:e.backend,...Dr(e.backend,e.observability),invocation:e.invocation,followUpPrompts:[],events:[]};return this.tasks.set(e.taskId,r),this.pruneTaskCapacity(),this.requestPersist({immediate:!0}),a.ok(L(r))}markRunning(e,t){return this.transition(e,`running`,{summary:t,activeToolCalls:1,totalToolCallsDelta:1})}markInteractionRunning(e,t,n){this.pruneExpiredTerminalTasks();let r=this.getMutableEntry(e);if(a.isError(r))return r;let i=r.value;if(I(i.record.state))return a.err(Cr(e,i.record.state));let o=this.now(),s=R({id:i.record.id,subagentType:i.record.subagentType,description:i.record.description,prompt:i.record.prompt,state:`running`,totalToolCalls:i.record.totalToolCalls+1,activeToolCalls:1,startedAtEpochMs:i.record.startedAtEpochMs,updatedAtEpochMs:o});if(a.isError(s))return s;let c=n.trim(),l=c.length>0?[...i.followUpPrompts,c]:[...i.followUpPrompts],u={...i,record:s.value,summary:t,followUpPrompts:l};return this.tasks.set(e,u),this.requestPersist({immediate:!1}),a.ok(L(u))}markInteractionComplete(e,t,n,r){this.pruneExpiredTerminalTasks();let i=this.getMutableEntry(e);if(a.isError(i))return i;let o=i.value;if(o.record.state!==`running`)return a.err(wr(e,o.record.state));let s=this.now(),c=R({id:o.record.id,subagentType:o.record.subagentType,description:o.record.description,prompt:o.record.prompt,state:`running`,totalToolCalls:o.record.totalToolCalls,activeToolCalls:0,startedAtEpochMs:o.record.startedAtEpochMs,updatedAtEpochMs:s});if(a.isError(c))return c;let l={...o,record:c.value,summary:t,output:n,...Dr(o.backend,{provider:r?.provider??o.provider,model:r?.model??o.model,runtime:r?.runtime??o.runtime,route:r?.route??o.route,promptProfile:r?.promptProfile??o.promptProfile,promptProfileSource:r?.promptProfileSource??o.promptProfileSource,promptProfileReason:r?.promptProfileReason??o.promptProfileReason})};return this.tasks.set(e,l),this.requestPersist({immediate:!1}),a.ok(L(l))}markSucceeded(e,t,n,r){return this.transition(e,`succeeded`,{summary:t,output:n,observability:r,activeToolCalls:0,totalToolCallsDelta:0})}markFailed(e,t,n,r){return this.transition(e,`failed`,{summary:t,activeToolCalls:0,totalToolCallsDelta:0,errorCode:n,errorMessage:r})}markCancelled(e,t){this.pruneExpiredTerminalTasks();let n=this.tasks.get(e);if(!n){let t=this.expiredTasks.get(e);return t?a.err(xr(e,t)):a.err(br(e))}if(I(n.record.state))return a.ok(L(n));let r=n.abortController,i=this.transition(e,`cancelled`,{summary:t,activeToolCalls:0,totalToolCallsDelta:0});return a.isError(i)||r?.abort(),i}getTask(e){this.pruneExpiredTerminalTasks();let t=this.tasks.get(e);if(t)return L(t)}listTasks(){return this.pruneExpiredTerminalTasks(),[...this.tasks.values()].map(e=>L(e))}getTasks(e){return this.pruneExpiredTerminalTasks(),e.map(e=>{let t=this.tasks.get(e);if(t)return{id:e,found:!0,snapshot:L(t)};let n=this.expiredTasks.get(e);return n?{id:e,found:!1,errorCode:`task_expired`,errorMessage:n}:{id:e,found:!1,errorCode:`unknown_task_id`,errorMessage:`Unknown task id '${e}'`}})}updateObservability(e,t){this.pruneExpiredTerminalTasks();let n=this.getMutableEntry(e);if(a.isError(n))return n;let r=n.value,i={...r,...Dr(r.backend,{provider:t.provider??r.provider,model:t.model??r.model,runtime:t.runtime??r.runtime,route:t.route??r.route,promptProfile:t.promptProfile??r.promptProfile,promptProfileSource:t.promptProfileSource??r.promptProfileSource,promptProfileReason:t.promptProfileReason??r.promptProfileReason})};return this.tasks.set(e,i),this.requestPersist({immediate:!1}),a.ok(L(i))}setAbortController(e,t){let n=this.getMutableEntry(e);if(a.isError(n))return n;let r=n.value;return this.tasks.set(e,{...r,abortController:t}),a.ok(!0)}getAbortController(e){return this.tasks.get(e)?.abortController}setExecutionPromise(e,t){let n=this.getMutableEntry(e);if(a.isError(n))return n;let r=n.value;return this.tasks.set(e,{...r,executionPromise:t}),a.ok(!0)}getExecutionPromise(e){return this.tasks.get(e)?.executionPromise}appendEvents(e,t){this.pruneExpiredTerminalTasks();let n=this.getMutableEntry(e);if(a.isError(n))return n;let r=n.value;if(t.length===0)return a.ok(L(r));let i=Er([...r.events,...t],this.maxEventsPerTask),o={...r,events:i};return this.tasks.set(e,o),this.requestPersist({immediate:!1}),a.ok(L(o))}getPersistenceDiagnostics(){return this.persistenceDiagnostics}getMutableEntry(e){let t=this.tasks.get(e);if(t)return a.ok(t);let n=this.expiredTasks.get(e);return n?a.err(xr(e,n)):a.err(br(e))}transition(e,t,n){this.pruneExpiredTerminalTasks();let r=this.getMutableEntry(e);if(a.isError(r))return r;let i=r.value;if(!vr(i.record.state,t))return a.err(Sr(e,i.record.state,t));let o=this.now(),s=i.record.totalToolCalls+n.totalToolCallsDelta,c={id:i.record.id,subagentType:i.record.subagentType,description:i.record.description,prompt:i.record.prompt,state:t,totalToolCalls:s,activeToolCalls:n.activeToolCalls,startedAtEpochMs:i.record.startedAtEpochMs,updatedAtEpochMs:o},l=R(t===`queued`||t===`running`?{...c,state:t}:{...c,state:t,endedAtEpochMs:o,lastErrorCode:n.errorCode,lastErrorMessage:n.errorMessage});if(a.isError(l))return l;let u={...i,record:l.value,summary:n.summary,output:n.output,...Dr(i.backend,{provider:n.observability?.provider??i.provider,model:n.observability?.model??i.model,runtime:n.observability?.runtime??i.runtime,route:n.observability?.route??i.route,promptProfile:n.observability?.promptProfile??i.promptProfile,promptProfileSource:n.observability?.promptProfileSource??i.promptProfileSource,promptProfileReason:n.observability?.promptProfileReason??i.promptProfileReason}),errorCode:n.errorCode,errorMessage:n.errorMessage,abortController:I(t)?void 0:i.abortController,executionPromise:I(t)?void 0:i.executionPromise};return this.tasks.set(e,u),this.requestPersist({immediate:I(t)}),a.ok(L(u))}hydrateFromPersistence(){if(!this.persistence)return;let e=this.persistence.load();if(a.isError(e)){this.persistenceDiagnostics.push(e.error.message);return}e.value.recoveredCorruptFilePath&&this.persistenceDiagnostics.push(`Recovered corrupt task registry snapshot: ${e.value.recoveredCorruptFilePath}`);let t=!1;for(let n of e.value.entries){let e=R(n.record.state===`queued`||n.record.state===`running`?Tr({record:n.record,nowEpochMs:this.now()}):n.record);if(a.isError(e)){this.persistenceDiagnostics.push(e.error.message);continue}let r=n.record.state!==e.value.state;r&&(t=!0,this.persistenceDiagnostics.push(`Task '${n.record.id}' restored from non-terminal '${n.record.state}' state and marked failed`));let i={record:e.value,summary:r?`Task '${n.record.id}' recovered from non-terminal state and marked failed`:n.summary,output:n.output,backend:n.backend,provider:n.provider,model:n.model,runtime:n.runtime,route:n.route,promptProfile:n.promptProfile,promptProfileSource:n.promptProfileSource,promptProfileReason:n.promptProfileReason,invocation:n.invocation,followUpPrompts:n.followUpPrompts,events:Er(n.events,this.maxEventsPerTask),errorCode:r?`task_rehydrated_incomplete`:n.errorCode,errorMessage:r?`Task '${n.record.id}' restored from persistence in non-terminal state '${n.record.state}' and was marked failed`:n.errorMessage};this.tasks.set(e.value.id,i)}let n=this.tasks.size;this.pruneTaskCapacity(),this.tasks.size!==n&&(t=!0),t&&this.requestPersist({immediate:!0})}pruneExpiredTerminalTasks(){let e=!1,t=this.now();for(let[n,r]of this.tasks.entries())I(r.record.state)&&r.record.endedAtEpochMs!==void 0&&(t-r.record.endedAtEpochMs<this.retentionMs||(this.tasks.delete(n),this.rememberExpiredTask(n,`Task id '${n}' expired by retention policy after ${this.retentionMs}ms`),e=!0));e&&this.requestPersist({immediate:!1})}rememberExpiredTask(e,t){for(this.expiredTasks.delete(e),this.expiredTasks.set(e,t);this.expiredTasks.size>this.maxExpiredTasks;){let e=this.expiredTasks.keys().next();if(e.done)return;this.expiredTasks.delete(e.value)}}pruneTaskCapacity(){if(this.tasks.size<=this.maxTasks)return;let e=[...this.tasks.entries()].filter(([,e])=>I(e.record.state)).sort((e,t)=>(e[1].record.endedAtEpochMs??e[1].record.updatedAtEpochMs)-(t[1].record.endedAtEpochMs??t[1].record.updatedAtEpochMs));for(let[t]of e){if(this.tasks.size<=this.maxTasks)return;this.tasks.delete(t),this.rememberExpiredTask(t,`Task id '${t}' evicted by capacity policy after reaching max ${this.maxTasks} tasks`)}}requestPersist(e){if(!this.persistence)return;if(e.immediate||this.persistenceDebounceMs===0){this.flushPendingPersistenceTimer(),this.persistCurrentState();return}if(this.pendingPersistenceTimer)return;let t=setTimeout(()=>{this.pendingPersistenceTimer=void 0,this.persistCurrentState()},this.persistenceDebounceMs);t.unref?.(),this.pendingPersistenceTimer=t}flushPendingPersistenceTimer(){this.pendingPersistenceTimer&&=(clearTimeout(this.pendingPersistenceTimer),void 0)}persistCurrentState(){if(!this.persistence)return;let e={schemaVersion:1,savedAtEpochMs:this.now(),entries:[...this.tasks.values()].map(e=>({record:e.record,summary:e.summary,output:e.output,backend:e.backend,provider:e.provider,model:e.model,runtime:e.runtime,route:e.route,promptProfile:e.promptProfile,promptProfileSource:e.promptProfileSource,promptProfileReason:e.promptProfileReason,invocation:e.invocation,followUpPrompts:e.followUpPrompts,errorCode:e.errorCode,errorMessage:e.errorMessage,events:e.events}))},t=this.persistence.save(e);a.isError(t)&&this.persistenceDiagnostics.push(t.error.message)}};function kr(e={}){return new Or(e)}function z(e){let t=process.env[e];if(!t)return;let n=Number.parseInt(t,10);if(!(Number.isNaN(n)||n<=0))return n}function Ar(e){let t=process.env[e];if(!t)return;let n=Number.parseInt(t,10);if(!(Number.isNaN(n)||n<0))return n}function jr(){return z(`OHM_SUBAGENTS_TASK_RETENTION_MS`)}function Mr(){return z(`OHM_SUBAGENTS_TASK_MAX_EVENTS`)}function Nr(){return z(`OHM_SUBAGENTS_TASK_MAX_ENTRIES`)}function Pr(){return z(`OHM_SUBAGENTS_TASK_MAX_EXPIRED_ENTRIES`)}function Fr(){let e=Ar(`OHM_SUBAGENTS_TASK_PERSIST_DEBOUNCE_MS`);return e===void 0?90:e}function Ir(e){let t=process.env[e];if(!t)return;let n=t.trim();if(n.length!==0)return n}function Lr(){let e=z(`OHM_SUBAGENTS_ONUPDATE_THROTTLE_MS`);return e===void 0?120:e}function Rr(){return Ir(`OHM_SUBAGENTS_TASK_PERSIST_PATH`)||ee(te(),`ohm.subagents.tasks.json`)}const zr=kr({persistence:_r(Rr()),retentionMs:jr(),maxEventsPerTask:Mr(),maxTasks:Nr(),maxExpiredTasks:Pr(),persistenceDebounceMs:Fr()});let Br=0;function Vr(e=Date.now()){return Br+=1,`task_${e}_${Br.toString().padStart(4,`0`)}`}function Hr(){return{loadConfig:t,backend:Yn(),findSubagentById:Se,subagents:x,createTaskId:Vr,taskStore:zr}}const B=h.String({minLength:1}),Ur=h.Integer({minimum:1}),Wr=h.Object({subagent_type:B,description:B,prompt:B,async:h.Optional(h.Boolean())},{additionalProperties:!1}),Gr=h.Object({op:h.Literal(`start`),subagent_type:B,description:B,prompt:B,async:h.Optional(h.Boolean())},{additionalProperties:!1}),Kr=h.Object({op:h.Literal(`start`),tasks:h.Array(Wr,{minItems:1}),parallel:h.Optional(h.Boolean()),async:h.Optional(h.Boolean())},{additionalProperties:!1}),qr=h.Object({op:h.Literal(`status`),ids:h.Array(B,{minItems:1})},{additionalProperties:!1}),Jr=h.Object({op:h.Literal(`wait`),ids:h.Array(B,{minItems:1}),timeout_ms:h.Optional(Ur)},{additionalProperties:!1}),Yr=h.Object({op:h.Literal(`send`),id:B,prompt:B},{additionalProperties:!1}),Xr=h.Object({op:h.Literal(`cancel`),id:B},{additionalProperties:!1}),Zr=h.Union([Gr,Kr,qr,Jr,Yr,Xr]),Qr=h.Object({op:B,subagent_type:h.Optional(B),description:h.Optional(B),prompt:h.Optional(B),async:h.Optional(h.Boolean()),tasks:h.Optional(h.Array(Wr,{minItems:1})),parallel:h.Optional(h.Boolean()),ids:h.Optional(h.Array(B,{minItems:1})),timeout_ms:h.Optional(Ur),id:h.Optional(B)},{additionalProperties:!1}),$r=[Gr,Kr,qr,Jr,Yr,Xr];function ei(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ti(e){if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)return t}function ni(e){if(Array.isArray(e)){let t=e.map(e=>ti(e)).filter(e=>typeof e==`string`);return t.length===0?void 0:t}let t=ti(e);if(t)return[t]}function ri(e){if(typeof e==`boolean`)return e}function ii(e){if(typeof e==`number`&&Number.isInteger(e))return e}function ai(e){return ei(e)?{subagent_type:Reflect.get(e,`subagent_type`),description:Reflect.get(e,`description`),prompt:Reflect.get(e,`prompt`),async:ri(Reflect.get(e,`async`))}:e}function oi(e){if(!ei(e))return e;let t=ti(Reflect.get(e,`op`));if(!t)return e;let n=t===`result`?`status`:t;if(n===`start`){let t=Reflect.get(e,`tasks`);return Array.isArray(t)?{op:`start`,tasks:t.map(e=>ai(e)),parallel:ri(Reflect.get(e,`parallel`)),async:ri(Reflect.get(e,`async`))}:{op:`start`,subagent_type:Reflect.get(e,`subagent_type`),description:Reflect.get(e,`description`),prompt:Reflect.get(e,`prompt`),async:ri(Reflect.get(e,`async`))}}return n===`status`?{op:`status`,ids:ni(Reflect.get(e,`ids`)??Reflect.get(e,`id`))}:n===`wait`?{op:`wait`,ids:ni(Reflect.get(e,`ids`)??Reflect.get(e,`id`)),timeout_ms:ii(Reflect.get(e,`timeout_ms`))}:n===`send`?{op:`send`,id:Reflect.get(e,`id`),prompt:Reflect.get(e,`prompt`)}:n===`cancel`?{op:`cancel`,id:Reflect.get(e,`id`)}:e}function si(e){let t=er(ve.Errors(Zr,e).First()?.path);if(t)return t;let n,r=-1;for(let t of $r){let i=er(ve.Errors(t,e).First()?.path);if(!i)continue;let a=i.split(`.`).length;a>r&&(r=a,n=i)}return n}function ci(e){let t=oi(e);if(!ve.Check(Zr,t)){let e=si(t);return a.err(new we({code:`invalid_task_tool_payload`,path:e,message:e?`Task tool payload failed validation at ${e}`:`Task tool payload failed validation`}))}return a.ok(ve.Decode(Zr,t))}function li(e){return e.length===0?`tool`:`${e[0]?.toUpperCase()??``}${e.slice(1)}`}function ui(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)return t}function di(e,t=88){let n=e.trim();return n.length<=t?n:`${n.slice(0,Math.max(t-1,1))}…`}function fi(e){let t=V(e);if(t&&t.startsWith(`{`))try{let e=JSON.parse(t);return ui(e)?e:void 0}catch{return}}function pi(e,t){let n=Reflect.get(e,t);if(typeof n==`number`&&!(!Number.isInteger(n)||n<=0))return n}function mi(e,t){let n=fi(t),r=e.trim().toLowerCase();if(!n){if(r===`bash`){let e=V(t);return e?di(e):void 0}return}if(r===`bash`){let e=V(Reflect.get(n,`command`));return e?di(e):void 0}if(r===`read`||r===`write`||r===`edit`){let e=V(Reflect.get(n,`path`));if(!e)return;let t=pi(n,`offset`),r=pi(n,`limit`);return t!==void 0&&r!==void 0?`${e} @${t}-${t+r-1}`:t===void 0?e:`${e} @${t}`}if(r===`grep`){let e=V(Reflect.get(n,`pattern`))??V(Reflect.get(n,`query`));return e?di(e):void 0}if(r===`glob`||r===`find`||r===`ls`){let e=V(Reflect.get(n,`pattern`))??V(Reflect.get(n,`path`))??V(Reflect.get(n,`query`));return e?di(e):void 0}}function hi(e){return mi(e.toolName,e.argsText)}function gi(e){let t=e.match(/^tool_call:\s*(\S+)\s+(start|update|end success|end error)\s*(.*)$/iu);if(!t)return;let n=t[1]?.trim(),r=t[2]?.trim().toLowerCase(),i=V(t[3]);if(!(!n||!r)&&!(r!==`start`&&r!==`update`&&r!==`end success`&&r!==`end error`))return{toolName:n,phase:r,payload:i}}function _i(e){let t=[];for(let n of e){let e=gi(n);if(!e)continue;if(e.phase===`start`){t.push({toolName:e.toolName,outcome:`running`,detail:mi(e.toolName,e.payload)});continue}let r=(()=>{for(let n=t.length-1;n>=0;--n){let r=t[n];if(r&&r.toolName===e.toolName&&r.outcome===`running`)return n}return-1})();if(r<0){t.push({toolName:e.toolName,outcome:e.phase===`end error`?`error`:`running`});continue}let i=t[r];if(i){if(e.phase===`end success`){i.outcome=`success`;continue}if(e.phase===`end error`){i.outcome=`error`;continue}i.detail||=mi(e.toolName,e.payload)}}return t.map(e=>{let t=e.outcome===`success`?`✓`:e.outcome===`error`?`✕`:`○`,n=e.detail?` ${e.detail}`:``;return`${t} ${li(e.toolName)}${n}`})}function vi(e){let t=[],n=new Map;for(let r of e){if(r.type!==`tool_start`&&r.type!==`tool_update`&&r.type!==`tool_end`)continue;let e=n.get(r.toolCallId);if(!e){t.push(r.toolCallId),n.set(r.toolCallId,{toolName:r.toolName,outcome:r.type===`tool_end`?r.status===`error`?`error`:`success`:`running`,detail:r.type===`tool_start`?hi(r):void 0});continue}if(r.type===`tool_start`){n.set(r.toolCallId,{toolName:e.toolName,outcome:e.outcome,detail:e.detail??hi(r)});continue}r.type===`tool_end`&&n.set(r.toolCallId,{toolName:e.toolName,outcome:r.status===`error`?`error`:`success`,detail:e.detail})}return t.map(e=>{let t=n.get(e);if(!t)return`○ Tool`;let r=t.outcome===`success`?`✓`:t.outcome===`error`?`✕`:`○`,i=t.detail?` ${t.detail}`:``;return`${r} ${li(t.toolName)}${i}`})}function yi(e){let t=e.filter(e=>e.type===`assistant_text_delta`).map(e=>e.delta);if(t.length===0)return;let n=t.join(``).trim();if(n.length!==0)return n}function bi(e){return e.replace(/^(assistant|user|system)\s*[:>]\s*/iu,``).trim().replace(/^tool(?:\([^)]+\))?\s*[:>]\s*/iu,``).trim()}function xi(e){return!!(/^[✓✕○•…⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]\s+/u.test(e)||/^(Read|Glob|Grep|Find|Search|Bash|Edit|Write|Ls)\b/u.test(e)||/^tool_call\s*[:>]/iu.test(e)||/^\$\s+.+/u.test(e))}function Si(e){let t=e.trim();return t.length===0?`✓ (empty tool line)`:/^[✓✕○•…⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]\s+/u.test(t)?t:`✓ ${t}`}function Ci(e,t={}){let n=e.split(/\r?\n/u).map(e=>bi(e.trim())).filter(e=>e.length>0);if(n.length===0)return{toolCalls:[],narrativeLines:[]};let r=t.normalizeDetectedToolCalls??!1,i=[],a=[],o=[];for(let e of n){if(gi(e)){a.push(e);continue}if(xi(e)){i.push(r?Si(e):e);continue}o.push(e)}let s=_i(a);return{toolCalls:s.length>0?[...s,...i]:i,narrativeLines:o}}function H(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString()}function wi(e){if(typeof e!=`string`)return`(no output)`;let t=Ci(e);if(t.narrativeLines.length>0)return t.narrativeLines.join(`
10
+ `);let n=e.trim();return n.length>0?n:`(no output)`}function Ti(e){if(e.outputAvailable===!0&&e.source!==`output`)throw Error(`task transport invariant violated (${e.scope}): output_available=true requires result_source=output, received '${e.source}'`)}function Ei(e){if(e.output_available===!0){let t={text:wi(e.output),source:`output`};return Ti({outputAvailable:e.output_available,source:t.source,scope:e.scope}),t}let t=e.assistant_text?.trim();return t&&t.length>0?{text:t,source:`assistant_text`}:{text:e.error_message&&e.error_message.length>0?e.error_message:e.summary,source:`summary`}}function Di(e){return e.found?Ei({output_available:e.output_available,output:e.output,assistant_text:e.assistant_text,summary:e.summary,error_message:e.error_message,scope:`item:${e.id}`}):{text:e.error_message??e.summary,source:`summary`}}function Oi(e){let t=Ei({output_available:e.output_available,output:e.output,assistant_text:e.assistant_text,summary:e.summary,error_message:e.error_message,scope:`op:${e.op}`});if(t.source!==`summary`)return t;if(e.items&&e.items.length===1){let[t]=e.items;if(t&&t.found)return Di(t)}return t}function ki(e){let t=new Set,n=e=>{if(!e)return;let n=e.trim();n.length!==0&&t.add(n)};n(e.task_id);for(let t of e.items??[])n(t.id);return[...t]}function Ai(e){let[t]=ki(e);return t||`unavailable`}function ji(e){if(!e.items||e.items.length===0)return;let t;for(let n of e.items){let r=n.ended_at_epoch_ms??n.updated_at_epoch_ms??e.ended_at_epoch_ms;typeof r!=`number`||!Number.isFinite(r)||(t=t===void 0?r:Math.max(t,r))}return H(t)}function Mi(e){let t=H(e.ended_at_epoch_ms)??H(e.updated_at_epoch_ms);if(t)return t;let n=ji(e);if(n)return n;if(e.items&&e.items.length===1){let[t]=e.items;if(t){let e=H(t.ended_at_epoch_ms)??H(t.updated_at_epoch_ms);if(e)return e}}return`unavailable`}function Ni(e,t){let n=e.found?e.status??`failed`:`failed`,r=e.subagent_type??`unknown`,i=e.description?` · ${e.description}`:``,a=Di(e).text.split(`
11
+ `),o=[`- ${t+1}. ${e.id} [${n}] ${r}${i}`];if(a.length<=1)return o.push(` result: ${a[0]??``}`),o;o.push(` result:`);for(let e of a)o.push(` ${e}`);return o}function Pi(e,t){let n=ki(e),r=Ai(e),i=Mi(e),a=[`task_id: ${r}`,...n.length>1?[`task_ids: ${n.join(`, `)}`]:[],`status: ${e.status}`,...e.subagent_type?[`subagent: ${e.subagent_type}`]:[],`backend: ${e.backend}`,`provider: ${e.provider??`unavailable`}`,`model: ${e.model??`unavailable`}`,`runtime: ${e.runtime??e.backend}`,`route: ${e.route??e.backend}`,`timestamp: ${i}`,`result:`,t];if(e.items&&e.items.length>1){a.push(`items:`);for(let[t,n]of e.items.entries())a.push(...Ni(n,t))}return a.join(`
12
+ `)}function Fi(e){let t=Oi(e);return{text:Pi(e,t.text),resultSource:t.source}}function Ii(e){return e===`unknown_task_id`||e===`task_expired`||e.includes(`not_found`)?`not_found`:e.startsWith(`invalid_`)||e.includes(`validation`)||e.includes(`payload`)||e.includes(`unknown_operation`)?`validation`:e.includes(`permission`)||e.includes(`policy`)||e.includes(`internal_subagent`)?`policy`:e.includes(`persistence`)||e.includes(`corrupt`)||e.includes(`retention`)?`persistence`:`runtime`}function Li(e){return!e.error_code||e.error_category?e:{...e,error_category:Ii(e.error_code)}}function Ri(e){return!e.error_code||e.error_category?e:{...e,error_category:Ii(e.error_code)}}function zi(e){return{...e,provider:e.provider??`unavailable`,model:e.model??`unavailable`,runtime:e.runtime??e.backend,route:e.route??e.backend}}function Bi(e){return{...e,provider:e.provider??`unavailable`,model:e.model??`unavailable`,runtime:e.runtime??e.backend??`unavailable`,route:e.route??e.backend??`unavailable`}}function Vi(){let e=process.env.OHM_DEBUG?.trim().toLowerCase();return e?e===`1`||e===`true`:!1}function Hi(){if(Vi())return!0;let e=process.env.OHM_SUBAGENTS_PROMPT_PROFILE_DEBUG?.trim().toLowerCase();return e?e===`1`||e===`true`:!1}function Ui(e){return e===`queued`?`queued`:e===`running`?`running`:e===`succeeded`?`succeeded`:e===`failed`?`failed`:`cancelled`}function Wi(e){return e.length===0?e:`${e[0]?.toUpperCase()??``}${e.slice(1)}`}function Gi(e){return Ci(e,{normalizeDetectedToolCalls:!0})}function Ki(e){if(e.sections.narrativeLines.length>0)return e.expanded?e.sections.narrativeLines.join(`
13
13
  `):e.sections.narrativeLines.slice(0,2).join(`
14
- `)}function Gi(e){return e.outputTruncated?typeof e.outputReturnedChars==`number`&&typeof e.outputTotalChars==`number`?`${e.result} (truncated ${e.outputReturnedChars}/${e.outputTotalChars} chars)`:`${e.result} (truncated)`:e.result}function Ki(e){return e.status===`running`||e.status===`queued`?`Working...`:e.status===`failed`?e.errorMessage??`Task failed.`:e.status===`cancelled`?e.errorMessage??`Task cancelled.`:e.assistantText&&e.assistantText.length>0?e.assistantText:e.errorMessage??e.summary}function qi(e){return e.subagentType&&e.description?`${Hi(e.subagentType)} · ${e.description}`:e.subagentType?Hi(e.subagentType):e.description??e.summary}function Ji(e,t){let n=e.output_available&&e.output?Ui(e.output):void 0,r=e.tool_rows&&e.tool_rows.length>0?e.tool_rows:n?.toolCalls??[],i=Gi({result:(n?Wi({sections:n,expanded:t}):void 0)??Ki({status:e.status,summary:e.summary,errorMessage:e.error_message,assistantText:e.assistant_text}),outputTruncated:e.output_truncated,outputReturnedChars:e.output_returned_chars,outputTotalChars:e.output_total_chars});return{id:e.task_id??`${e.op}_task`,status:Vi(e.status),title:qi({subagentType:e.subagent_type,description:e.description,summary:e.summary}),prompt:e.prompt??e.description??e.summary,toolCalls:r,result:i}}function Yi(e,t){if(!e.found)return{id:e.id,status:`failed`,title:`Task ${e.id}`,prompt:`Resolve task ${e.id}`,toolCalls:[],result:e.error_message??`Unknown task id.`};let n=e.status??`failed`,r=e.output_available&&e.output?Ui(e.output):void 0,i=e.tool_rows&&e.tool_rows.length>0?e.tool_rows:r?.toolCalls??[],a=Gi({result:(r?Wi({sections:r,expanded:t}):void 0)??Ki({status:n,summary:e.summary,errorMessage:e.error_message,assistantText:e.assistant_text}),outputTruncated:e.output_truncated,outputReturnedChars:e.output_returned_chars,outputTotalChars:e.output_total_chars});return{id:e.id,status:Vi(n),title:qi({subagentType:e.subagent_type,description:e.description,summary:e.summary}),prompt:e.prompt??e.description??e.summary,toolCalls:i,result:a}}function Xi(e){return e?{compact:!1,maxPromptLines:16,maxToolCalls:2**53-1,maxResultLines:2**53-1}:{compact:!0,maxPromptLines:2**53-1,maxToolCalls:2,maxResultLines:2}}function Zi(e,t){let n=[...f({entries:Qi(e,t),width:120,options:Xi(t)})];return e.wait_status&&e.wait_status!==`completed`&&n.push(`wait: ${e.wait_status}${e.done?` (done)`:``}`),typeof e.accepted_count==`number`&&typeof e.total_count==`number`&&n.push(`batch: accepted ${e.accepted_count}/${e.total_count}`),e.route&&e.route!==e.backend&&(n.push(`route fallback: ${e.backend} -> ${e.route}`),e.route===`interactive-shell`&&n.push(`note: live sdk tool streaming unavailable on interactive-shell fallback`)),n.join(`
15
- `)}function Qi(e,t){return e.items&&e.items.length>0?e.items.map(e=>Yi(e,t)):[Ji(e,t)]}function $i(e,t){return d({entries:Qi(e,t),options:Xi(t)})}function ea(e,t){let n=[`summary: ${e.summary}`];if(e.task_id&&n.push(`task_id: ${e.task_id}`),e.subagent_type&&n.push(`subagent_type: ${e.subagent_type}`),e.prompt&&n.push(`prompt: ${e.prompt}`),e.description&&n.push(`description: ${e.description}`),n.push(`status: ${e.status}`),n.push(`backend: ${e.backend}`),e.provider&&n.push(`provider: ${e.provider}`),e.model&&n.push(`model: ${e.model}`),e.runtime&&n.push(`runtime: ${e.runtime}`),e.route&&n.push(`route: ${e.route}`),Bi()&&(e.prompt_profile&&n.push(`prompt_profile: ${e.prompt_profile}`),e.prompt_profile_source&&n.push(`prompt_profile_source: ${e.prompt_profile_source}`),e.prompt_profile_reason&&n.push(`prompt_profile_reason: ${e.prompt_profile_reason}`)),e.invocation&&n.push(`invocation: ${e.invocation}`),e.wait_status&&n.push(`wait_status: ${e.wait_status}`),typeof e.done==`boolean`&&n.push(`done: ${e.done?`true`:`false`}`),typeof e.cancel_applied==`boolean`&&n.push(`cancel_applied: ${e.cancel_applied?`true`:`false`}`),e.prior_status&&n.push(`prior_status: ${e.prior_status}`),typeof e.total_count==`number`&&n.push(`total_count: ${e.total_count}`),typeof e.accepted_count==`number`&&n.push(`accepted_count: ${e.accepted_count}`),typeof e.rejected_count==`number`&&n.push(`rejected_count: ${e.rejected_count}`),e.batch_status&&n.push(`batch_status: ${e.batch_status}`),e.error_code&&n.push(`error_code: ${e.error_code}`),e.error_category&&n.push(`error_category: ${e.error_category}`),e.error_message&&n.push(`error_message: ${e.error_message}`),typeof e.result_chars_total==`number`&&n.push(`result_chars_total: ${e.result_chars_total}`),typeof e.result_chars_to_agent==`number`&&n.push(`result_chars_to_agent: ${e.result_chars_to_agent}`),typeof e.result_chars_to_ui==`number`&&n.push(`result_chars_to_ui: ${e.result_chars_to_ui}`),typeof e.ui_truncated==`boolean`&&n.push(`ui_truncated: ${e.ui_truncated?`true`:`false`}`),typeof e.event_count==`number`&&n.push(`event_count: ${e.event_count}`),e.assistant_text&&n.push(`assistant_text: ${e.assistant_text}`),e.timed_out&&n.push(`timed_out: true`),e.items!==void 0&&e.items.length>0&&(e.provider===`mixed`||e.model===`mixed`||e.runtime===`mixed`||e.route===`mixed`||e.prompt_profile===`mixed`||e.prompt_profile_source===`mixed`||e.prompt_profile_reason===`mixed`)){n.push(``,`batch_observability:`);for(let t of e.items??[]){if(!t.found){n.push(`- ${t.id}: unknown`);continue}let e=t.provider??`unavailable`,r=t.model??`unavailable`,i=t.runtime??t.backend??`unavailable`,a=t.route??t.backend??`unavailable`,o=t.prompt_profile??`unavailable`,s=t.prompt_profile_source??`unavailable`,c=t.prompt_profile_reason??`unavailable`;n.push(`- ${t.id}: provider=${e} model=${r} runtime=${i} route=${a}`),Bi()&&n.push(` prompt_profile=${o} source=${s} reason=${c}`)}}if(e.tool_rows&&e.tool_rows.length>0){n.push(``,`tool_rows:`);for(let t of e.tool_rows)n.push(`- ${t}`)}if(e.output_available&&e.output){n.push(``,`output:`);for(let t of e.output.split(`
16
- `))n.push(t);e.output_truncated&&(n.push(`output_truncated: true`),typeof e.output_total_chars==`number`&&n.push(`output_total_chars: ${e.output_total_chars}`),typeof e.output_returned_chars==`number`&&n.push(`output_returned_chars: ${e.output_returned_chars}`))}if(e.items&&e.items.length>0){n.push(``,`items:`);for(let r of e.items){if(!r.found){n.push(`- ${r.id}: unknown (${r.error_code??`unknown_task_id`})`);continue}let e=r.status??`failed`,i=r.subagent_type??`unknown`,a=r.description??``,o=a.length>0?`${r.id}: ${e} ${i} · ${a}`:`${r.id}: ${e} ${i}`;if(n.push(`- ${o}`),t){if(n.push(` summary: ${r.summary}`),r.backend&&n.push(` backend: ${r.backend}`),r.provider&&n.push(` provider: ${r.provider}`),r.model&&n.push(` model: ${r.model}`),r.runtime&&n.push(` runtime: ${r.runtime}`),r.route&&n.push(` route: ${r.route}`),Bi()&&(r.prompt_profile&&n.push(` prompt_profile: ${r.prompt_profile}`),r.prompt_profile_source&&n.push(` prompt_profile_source: ${r.prompt_profile_source}`),r.prompt_profile_reason&&n.push(` prompt_profile_reason: ${r.prompt_profile_reason}`)),r.prompt&&n.push(` prompt: ${r.prompt}`),r.output_available&&r.output){n.push(` output:`);for(let e of r.output.split(`
14
+ `)}function qi(e){return e.outputTruncated?typeof e.outputReturnedChars==`number`&&typeof e.outputTotalChars==`number`?`${e.result} (truncated ${e.outputReturnedChars}/${e.outputTotalChars} chars)`:`${e.result} (truncated)`:e.result}function Ji(e){return e.status===`running`||e.status===`queued`?`Working...`:e.status===`failed`?e.errorMessage??`Task failed.`:e.status===`cancelled`?e.errorMessage??`Task cancelled.`:e.assistantText&&e.assistantText.length>0?e.assistantText:e.errorMessage??e.summary}function Yi(e){return e.subagentType&&e.description?`${Wi(e.subagentType)} · ${e.description}`:e.subagentType?Wi(e.subagentType):e.description??e.summary}function Xi(e,t){let n=e.output_available&&e.output?Gi(e.output):void 0,r=e.tool_rows&&e.tool_rows.length>0?e.tool_rows:n?.toolCalls??[],i=qi({result:(n?Ki({sections:n,expanded:t}):void 0)??Ji({status:e.status,summary:e.summary,errorMessage:e.error_message,assistantText:e.assistant_text}),outputTruncated:e.output_truncated,outputReturnedChars:e.output_returned_chars,outputTotalChars:e.output_total_chars});return{id:e.task_id??`${e.op}_task`,status:Ui(e.status),title:Yi({subagentType:e.subagent_type,description:e.description,summary:e.summary}),prompt:e.prompt??e.description??e.summary,toolCalls:r,result:i}}function Zi(e,t){if(!e.found)return{id:e.id,status:`failed`,title:`Task ${e.id}`,prompt:`Resolve task ${e.id}`,toolCalls:[],result:e.error_message??`Unknown task id.`};let n=e.status??`failed`,r=e.output_available&&e.output?Gi(e.output):void 0,i=e.tool_rows&&e.tool_rows.length>0?e.tool_rows:r?.toolCalls??[],a=qi({result:(r?Ki({sections:r,expanded:t}):void 0)??Ji({status:n,summary:e.summary,errorMessage:e.error_message,assistantText:e.assistant_text}),outputTruncated:e.output_truncated,outputReturnedChars:e.output_returned_chars,outputTotalChars:e.output_total_chars});return{id:e.id,status:Ui(n),title:Yi({subagentType:e.subagent_type,description:e.description,summary:e.summary}),prompt:e.prompt??e.description??e.summary,toolCalls:i,result:a}}function Qi(e){return e?{compact:!1,maxPromptLines:16,maxToolCalls:2**53-1,maxResultLines:2**53-1}:{compact:!0,maxPromptLines:2,maxToolCalls:2,maxResultLines:2}}function $i(e,t){let n=[...f({entries:ea(e,t),width:120,options:Qi(t)})];return e.wait_status&&e.wait_status!==`completed`&&n.push(`wait: ${e.wait_status}${e.done?` (done)`:``}`),typeof e.accepted_count==`number`&&typeof e.total_count==`number`&&n.push(`batch: accepted ${e.accepted_count}/${e.total_count}`),e.route&&e.route!==e.backend&&(n.push(`route fallback: ${e.backend} -> ${e.route}`),e.route===`interactive-shell`&&n.push(`note: live sdk tool streaming unavailable on interactive-shell fallback`)),n.join(`
15
+ `)}function ea(e,t){return e.items&&e.items.length>0?e.items.map(e=>Zi(e,t)):[Xi(e,t)]}function ta(e,t){return d({entries:ea(e,t),options:Qi(t)})}function na(e,t){let n=[`summary: ${e.summary}`];if(e.task_id&&n.push(`task_id: ${e.task_id}`),e.subagent_type&&n.push(`subagent_type: ${e.subagent_type}`),e.prompt&&n.push(`prompt: ${e.prompt}`),e.description&&n.push(`description: ${e.description}`),n.push(`status: ${e.status}`),n.push(`backend: ${e.backend}`),e.provider&&n.push(`provider: ${e.provider}`),e.model&&n.push(`model: ${e.model}`),e.runtime&&n.push(`runtime: ${e.runtime}`),e.route&&n.push(`route: ${e.route}`),Hi()&&(e.prompt_profile&&n.push(`prompt_profile: ${e.prompt_profile}`),e.prompt_profile_source&&n.push(`prompt_profile_source: ${e.prompt_profile_source}`),e.prompt_profile_reason&&n.push(`prompt_profile_reason: ${e.prompt_profile_reason}`)),e.invocation&&n.push(`invocation: ${e.invocation}`),e.wait_status&&n.push(`wait_status: ${e.wait_status}`),typeof e.done==`boolean`&&n.push(`done: ${e.done?`true`:`false`}`),typeof e.cancel_applied==`boolean`&&n.push(`cancel_applied: ${e.cancel_applied?`true`:`false`}`),e.prior_status&&n.push(`prior_status: ${e.prior_status}`),typeof e.total_count==`number`&&n.push(`total_count: ${e.total_count}`),typeof e.accepted_count==`number`&&n.push(`accepted_count: ${e.accepted_count}`),typeof e.rejected_count==`number`&&n.push(`rejected_count: ${e.rejected_count}`),e.batch_status&&n.push(`batch_status: ${e.batch_status}`),e.error_code&&n.push(`error_code: ${e.error_code}`),e.error_category&&n.push(`error_category: ${e.error_category}`),e.error_message&&n.push(`error_message: ${e.error_message}`),typeof e.result_chars_total==`number`&&n.push(`result_chars_total: ${e.result_chars_total}`),typeof e.result_chars_to_agent==`number`&&n.push(`result_chars_to_agent: ${e.result_chars_to_agent}`),typeof e.result_chars_to_ui==`number`&&n.push(`result_chars_to_ui: ${e.result_chars_to_ui}`),e.result_source&&n.push(`result_source: ${e.result_source}`),typeof e.ui_truncated==`boolean`&&n.push(`ui_truncated: ${e.ui_truncated?`true`:`false`}`),typeof e.event_count==`number`&&n.push(`event_count: ${e.event_count}`),e.assistant_text&&n.push(`assistant_text: ${e.assistant_text}`),e.timed_out&&n.push(`timed_out: true`),e.items!==void 0&&e.items.length>0&&(e.provider===`mixed`||e.model===`mixed`||e.runtime===`mixed`||e.route===`mixed`||e.prompt_profile===`mixed`||e.prompt_profile_source===`mixed`||e.prompt_profile_reason===`mixed`)){n.push(``,`batch_observability:`);for(let t of e.items??[]){if(!t.found){n.push(`- ${t.id}: unknown`);continue}let e=t.provider??`unavailable`,r=t.model??`unavailable`,i=t.runtime??t.backend??`unavailable`,a=t.route??t.backend??`unavailable`,o=t.prompt_profile??`unavailable`,s=t.prompt_profile_source??`unavailable`,c=t.prompt_profile_reason??`unavailable`;n.push(`- ${t.id}: provider=${e} model=${r} runtime=${i} route=${a}`),Hi()&&n.push(` prompt_profile=${o} source=${s} reason=${c}`)}}if(e.tool_rows&&e.tool_rows.length>0){n.push(``,`tool_rows:`);for(let t of e.tool_rows)n.push(`- ${t}`)}if(e.output_available&&e.output){n.push(``,`output:`);for(let t of e.output.split(`
16
+ `))n.push(t);e.output_truncated&&(n.push(`output_truncated: true`),typeof e.output_total_chars==`number`&&n.push(`output_total_chars: ${e.output_total_chars}`),typeof e.output_returned_chars==`number`&&n.push(`output_returned_chars: ${e.output_returned_chars}`))}if(e.items&&e.items.length>0){n.push(``,`items:`);for(let r of e.items){if(!r.found){n.push(`- ${r.id}: unknown (${r.error_code??`unknown_task_id`})`);continue}let e=r.status??`failed`,i=r.subagent_type??`unknown`,a=r.description??``,o=a.length>0?`${r.id}: ${e} ${i} · ${a}`:`${r.id}: ${e} ${i}`;if(n.push(`- ${o}`),t){if(n.push(` summary: ${r.summary}`),r.backend&&n.push(` backend: ${r.backend}`),r.provider&&n.push(` provider: ${r.provider}`),r.model&&n.push(` model: ${r.model}`),r.runtime&&n.push(` runtime: ${r.runtime}`),r.route&&n.push(` route: ${r.route}`),Hi()&&(r.prompt_profile&&n.push(` prompt_profile: ${r.prompt_profile}`),r.prompt_profile_source&&n.push(` prompt_profile_source: ${r.prompt_profile_source}`),r.prompt_profile_reason&&n.push(` prompt_profile_reason: ${r.prompt_profile_reason}`)),r.prompt&&n.push(` prompt: ${r.prompt}`),r.output_available&&r.output){n.push(` output:`);for(let e of r.output.split(`
17
17
  `))n.push(` ${e}`);r.output_truncated&&(n.push(` output_truncated: true`),typeof r.output_total_chars==`number`&&n.push(` output_total_chars: ${r.output_total_chars}`),typeof r.output_returned_chars==`number`&&n.push(` output_returned_chars: ${r.output_returned_chars}`))}if(r.error_code&&n.push(` error_code: ${r.error_code}`),r.error_category&&n.push(` error_category: ${r.error_category}`),r.error_message&&n.push(` error_message: ${r.error_message}`),typeof r.event_count==`number`&&n.push(` event_count: ${r.event_count}`),r.assistant_text&&n.push(` assistant_text: ${r.assistant_text}`),r.tool_rows&&r.tool_rows.length>0){n.push(` tool_rows:`);for(let e of r.tool_rows)n.push(` - ${e}`)}}else if(r.output_available&&r.output){n.push(` output:`);for(let e of r.output.split(`
18
18
  `))n.push(` ${e}`);r.output_truncated&&(n.push(` output_truncated: true`),typeof r.output_total_chars==`number`&&n.push(` output_total_chars: ${r.output_total_chars}`),typeof r.output_returned_chars==`number`&&n.push(` output_returned_chars: ${r.output_returned_chars}`))}}}return n.join(`
19
- `)}function ta(e,t){return zi()?ea(e,t):Zi(e,t)}function na(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Reflect.get(e,`op`),n=Reflect.get(e,`status`),r=Reflect.get(e,`summary`);return(t===`start`||t===`status`||t===`wait`||t===`send`||t===`cancel`)&&(n===`queued`||n===`running`||n===`succeeded`||n===`failed`||n===`cancelled`)&&typeof r==`string`}function ra(e){return e.op===`start`?`tasks`in e?`task start batch (${e.tasks.length})`:`task start ${e.subagent_type} · ${e.description}`:`task ${e.op}`}function ia(e,t){return ta(e,t)}function U(e){let t=e.items?.map(e=>Oi(Ei(e))),n=Di(Ti({contract_version:`task.v1`,...e,items:t})),r=Ri(n),i=ta(n,!1),a=r.length,o=r.length,s=i.length,c={...n,result_chars_total:a,result_chars_to_agent:o,result_chars_to_ui:s,ui_truncated:s<a};return{content:[{type:`text`,text:r}],details:c}}function aa(e){let t=ci(e);return a.isError(t)?`task ${e&&typeof e==`object`&&`op`in e&&typeof e.op==`string`?e.op:`unknown`}`:ra(t.value)}function W(e,t){return!t||!e.resolveBackendId?e.id:e.resolveBackendId(t)}function oa(e){return{op:e,status:`failed`,summary:`Operation '${e}' is not available yet`,backend:`task`,error_code:`task_operation_not_supported`,error_message:`Operation '${e}' is not available in current implementation`}}function sa(e,t,n,r){return{op:e,status:`failed`,summary:r,backend:`task`,task_id:t,error_code:n,error_message:r}}function ca(e){if(e===`painter`)return`painterImagegen`}function la(e,t){let n=ca(e.id);return!n||t.features[n]?a.ok(!0):a.err(new C({code:`subagent_unavailable`,stage:`task_start`,message:`Subagent '${e.id}' is disabled by feature flag '${n}'`,meta:{subagentId:e.id,featureFlag:n}}))}function ua(e,t){let n=je(e,t);return a.isOk(n)?a.ok(!0):a.err({code:n.error.code,message:n.error.message})}function da(e){return e===`failed`?5:e===`running`?4:e===`queued`?3:e===`cancelled`?2:1}function fa(e){if(e.length===0)return`failed`;let t=`succeeded`;for(let n of e){let e=n.found&&n.status?n.status:`failed`;da(e)>da(t)&&(t=e)}return t}function pa(e,t){let n=e.map(e=>e.backend).filter(e=>typeof e==`string`&&e.length>0),[r]=n;return!r||n.some(e=>e!==r)?t:r}function G(e,t,n){let r=e.filter(e=>e.found).map(e=>t(e)).filter(e=>typeof e==`string`&&e.length>0),[i]=r;return i?r.some(e=>e!==i)?`mixed`:i:n}function ma(e,t){let n=G(e,t,``);if(n.length!==0)return n}function K(e,t){return{provider:G(e,e=>e.provider,`unavailable`),model:G(e,e=>e.model,`unavailable`),runtime:G(e,e=>e.runtime,t),route:G(e,e=>e.route,t),promptProfile:ma(e,e=>e.prompt_profile),promptProfileSource:ma(e,e=>e.prompt_profile_source),promptProfileReason:ma(e,e=>e.prompt_profile_reason)}}function ha(e,t,n,r,i={}){let a=fa(t),o=`${e} for ${t.length} task(s)`;return U({op:e,status:a,summary:r?`${o} (timeout)`:o,backend:n,provider:i.provider,model:i.model,runtime:i.runtime,route:i.route,...i.promptProfile?{prompt_profile:i.promptProfile}:{},...i.promptProfileSource?{prompt_profile_source:i.promptProfileSource}:{},...i.promptProfileReason?{prompt_profile_reason:i.promptProfileReason}:{},items:t,timed_out:r,done:i.done,wait_status:i.waitStatus})}function q(e){return e===`succeeded`||e===`failed`||e===`cancelled`}function ga(e,t){if(!e)return()=>{};if(e.aborted)return t.abort(),()=>{};let n=()=>{t.abort()};return e.addEventListener(`abort`,n,{once:!0}),()=>{e.removeEventListener(`abort`,n)}}function _a(e){return`tasks`in e?e.async===!0?!0:e.tasks.some(e=>e.async===!0):e.async===!0}function va(e){let t=e.subagents?.taskMaxConcurrency;return t===void 0||!Number.isInteger(t)||t<=0?3:t}function J(e){return{id:e.id,found:!1,summary:e.summary,subagent_type:e.subagentType,description:e.description,output_available:!1,error_code:e.errorCode,error_message:e.errorMessage}}function ya(e){return{...e.created,state:`failed`,summary:e.errorMessage,errorCode:e.errorCode,errorMessage:e.errorMessage,activeToolCalls:0,endedAtEpochMs:Date.now(),updatedAtEpochMs:Date.now()}}function ba(e){return{op:`start`,status:`failed`,summary:`Async/background subagent execution is disabled`,backend:e.backendId,subagent_type:e.subagentType,description:e.description,error_code:`task_async_disabled`,error_message:`Subagent starts must run synchronously. Remove async:true and run start directly.`}}function xa(e){return{op:e.op,status:`failed`,task_id:e.taskId,subagent_type:e.subagentType,description:e.description,summary:`Unknown subagent_type '${e.subagentType}'`,backend:e.backendId,invocation:e.invocation,error_code:`unknown_subagent_type`,error_message:`No subagent profile found for '${e.subagentType}'.`}}function Sa(e){return{op:e.op,status:`failed`,task_id:e.taskId,subagent_type:e.subagentType,description:e.description,summary:e.message,backend:e.backendId,invocation:e.invocation,error_code:e.code,error_message:e.message}}function Ca(e){return{op:e.op,status:`failed`,task_id:e.taskId,subagent_type:e.subagentType,description:e.description,summary:e.message,backend:e.backendId,invocation:e.invocation,error_code:e.code,error_message:e.message}}function wa(e){return $(e.primary)}const Ta=new WeakMap;function Ea(e){let t=Ta.get(e);if(t)return t;let n={toolRows:vi(e),assistantText:yi(e)};return Ta.set(e,n),n}function Da(e){if(typeof e!=`string`||e.length===0)return{output_available:!1};let t=e.length;return{output:e,output_available:!0,output_truncated:!1,output_total_chars:t,output_returned_chars:t}}function Oa(e){return q(e.state)?Da(e.output):{output_available:!1}}function ka(e){let t=Oa(e),n=Ea(e.events);return{id:e.id,found:!0,status:e.state,subagent_type:e.subagentType,prompt:e.prompt,description:e.description,summary:e.summary,invocation:e.invocation,backend:e.backend,provider:e.provider,model:e.model,runtime:e.runtime,route:e.route,...e.promptProfile?{prompt_profile:e.promptProfile}:{},...e.promptProfileSource?{prompt_profile_source:e.promptProfileSource}:{},...e.promptProfileReason?{prompt_profile_reason:e.promptProfileReason}:{},output:t.output,output_available:t.output_available,output_truncated:t.output_truncated,output_total_chars:t.output_total_chars,output_returned_chars:t.output_returned_chars,updated_at_epoch_ms:e.updatedAtEpochMs,ended_at_epoch_ms:e.endedAtEpochMs,error_code:e.errorCode,error_message:e.errorMessage,tool_rows:n.toolRows,event_count:e.events.length,assistant_text:n.assistantText}}function Aa(e){return!e.found||!e.snapshot?{id:e.id,found:!1,summary:e.errorMessage??`Unknown task id '${e.id}'`,output_available:!1,error_code:e.errorCode??`unknown_task_id`,error_message:e.errorMessage??`Unknown task id '${e.id}'`}:ka(e.snapshot)}function Y(e,t,n){let r=typeof n==`string`&&n.length>0?Da(n):Oa(t),i=Ea(t.events);return{op:e,status:t.state,task_id:t.id,subagent_type:t.subagentType,prompt:t.prompt,description:t.description,summary:t.summary,output:r.output,output_available:r.output_available,output_truncated:r.output_truncated,output_total_chars:r.output_total_chars,output_returned_chars:r.output_returned_chars,updated_at_epoch_ms:t.updatedAtEpochMs,ended_at_epoch_ms:t.endedAtEpochMs,backend:t.backend,provider:t.provider,model:t.model,runtime:t.runtime,route:t.route,...t.promptProfile?{prompt_profile:t.promptProfile}:{},...t.promptProfileSource?{prompt_profile_source:t.promptProfileSource}:{},...t.promptProfileReason?{prompt_profile_reason:t.promptProfileReason}:{},invocation:t.invocation,error_code:t.errorCode,error_message:t.errorMessage,tool_rows:i.toolRows,event_count:t.events.length,assistant_text:i.assistantText}}function ja(e){return[...e].sort((e,t)=>{let n=e.state===`running`||e.state===`queued`;return n===(t.state===`running`||t.state===`queued`)?t.updatedAtEpochMs-e.updatedAtEpochMs:n?-1:1})}function Ma(e){return e===`queued`?`queued`:e===`running`?`running`:e===`succeeded`?`succeeded`:e===`failed`?`failed`:`cancelled`}function Na(e){let t=Ci(e);return t.narrativeLines.length===0?{toolCalls:t.toolCalls,result:void 0}:{toolCalls:t.toolCalls,result:t.narrativeLines.slice(0,2).join(`
20
- `)}}function Pa(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Fa(e,t){let n=e.output?Na(e.output):void 0,r=vi(e.events),i=yi(e.events),a=e.state===`queued`||e.state===`running`?i??`Working...`:i??n?.result??e.errorMessage??e.summary??`(no output)`;return{id:e.id,status:Ma(e.state),title:`${Pa(e.subagentType)} · ${e.description}`,prompt:e.prompt,toolCalls:r.length>0?r:n?.toolCalls??[],result:a}}function Ia(e){let t=e.maxItems??5,n=e.maxWidth??100,r=ja(e.snapshots),i=r.filter(e=>e.state===`running`||e.state===`queued`),a=i.slice(0,Math.max(t,0)),o=i.length,s=r.filter(e=>e.state===`failed`).length,c=r.filter(e=>e.state===`succeeded`).length,l=r.filter(e=>e.state===`cancelled`).length,u=r.reduce((e,t)=>e+t.activeToolCalls,0),d=o>0?`subagents ${o} running · tools ${u} active · done ${c} · failed ${s} · cancelled ${l}`:`subagents idle · done ${c} · failed ${s} · cancelled ${l}`,p=a.map(t=>Fa(t,e.nowEpochMs)),m=[...p],h=f({entries:p,width:n,options:{compact:!1}});return{statusLine:d,widgetLines:h,compactWidgetLines:f({entries:m,width:n,options:{compact:!0,maxPromptLines:2**53-1,maxToolCalls:2,maxResultLines:2}}),widgetEntries:p,compactWidgetEntries:m,plainText:h.length>0?h.join(`
21
- `):`No task activity`,hasActiveTasks:o>0,runningCount:o,activeToolCalls:u,completedCount:c,failedCount:s,cancelledCount:l}}const La=new WeakMap,Ra=new WeakMap,za=new WeakMap;function Ba(e,t){if(!e)return``;let n=e.trim();if(n.length<=t)return n;let r=Math.max(1,Math.floor(t/2)),i=Math.max(1,t-r),a=n.slice(0,r),o=n.slice(Math.max(n.length-i,0));return`${n.length}:${a}:${o}`}function Va(e){if(!e||e.length===0)return``;let t=e[0],n=e[e.length-1];return[String(e.length),Ba(t,48),Ba(n,48)].join(`|`)}function Ha(e){if(!e||e.length===0)return``;let t=e=>[e.id,e.found?`1`:`0`,e.status??`-`,e.provider??`-`,e.model??`-`,e.runtime??`-`,e.route??`-`,e.prompt_profile??`-`,e.prompt_profile_source??`-`,e.prompt_profile_reason??`-`,e.event_count===void 0?`-`:String(e.event_count),e.updated_at_epoch_ms===void 0?`-`:String(e.updated_at_epoch_ms),e.output_returned_chars===void 0?`-`:String(e.output_returned_chars),e.error_code??`-`,Ba(e.summary,48)].join(`~`),n=e.slice(0,2).map(e=>t(e)).join(`^`),r=e.length>2?e[e.length-1]:void 0,i=r?t(r):``;return`${e.length}|${n}|${i}`}function Ua(e){return[e.op,e.status,e.task_id??``,e.subagent_type??``,e.backend,e.provider??``,e.model??``,e.runtime??``,e.route??``,e.prompt_profile??``,e.prompt_profile_source??``,e.prompt_profile_reason??``,Ba(e.summary,120),e.error_code??``,e.error_message??``,e.wait_status??``,e.done===!0?`1`:`0`,e.timed_out===!0?`1`:`0`,e.batch_status??``,e.total_count===void 0?``:String(e.total_count),e.accepted_count===void 0?``:String(e.accepted_count),e.rejected_count===void 0?``:String(e.rejected_count),e.event_count===void 0?``:String(e.event_count),Ba(e.assistant_text,96),Va(e.tool_rows),Ha(e.items)].join(`¦`)}function Wa(e){return e.status===`succeeded`||e.status===`failed`||e.status===`cancelled`||e.op===`wait`&&(e.done===!0||e.wait_status===`timeout`||e.wait_status===`aborted`)}function Ga(e,t){let n=Ua(t),r=Date.now(),i=za.get(e),a=typeof t.event_count==`number`?t.event_count:void 0,o=Va(t.tool_rows),s=t.assistant_text;if(i&&i.signatureKey===n)return!1;let c=Wa(t),l=Lr(),u=i!==void 0&&(i.status!==t.status||a!==void 0&&(i.eventCount===void 0||a>i.eventCount)||i.toolRowsSignature!==o||i.assistantText!==s);return!c&&!u&&i&&r-i.atEpochMs<l?!1:(za.set(e,{atEpochMs:r,signatureKey:n,status:t.status,eventCount:a,toolRowsSignature:o,assistantText:s}),!0)}function Ka(e){let t=La.get(e);if(t)return t;let n=Ge(e);return La.set(e,n),n}function qa(e){let t=Ra.get(e);t&&(clearInterval(t),Ra.delete(e))}function Ja(e,t){if(Ra.get(e))return;let n=Ka(e),r=setInterval(()=>{let r=Ia({snapshots:t.taskStore.listTasks(),nowEpochMs:Date.now(),maxItems:5});n.publish(r),r.hasActiveTasks||qa(e)},120);Ra.set(e,r)}function Ya(e){if(!e.onUpdate||e.hasUI)return()=>{};let t=setInterval(()=>{let n=e.deps.taskStore.getTask(e.taskId);if(!n){clearInterval(t);return}if(e.isTerminalState(n.state)){clearInterval(t);return}X({details:e.snapshotToDetails(e.op,n,n.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})},120);return()=>{clearInterval(t)}}function X(e){let t=Ia({snapshots:e.deps.taskStore.listTasks(),nowEpochMs:Date.now(),maxItems:5});if(e.hasUI&&e.ui&&Ve()!==`off`?(Ka(e.ui).publish(t),t.hasActiveTasks?Ja(e.ui,e.deps):qa(e.ui)):e.ui&&(qa(e.ui),La.get(e.ui)?.clear()),!e.onUpdate||!Ga(e.onUpdate,e.details))return;let n=t.statusLine,r=e.hasUI?ta(e.details,!1):`${n}\n\n${Ri(e.details)}`;e.onUpdate({content:[{type:`text`,text:r}],details:e.details})}function Xa(e,t){return xe(e,t)}function Z(e){return ye({details:e.details,toResult:U,report:t=>{X({details:t.details,deps:e.runtime.deps,hasUI:e.runtime.hasUI,ui:e.runtime.ui,onUpdate:e.runtime.onUpdate})}})}function Za(e,t){return be(t,t=>sa(e,t.id,t.code,t.message))}async function Qa(e,t){let n=Xa(t),r=Za(`cancel`,t.deps.taskStore.getTasks([e.id])[0]);if(a.isError(r))return U(r.error);let i=r.value,o=i.state;if(q(i.state))return Z({runtime:n,details:{...Y(`cancel`,i),summary:`Task '${i.id}' is already terminal (${i.state}); cancel not applied`,cancel_applied:!1,prior_status:o}});let s=t.deps.taskStore.markCancelled(e.id,`Cancelled ${i.subagentType}: ${i.description}`);if(a.isError(s))return Z({runtime:n,details:{op:`cancel`,status:`failed`,summary:s.error.message,backend:i.backend,task_id:e.id,error_code:s.error.code,error_message:s.error.message}});let c=s.value.state===`cancelled`;return Z({runtime:n,details:{...Y(`cancel`,s.value),cancel_applied:c,prior_status:o}})}function $a(e){return e.type===`task_terminal`}function eo(e){let t=[],n,r=0,i=()=>{if(n&&=(clearTimeout(n),void 0),t.length===0)return;let r=t;t=[];let i=e.deps.taskStore.appendEvents(e.taskId,r);a.isError(i)||X({details:Y(e.op,i.value),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})},o=()=>{n||=setTimeout(()=>{i()},40)};return{onEvent(e){if(r+=1,t.push(e),t.length>=24||$a(e)){i();return}o()},flush:i,dispose(){n&&=(clearTimeout(n),void 0),t=[]},getStreamedEventCount(){return r}}}function to(e){if(!e.backendEvents||e.backendEvents.length===0)return e.deps.taskStore.appendEvents(e.taskId,[]);let t=e.backendEvents.slice(Math.min(e.streamedEventCount,e.backendEvents.length));return t.length===0?e.deps.taskStore.appendEvents(e.taskId,[]):e.deps.taskStore.appendEvents(e.taskId,t)}async function no(e){await new Promise(t=>{setTimeout(t,e)})}function ro(e){let t=e.deps.taskStore.updateObservability(e.taskId,{provider:e.observability.provider,model:e.observability.model,runtime:e.observability.runtime,route:e.observability.route,promptProfile:e.observability.promptProfile,promptProfileSource:e.observability.promptProfileSource,promptProfileReason:e.observability.promptProfileReason});a.isError(t)||X({details:Y(e.op,t.value),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})}async function io(e){let t=e.deps.taskStore.markRunning(e.taskId,`Starting ${e.subagent.name}: ${e.description}`);if(a.isError(t)){let n=W(e.deps.backend,e.config),r={id:e.taskId,state:`failed`,subagentType:e.subagent.id,description:e.description,prompt:e.prompt,followUpPrompts:[],summary:t.error.message,backend:n,provider:`unavailable`,model:`unavailable`,runtime:n,route:n,invocation:$(e.subagent.primary),totalToolCalls:0,activeToolCalls:0,startedAtEpochMs:Date.now(),updatedAtEpochMs:Date.now(),endedAtEpochMs:Date.now(),errorCode:t.error.code,errorMessage:t.error.message,events:[]};return X({details:Y(`start`,r),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),r}X({details:Y(`start`,t.value),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate});let n=eo({taskId:e.taskId,op:`start`,deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),r=Ya({op:`start`,taskId:e.taskId,deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate,isTerminalState:q,snapshotToDetails:Y}),i;try{i=await e.deps.backend.executeStart({taskId:e.taskId,subagent:e.subagent,description:e.description,prompt:e.prompt,cwd:e.cwd,config:e.config,signal:e.signal,onEvent:n.onEvent,onObservability:t=>{ro({op:`start`,taskId:e.taskId,observability:t,deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})}})}finally{r(),n.flush(),n.dispose()}let o=e.deps.taskStore.getTask(e.taskId);if(o&&q(o.state))return X({details:Y(`start`,o,o.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),o;if(a.isError(i)){if(i.error.code===`task_aborted`){let t=e.deps.taskStore.markCancelled(e.taskId,`Cancelled ${e.subagent.name}: ${e.description}`);if(a.isOk(t))return X({details:Y(`start`,t.value),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),t.value}let n=e.deps.taskStore.markFailed(e.taskId,i.error.message,i.error.code,i.error.message);if(a.isOk(n))return X({details:Y(`start`,n.value,n.value.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),n.value;let r={...t.value,state:`failed`,summary:n.error.message,errorCode:n.error.code,errorMessage:n.error.message,activeToolCalls:0,endedAtEpochMs:Date.now(),updatedAtEpochMs:Date.now()};return X({details:Y(`start`,r,r.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),r}let s=to({taskId:e.taskId,streamedEventCount:n.getStreamedEventCount(),backendEvents:i.value.events,deps:e.deps});if(a.isError(s)){let t=e.deps.taskStore.markFailed(e.taskId,s.error.message,s.error.code,s.error.message);if(a.isOk(t))return X({details:Y(`start`,t.value,t.value.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),t.value}let c=e.deps.taskStore.markSucceeded(e.taskId,i.value.summary,i.value.output,{provider:i.value.provider,model:i.value.model,runtime:i.value.runtime,route:i.value.route,promptProfile:i.value.promptProfile,promptProfileSource:i.value.promptProfileSource,promptProfileReason:i.value.promptProfileReason});if(a.isError(c)){let n={...t.value,state:`failed`,summary:c.error.message,errorCode:c.error.code,errorMessage:c.error.message,activeToolCalls:0,endedAtEpochMs:Date.now(),updatedAtEpochMs:Date.now()};return X({details:Y(`start`,n,n.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),n}return X({details:Y(`start`,c.value,c.value.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),c.value}function ao(e){let t=W(e.deps.backend,e.config),n=e.deps.taskStore.createTask({taskId:e.taskId,subagent:e.subagent,description:e.description,prompt:e.prompt,backend:t,observability:{provider:`unavailable`,model:`unavailable`,runtime:t,route:t},invocation:$(e.subagent.primary)});if(a.isError(n))return a.err(J({id:e.taskId,summary:n.error.message,errorCode:n.error.code,errorMessage:n.error.message,subagentType:e.subagent.id,description:e.description}));let r=new AbortController,i=ga(e.signal,r),o=e.deps.taskStore.setAbortController(e.taskId,r);return a.isError(o)?(i(),a.err(J({id:e.taskId,summary:o.error.message,errorCode:o.error.code,errorMessage:o.error.message,subagentType:e.subagent.id,description:e.description}))):a.ok({index:e.index,taskId:e.taskId,createdSnapshot:n.value,run:async()=>{let t=io({taskId:e.taskId,subagent:e.subagent,description:e.description,prompt:e.prompt,cwd:e.cwd,config:e.config,signal:r.signal,onUpdate:e.onUpdate,hasUI:e.hasUI,ui:e.ui,deps:e.deps}).finally(()=>{i()}),o=t.then(()=>void 0),s=e.deps.taskStore.setExecutionPromise(e.taskId,o);if(a.isError(s)){r.abort();let t=e.deps.taskStore.markFailed(e.taskId,s.error.message,s.error.code,s.error.message);return a.isError(t)?ya({created:n.value,errorCode:t.error.code,errorMessage:t.error.message}):t.value}return t}})}async function oo(e,t){let n=Math.min(Math.max(t,1),e.length),r=Array.from({length:e.length},()=>void 0),i=0,a=async()=>{for(;;){let t=i;if(t>=e.length)return;i+=1;let n=e[t];if(!n)return;r[t]=await n.run(),await no(0)}},o=[];for(let e=0;e<n;e+=1)o.push(a());return await Promise.all(o),e.map((e,t)=>r[t]||e.createdSnapshot)}function so(e){return eo({taskId:e.taskId,op:e.op,deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})}function co(e,t){return Z({details:t,runtime:Xa(e)})}async function lo(e,t,n){let r=W(t.deps.backend,n.config),i=Za(`send`,t.deps.taskStore.getTasks([e.id])[0]);if(a.isError(i))return U(i.error);let o=i.value;if(q(o.state))return U({op:`send`,status:`failed`,task_id:o.id,subagent_type:o.subagentType,description:o.description,summary:`Task '${o.id}' is terminal (${o.state}) and cannot be resumed`,backend:o.backend,invocation:o.invocation,error_code:`task_not_resumable`,error_message:`Task '${o.id}' is terminal (${o.state}) and cannot be resumed`});let s=Ie({subagentId:o.subagentType,config:n.config});if(!s)return U(xa({op:`send`,backendId:r,taskId:o.id,subagentType:o.subagentType,description:o.description,invocation:o.invocation}));let c=la(s,n.config);if(a.isError(c))return U(Sa({op:`send`,backendId:r,taskId:o.id,subagentType:o.subagentType,description:o.description,invocation:o.invocation,code:c.error.code,message:c.error.message}));let l=ua(s,n.config);if(a.isError(l))return U(Ca({op:`send`,backendId:r,taskId:o.id,subagentType:o.subagentType,description:o.description,invocation:o.invocation,code:l.error.code,message:l.error.message}));let u=t.deps.taskStore.markInteractionRunning(e.id,`Continuing ${s.name}: ${o.description}`,e.prompt);if(a.isError(u))return U({op:`send`,status:`failed`,task_id:e.id,summary:u.error.message,backend:r,error_code:u.error.code,error_message:u.error.message});X({details:Y(`send`,u.value),deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate});let d=so({taskId:u.value.id,op:`send`,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate}),f=Ya({op:`send`,taskId:u.value.id,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate,isTerminalState:q,snapshotToDetails:Y}),p;try{p=await t.deps.backend.executeSend({taskId:u.value.id,subagent:s,description:u.value.description,initialPrompt:u.value.prompt,followUpPrompts:u.value.followUpPrompts,prompt:e.prompt,cwd:t.cwd,config:n.config,signal:t.signal,onEvent:d.onEvent,onObservability:e=>{ro({op:`send`,taskId:u.value.id,observability:e,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate})}})}finally{f(),d.flush(),d.dispose()}if(a.isError(p)){let e=t.deps.taskStore.markFailed(u.value.id,p.error.message,p.error.code,p.error.message);if(a.isError(e))return co(t,{op:`send`,status:`failed`,task_id:u.value.id,summary:e.error.message,backend:r,error_code:e.error.code,error_message:e.error.message});let n=U(Y(`send`,e.value,e.value.output));return X({details:n.details,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate}),n}let m=to({taskId:u.value.id,streamedEventCount:d.getStreamedEventCount(),backendEvents:p.value.events,deps:t.deps});if(a.isError(m)){let e=t.deps.taskStore.markFailed(u.value.id,m.error.message,m.error.code,m.error.message);if(a.isError(e))return co(t,{op:`send`,status:`failed`,task_id:u.value.id,summary:e.error.message,backend:r,error_code:e.error.code,error_message:e.error.message});let n=U(Y(`send`,e.value,e.value.output));return X({details:n.details,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate}),n}let h=t.deps.taskStore.markInteractionComplete(u.value.id,p.value.summary,p.value.output,{provider:p.value.provider,model:p.value.model,runtime:p.value.runtime,route:p.value.route,promptProfile:p.value.promptProfile,promptProfileSource:p.value.promptProfileSource,promptProfileReason:p.value.promptProfileReason});if(a.isError(h))return co(t,{op:`send`,status:`failed`,task_id:u.value.id,summary:h.error.message,backend:r,error_code:h.error.code,error_message:h.error.message});let g=U(Y(`send`,h.value,p.value.output));return X({details:g.details,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate}),g}function uo(e){let t=0,n=0,r=0,i=0;for(let a of e){if(!a.found){i+=1;continue}if(t+=1,a.status===`running`||a.status===`queued`){n+=1;continue}if(a.status===`succeeded`){r+=1;continue}i+=1}let a=e.length;return{totalCount:a,acceptedCount:t,rejectedCount:a-t,runningCount:n,succeededCount:r,failedCount:i}}function fo(e){let t=uo(e),n=t.acceptedCount===0?`rejected`:t.runningCount>0?t.failedCount===0&&t.rejectedCount===0?`accepted`:`partial`:t.failedCount===0&&t.rejectedCount===0?`completed`:`partial`;return{status:t.acceptedCount===0?`failed`:t.runningCount>0?`running`:t.succeededCount===t.acceptedCount&&t.rejectedCount===0?`succeeded`:`failed`,totalCount:t.totalCount,acceptedCount:t.acceptedCount,rejectedCount:t.rejectedCount,batchStatus:n}}function po(e){let t=uo(e);return t.rejectedCount>0?`Completed batch tasks: ${t.succeededCount}/${t.acceptedCount} succeeded (${t.rejectedCount} rejected)`:`Completed batch tasks: ${t.succeededCount}/${t.totalCount} succeeded`}function mo(e,t){if(t.status!==`running`)return po(e);let n=uo(e);return[`Running batch tasks: ${n.acceptedCount-n.runningCount}/${t.acceptedCount} done`,`active ${n.runningCount}`,`failed ${n.failedCount}`,`rejected ${t.rejectedCount}`].join(` · `)}function ho(e){let t=[...e.items],n=e.prepared.map(e=>e.taskId),r=e.deps.taskStore.getTasks(n),i=new Map;for(let e of r)i.set(e.id,e);for(let n of e.prepared){let e=i.get(n.taskId);e&&(t[n.index]=e.found&&e.snapshot?ka(e.snapshot):{id:e.id,found:!1,summary:e.errorMessage??`Unknown task id '${e.id}'`,output_available:!1,error_code:e.errorCode??`unknown_task_id`,error_message:e.errorMessage??`Unknown task id '${e.id}'`})}return t.map((e,t)=>e||J({id:`task_batch_${t+1}`,summary:`Batch task result unavailable`,errorCode:`task_batch_result_unavailable`,errorMessage:`Batch task result unavailable`}))}function go(e){return e.map(e=>[e.id,e.found?`1`:`0`,e.status??`-`,e.updated_at_epoch_ms===void 0?`-`:String(e.updated_at_epoch_ms),e.event_count===void 0?`-`:String(e.event_count)].join(`:`)).join(`|`)}async function _o(e,t,n){let r=W(t.deps.backend,n.config),i=Array.from({length:e.tasks.length},()=>void 0),o=[];for(let r=0;r<e.tasks.length;r+=1){let s=e.tasks[r];if(!s){i[r]=J({id:`task_batch_${r+1}`,summary:`Missing batch task item`,errorCode:`task_batch_item_missing`,errorMessage:`Missing batch task item`});continue}let c=Ie({subagentId:s.subagent_type,config:n.config});if(!c){i[r]=J({id:`task_batch_${r+1}`,summary:`Unknown subagent_type '${s.subagent_type}'`,errorCode:`unknown_subagent_type`,errorMessage:`No subagent profile found for '${s.subagent_type}'.`,subagentType:s.subagent_type,description:s.description});continue}let l=la(c,n.config);if(a.isError(l)){i[r]=J({id:`task_batch_${r+1}`,summary:l.error.message,errorCode:l.error.code,errorMessage:l.error.message,subagentType:c.id,description:s.description});continue}let u=ua(c,n.config);if(a.isError(u)){i[r]=J({id:`task_batch_${r+1}`,summary:u.error.message,errorCode:u.error.code,errorMessage:u.error.message,subagentType:c.id,description:s.description});continue}let d=t.deps.createTaskId(),f=ao({index:r,taskId:d,subagent:c,description:s.description,prompt:s.prompt,cwd:t.cwd,config:n.config,signal:t.signal,onUpdate:void 0,hasUI:t.hasUI,ui:t.ui,deps:t.deps});if(a.isError(f)){i[r]=f.error;continue}o.push(f.value),i[r]={...ka(f.value.createdSnapshot),invocation:wa(c)}}let s=e.parallel?va(n.config):1,c=t.onUpdate!==void 0||t.hasUI&&t.ui&&Ve()!==`off`,l,u=()=>{let e=ho({items:i,prepared:o,deps:t.deps}),n=go(e);if(n===l)return;l=n;let a=fo(e),s=K(e,r);X({details:{op:`start`,status:a.status,summary:mo(e,a),backend:r,provider:s.provider,model:s.model,runtime:s.runtime,route:s.route,...s.promptProfile?{prompt_profile:s.promptProfile}:{},...s.promptProfileSource?{prompt_profile_source:s.promptProfileSource}:{},...s.promptProfileReason?{prompt_profile_reason:s.promptProfileReason}:{},items:e,total_count:a.totalCount,accepted_count:a.acceptedCount,rejected_count:a.rejectedCount,batch_status:a.batchStatus},deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate})},d;c&&(u(),d=setInterval(()=>{u()},120));let f;try{f=await oo(o,s)}finally{d&&clearInterval(d)}for(let e=0;e<o.length;e+=1){let t=o[e],n=f[e];!t||!n||(i[t.index]=ka(n))}let p=i.map((e,t)=>e||J({id:`task_batch_${t+1}`,summary:`Batch task result unavailable`,errorCode:`task_batch_result_unavailable`,errorMessage:`Batch task result unavailable`})),m=fo(p),h=K(p,r);return U({op:`start`,status:m.status,summary:po(p),backend:r,provider:h.provider,model:h.model,runtime:h.runtime,route:h.route,...h.promptProfile?{prompt_profile:h.promptProfile}:{},...h.promptProfileSource?{prompt_profile_source:h.promptProfileSource}:{},...h.promptProfileReason?{prompt_profile_reason:h.promptProfileReason}:{},items:p,total_count:m.totalCount,accepted_count:m.acceptedCount,rejected_count:m.rejectedCount,batch_status:m.batchStatus})}async function vo(e,t,n){let r=W(t.deps.backend,n.config),i=Ie({subagentId:e.subagent_type,config:n.config});if(!i)return U(xa({op:`start`,backendId:r,subagentType:e.subagent_type,description:e.description}));let o=la(i,n.config);if(a.isError(o))return U(Sa({op:`start`,backendId:r,subagentType:i.id,description:e.description,invocation:wa(i),code:o.error.code,message:o.error.message}));let s=ua(i,n.config);if(a.isError(s))return U(Ca({op:`start`,backendId:r,subagentType:i.id,description:e.description,invocation:wa(i),code:s.error.code,message:s.error.message}));let c=t.deps.createTaskId(),l=ao({index:0,taskId:c,subagent:i,description:e.description,prompt:e.prompt,cwd:t.cwd,config:n.config,signal:t.signal,onUpdate:t.onUpdate,hasUI:t.hasUI,ui:t.ui,deps:t.deps});if(a.isError(l))return U({op:`start`,status:`failed`,task_id:c,subagent_type:i.id,description:e.description,summary:l.error.summary,backend:r,error_code:l.error.error_code,error_message:l.error.error_message});let u=await l.value.run();return U(Y(`start`,u,u.output))}async function yo(e,t,n){if(_a(e)){let r=`tasks`in e?void 0:e.subagent_type,i=`tasks`in e?void 0:e.description;return U(ba({backendId:W(t.deps.backend,n.config),subagentType:r,description:i}))}return`tasks`in e?_o(e,t,n):vo(e,t,n)}async function bo(e,t){let n=t.deps.taskStore.getTasks(e.ids).map(e=>Aa(e)),r=pa(n,t.deps.backend.id),i=K(n,r);return Z({details:ha(`status`,n,r,!1,{provider:i.provider,model:i.model,runtime:i.runtime,route:i.route,promptProfile:i.promptProfile,promptProfileSource:i.promptProfileSource,promptProfileReason:i.promptProfileReason}).details,runtime:Xa(t,{onUpdate:void 0})})}async function xo(e){await new Promise(t=>{setTimeout(t,e)})}async function So(e){if(!e){await new Promise(()=>void 0);return}e.aborted||await new Promise(t=>{let n=()=>{e.removeEventListener(`abort`,n),t()};e.addEventListener(`abort`,n,{once:!0})})}function Co(e){return e.map(e=>{let t=e.snapshot;return[e.id,e.found?`1`:`0`,t?.state??`-`,t?.updatedAtEpochMs===void 0?`-`:String(t.updatedAtEpochMs)].join(`:`)}).join(`|`)}async function wo(e){let t=Date.now(),n=0,r=``;for(;;){let i=e.deps.taskStore.getTasks(e.ids),a=Date.now(),o=Co(i);(o!==r||a-n>=150)&&(e.onProgress?.(i),n=a,r=o);let s=[];for(let e of i)!e.found||!e.snapshot||q(e.snapshot.state)||s.push(e.id);if(s.length===0)return{lookups:i,timedOut:!1,timeoutReason:void 0};if(e.timeoutMs!==void 0&&a-t>=e.timeoutMs)return{lookups:i,timedOut:!0,timeoutReason:`timeout`};if(e.signal?.aborted)return{lookups:i,timedOut:!0,timeoutReason:`aborted`};let c=e.timeoutMs===void 0?120:Math.max(1,Math.min(120,e.timeoutMs-(a-t))),l=s.map(t=>e.deps.taskStore.getExecutionPromise(t)).filter(e=>e!==void 0).map(e=>e.catch(()=>{})),u=[xo(c),So(e.signal)],d=[...l,...u];await Promise.race(d)}}async function To(e,t){let n=await wo({ids:e.ids,timeoutMs:e.timeout_ms,signal:t.signal,deps:t.deps,onProgress:e=>{let n=e.map(e=>Aa(e)),r=pa(n,t.deps.backend.id),i=K(n,r);X({details:U({op:`wait`,status:fa(n),summary:`wait for ${n.length} task(s)`,backend:r,provider:i.provider,model:i.model,runtime:i.runtime,route:i.route,...i.promptProfile?{prompt_profile:i.promptProfile}:{},...i.promptProfileSource?{prompt_profile_source:i.promptProfileSource}:{},...i.promptProfileReason?{prompt_profile_reason:i.promptProfileReason}:{},items:n,done:!1}).details,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate})}}),r=n.lookups.map(e=>Aa(e)),i=pa(r,t.deps.backend.id),a=K(r,i),o=n.timeoutReason===`timeout`?`timeout`:n.timeoutReason===`aborted`?`aborted`:`completed`,s=ha(`wait`,r,i,n.timedOut,{done:o===`completed`,waitStatus:o,provider:a.provider,model:a.model,runtime:a.runtime,route:a.route,promptProfile:a.promptProfile,promptProfileSource:a.promptProfileSource,promptProfileReason:a.promptProfileReason});return Z({details:(n.timeoutReason===`timeout`?U({...s.details,error_code:`task_wait_timeout`,error_message:`Wait operation timed out before all tasks reached a terminal state`}):n.timeoutReason===`aborted`?U({...s.details,error_code:`task_wait_aborted`,error_message:`Wait operation aborted before all tasks reached a terminal state`}):s).details,runtime:Xa(t)})}function Eo(e){if(!e||typeof e!=`object`||Array.isArray(e))return`start`;let t=Reflect.get(e,`op`);return t===`start`||t===`status`||t===`wait`||t===`send`||t===`cancel`?t:t===`result`?`status`:`start`}function Do(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:Reflect.get(e,`op`)===`help`}function Oo(e,t,n,r){return{op:e,status:`failed`,summary:t,backend:`task`,error_code:n,error_message:r?`${t} (path: ${r})`:t}}function ko(e){let t=ci(e);if(a.isError(t)){let n=Eo(e);return a.err(Oo(n,t.error.message,t.error.code,typeof t.error.path==`string`?t.error.path:void 0))}return a.ok(t.value)}async function Ao(e,t){let n=await a.tryPromise({try:async()=>e.deps.loadConfig(e.cwd),catch:e=>new C({code:`task_config_load_failed`,stage:`task_tool`,cause:e,message:`Failed to load runtime config for task tool`})});if(a.isError(n))return a.err({op:t,status:`failed`,summary:n.error.message,backend:e.deps.backend.id,error_code:n.error.code,error_message:n.error.message});if(!n.value.config.features.subagents){let r=W(e.deps.backend,n.value.config);return a.err({op:t,status:`failed`,summary:`Subagents feature is disabled`,backend:r,error_code:`subagents_disabled`,error_message:`Enable features.subagents to use task orchestration and primary subagent tools`})}return a.ok(n.value)}async function jo(e){return e.params.op===`start`?yo(e.params,e.toolInput,e.runtimeConfig):e.params.op===`status`?bo(e.params,e.toolInput):e.params.op===`wait`?To(e.params,e.toolInput):e.params.op===`send`?lo(e.params,e.toolInput,e.runtimeConfig):e.params.op===`cancel`?Qa(e.params,e.toolInput):(e.params,U(oa(`start`)))}function Mo(e){let t=[`Orchestrate subagent execution. Supports start/status/wait/send/cancel.`,`Subagent starts are synchronous and blocking. Async/background start mode is disabled.`,`Compatibility: status/wait accept either id or ids. op=result is treated as status.`,``,`Active subagent roster:`];for(let n of e){if(n.internal)continue;let e=$(n.primary);if(n.primary){t.push(`- ${n.id} (${e}): the ${n.name} is available via primary tool '${n.id}' and task start`);continue}t.push(`- ${n.id} (${e}): ${S(n)}`),No(t,`When to use:`,n.whenToUse),No(t,`When not to use:`,n.whenNotToUse),No(t,`Usage guidelines:`,n.usageGuidelines),No(t,`Examples:`,n.examples)}return t.join(`
22
- `)}function No(e,t,n){if(!(!n||n.length===0)){e.push(` ${t}`);for(let t of n)e.push(` - ${t}`)}}async function Po(e){if(Do(e.params))return U({op:`status`,status:`failed`,summary:`Unsupported op 'help'. Use start, status, wait, send, or cancel.`,backend:e.deps.backend.id,error_code:`task_operation_not_supported`,error_message:`task tool supports op=start|status|wait|send|cancel (status/wait accept id or ids; result aliases status)`});let t=ko(e.params);if(a.isError(t))return U(t.error);let n=await Ao(e,t.value.op);return a.isError(n)?U(n.error):jo({params:t.value,runtimeConfig:n.value,toolInput:e})}function Fo(e,t=Hr()){e.registerTool({name:`task`,label:`Task`,description:Mo(t.subagents),parameters:Qr,execute:async(e,n,r,i,a)=>Po({params:n,cwd:a.cwd,signal:r,onUpdate:i,hasUI:a.hasUI,ui:a.hasUI?a.ui:void 0,deps:t}),renderCall:(e,t)=>new p(aa(e),0,0),renderResult:(e,t,n)=>{if(na(e.details)&&!zi())return $i(e.details,t.expanded);let r=na(e.details)?ta(e.details,t.expanded):e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
19
+ `)}function ra(e,t){return Vi()?na(e,t):$i(e,t)}function ia(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Reflect.get(e,`op`),n=Reflect.get(e,`status`),r=Reflect.get(e,`summary`);return(t===`start`||t===`status`||t===`wait`||t===`send`||t===`cancel`)&&(n===`queued`||n===`running`||n===`succeeded`||n===`failed`||n===`cancelled`)&&typeof r==`string`}function aa(e){return e.op===`start`?`tasks`in e?`task start batch (${e.tasks.length})`:`task start ${e.subagent_type} · ${e.description}`:`task ${e.op}`}function oa(e,t){return ra(e,t)}function U(e){let t=e.items?.map(e=>Bi(Ri(e))),n=zi(Li({contract_version:`task.v1`,...e,items:t})),r=Fi(n),i=r.text,a=ra(n,!1),o=i.length,s=i.length,c=a.length,l={...n,result_chars_total:o,result_chars_to_agent:s,result_chars_to_ui:c,result_source:r.resultSource,ui_truncated:c<o};return{content:[{type:`text`,text:i}],details:l}}function sa(e){let t=ci(e);return a.isError(t)?`task ${e&&typeof e==`object`&&`op`in e&&typeof e.op==`string`?e.op:`unknown`}`:aa(t.value)}function W(e,t){return!t||!e.resolveBackendId?e.id:e.resolveBackendId(t)}function ca(e){return{op:e,status:`failed`,summary:`Operation '${e}' is not available yet`,backend:`task`,error_code:`task_operation_not_supported`,error_message:`Operation '${e}' is not available in current implementation`}}function la(e,t,n,r){return{op:e,status:`failed`,summary:r,backend:`task`,task_id:t,error_code:n,error_message:r}}function ua(e){if(e===`painter`)return`painterImagegen`}function da(e,t){let n=ua(e.id);return!n||t.features[n]?a.ok(!0):a.err(new C({code:`subagent_unavailable`,stage:`task_start`,message:`Subagent '${e.id}' is disabled by feature flag '${n}'`,meta:{subagentId:e.id,featureFlag:n}}))}function fa(e,t){let n=je(e,t);return a.isOk(n)?a.ok(!0):a.err({code:n.error.code,message:n.error.message})}function pa(e){return e===`failed`?5:e===`running`?4:e===`queued`?3:e===`cancelled`?2:1}function ma(e){if(e.length===0)return`failed`;let t=`succeeded`;for(let n of e){let e=n.found&&n.status?n.status:`failed`;pa(e)>pa(t)&&(t=e)}return t}function ha(e,t){let n=e.map(e=>e.backend).filter(e=>typeof e==`string`&&e.length>0),[r]=n;return!r||n.some(e=>e!==r)?t:r}function G(e,t,n){let r=e.filter(e=>e.found).map(e=>t(e)).filter(e=>typeof e==`string`&&e.length>0),[i]=r;return i?r.some(e=>e!==i)?`mixed`:i:n}function ga(e,t){let n=G(e,t,``);if(n.length!==0)return n}function K(e,t){return{provider:G(e,e=>e.provider,`unavailable`),model:G(e,e=>e.model,`unavailable`),runtime:G(e,e=>e.runtime,t),route:G(e,e=>e.route,t),promptProfile:ga(e,e=>e.prompt_profile),promptProfileSource:ga(e,e=>e.prompt_profile_source),promptProfileReason:ga(e,e=>e.prompt_profile_reason)}}function _a(e,t,n,r,i={}){let a=ma(t),o=`${e} for ${t.length} task(s)`;return U({op:e,status:a,summary:r?`${o} (timeout)`:o,backend:n,provider:i.provider,model:i.model,runtime:i.runtime,route:i.route,...i.promptProfile?{prompt_profile:i.promptProfile}:{},...i.promptProfileSource?{prompt_profile_source:i.promptProfileSource}:{},...i.promptProfileReason?{prompt_profile_reason:i.promptProfileReason}:{},items:t,timed_out:r,done:i.done,wait_status:i.waitStatus})}function q(e){return e===`succeeded`||e===`failed`||e===`cancelled`}function va(e,t){if(!e)return()=>{};if(e.aborted)return t.abort(),()=>{};let n=()=>{t.abort()};return e.addEventListener(`abort`,n,{once:!0}),()=>{e.removeEventListener(`abort`,n)}}function ya(e){return`tasks`in e?e.async===!0?!0:e.tasks.some(e=>e.async===!0):e.async===!0}function ba(e){let t=e.subagents?.taskMaxConcurrency;return t===void 0||!Number.isInteger(t)||t<=0?3:t}function J(e){return{id:e.id,found:!1,summary:e.summary,subagent_type:e.subagentType,description:e.description,output_available:!1,error_code:e.errorCode,error_message:e.errorMessage}}function xa(e){return{...e.created,state:`failed`,summary:e.errorMessage,errorCode:e.errorCode,errorMessage:e.errorMessage,activeToolCalls:0,endedAtEpochMs:Date.now(),updatedAtEpochMs:Date.now()}}function Sa(e){return{op:`start`,status:`failed`,summary:`Async/background subagent execution is disabled`,backend:e.backendId,subagent_type:e.subagentType,description:e.description,error_code:`task_async_disabled`,error_message:`Subagent starts must run synchronously. Remove async:true and run start directly.`}}function Ca(e){return{op:e.op,status:`failed`,task_id:e.taskId,subagent_type:e.subagentType,description:e.description,summary:`Unknown subagent_type '${e.subagentType}'`,backend:e.backendId,invocation:e.invocation,error_code:`unknown_subagent_type`,error_message:`No subagent profile found for '${e.subagentType}'.`}}function wa(e){return{op:e.op,status:`failed`,task_id:e.taskId,subagent_type:e.subagentType,description:e.description,summary:e.message,backend:e.backendId,invocation:e.invocation,error_code:e.code,error_message:e.message}}function Ta(e){return{op:e.op,status:`failed`,task_id:e.taskId,subagent_type:e.subagentType,description:e.description,summary:e.message,backend:e.backendId,invocation:e.invocation,error_code:e.code,error_message:e.message}}function Ea(e){return $(e.primary)}const Da=new WeakMap;function Oa(e){let t=Da.get(e);if(t)return t;let n={toolRows:vi(e),assistantText:yi(e)};return Da.set(e,n),n}function ka(e){if(typeof e!=`string`||e.length===0)return{output_available:!1};let t=e.length;return{output:e,output_available:!0,output_truncated:!1,output_total_chars:t,output_returned_chars:t}}function Aa(e){return q(e.state)?ka(e.output):{output_available:!1}}function ja(e){let t=Aa(e),n=Oa(e.events);return{id:e.id,found:!0,status:e.state,subagent_type:e.subagentType,prompt:e.prompt,description:e.description,summary:e.summary,invocation:e.invocation,backend:e.backend,provider:e.provider,model:e.model,runtime:e.runtime,route:e.route,...e.promptProfile?{prompt_profile:e.promptProfile}:{},...e.promptProfileSource?{prompt_profile_source:e.promptProfileSource}:{},...e.promptProfileReason?{prompt_profile_reason:e.promptProfileReason}:{},output:t.output,output_available:t.output_available,output_truncated:t.output_truncated,output_total_chars:t.output_total_chars,output_returned_chars:t.output_returned_chars,updated_at_epoch_ms:e.updatedAtEpochMs,ended_at_epoch_ms:e.endedAtEpochMs,error_code:e.errorCode,error_message:e.errorMessage,tool_rows:n.toolRows,event_count:e.events.length,assistant_text:n.assistantText}}function Ma(e){return!e.found||!e.snapshot?{id:e.id,found:!1,summary:e.errorMessage??`Unknown task id '${e.id}'`,output_available:!1,error_code:e.errorCode??`unknown_task_id`,error_message:e.errorMessage??`Unknown task id '${e.id}'`}:ja(e.snapshot)}function Y(e,t,n){let r=typeof n==`string`&&n.length>0?ka(n):Aa(t),i=Oa(t.events);return{op:e,status:t.state,task_id:t.id,subagent_type:t.subagentType,prompt:t.prompt,description:t.description,summary:t.summary,output:r.output,output_available:r.output_available,output_truncated:r.output_truncated,output_total_chars:r.output_total_chars,output_returned_chars:r.output_returned_chars,updated_at_epoch_ms:t.updatedAtEpochMs,ended_at_epoch_ms:t.endedAtEpochMs,backend:t.backend,provider:t.provider,model:t.model,runtime:t.runtime,route:t.route,...t.promptProfile?{prompt_profile:t.promptProfile}:{},...t.promptProfileSource?{prompt_profile_source:t.promptProfileSource}:{},...t.promptProfileReason?{prompt_profile_reason:t.promptProfileReason}:{},invocation:t.invocation,error_code:t.errorCode,error_message:t.errorMessage,tool_rows:i.toolRows,event_count:t.events.length,assistant_text:i.assistantText}}function Na(e){return[...e].sort((e,t)=>{let n=e.state===`running`||e.state===`queued`;return n===(t.state===`running`||t.state===`queued`)?t.updatedAtEpochMs-e.updatedAtEpochMs:n?-1:1})}function Pa(e){return e===`queued`?`queued`:e===`running`?`running`:e===`succeeded`?`succeeded`:e===`failed`?`failed`:`cancelled`}function Fa(e){let t=Ci(e);return t.narrativeLines.length===0?{toolCalls:t.toolCalls,result:void 0}:{toolCalls:t.toolCalls,result:t.narrativeLines.slice(0,2).join(`
20
+ `)}}function Ia(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function La(e,t){let n=e.output?Fa(e.output):void 0,r=vi(e.events),i=yi(e.events),a=e.state===`queued`||e.state===`running`?i??`Working...`:i??n?.result??e.errorMessage??e.summary??`(no output)`;return{id:e.id,status:Pa(e.state),title:`${Ia(e.subagentType)} · ${e.description}`,prompt:e.prompt,toolCalls:r.length>0?r:n?.toolCalls??[],result:a}}function Ra(e){let t=e.maxItems??5,n=e.maxWidth??100,r=Na(e.snapshots),i=r.filter(e=>e.state===`running`||e.state===`queued`),a=i.slice(0,Math.max(t,0)),o=i.length,s=r.filter(e=>e.state===`failed`).length,c=r.filter(e=>e.state===`succeeded`).length,l=r.filter(e=>e.state===`cancelled`).length,u=r.reduce((e,t)=>e+t.activeToolCalls,0),d=o>0?`subagents ${o} running · tools ${u} active · done ${c} · failed ${s} · cancelled ${l}`:`subagents idle · done ${c} · failed ${s} · cancelled ${l}`,p=a.map(t=>La(t,e.nowEpochMs)),m=[...p],h=f({entries:p,width:n,options:{compact:!1}});return{statusLine:d,widgetLines:h,compactWidgetLines:f({entries:m,width:n,options:{compact:!0,maxPromptLines:2,maxToolCalls:2,maxResultLines:2}}),widgetEntries:p,compactWidgetEntries:m,plainText:h.length>0?h.join(`
21
+ `):`No task activity`,hasActiveTasks:o>0,runningCount:o,activeToolCalls:u,completedCount:c,failedCount:s,cancelledCount:l}}const za=new WeakMap,Ba=new WeakMap,Va=new WeakMap;function Ha(e,t){if(!e)return``;let n=e.trim();if(n.length<=t)return n;let r=Math.max(1,Math.floor(t/2)),i=Math.max(1,t-r),a=n.slice(0,r),o=n.slice(Math.max(n.length-i,0));return`${n.length}:${a}:${o}`}function Ua(e){if(!e||e.length===0)return``;let t=e[0],n=e[e.length-1];return[String(e.length),Ha(t,48),Ha(n,48)].join(`|`)}function Wa(e){if(!e||e.length===0)return``;let t=e=>[e.id,e.found?`1`:`0`,e.status??`-`,e.provider??`-`,e.model??`-`,e.runtime??`-`,e.route??`-`,e.prompt_profile??`-`,e.prompt_profile_source??`-`,e.prompt_profile_reason??`-`,e.event_count===void 0?`-`:String(e.event_count),e.updated_at_epoch_ms===void 0?`-`:String(e.updated_at_epoch_ms),e.output_returned_chars===void 0?`-`:String(e.output_returned_chars),e.error_code??`-`,Ha(e.summary,48)].join(`~`),n=e.slice(0,2).map(e=>t(e)).join(`^`),r=e.length>2?e[e.length-1]:void 0,i=r?t(r):``;return`${e.length}|${n}|${i}`}function Ga(e){return[e.op,e.status,e.task_id??``,e.subagent_type??``,e.backend,e.provider??``,e.model??``,e.runtime??``,e.route??``,e.prompt_profile??``,e.prompt_profile_source??``,e.prompt_profile_reason??``,Ha(e.summary,120),e.error_code??``,e.error_message??``,e.wait_status??``,e.done===!0?`1`:`0`,e.timed_out===!0?`1`:`0`,e.batch_status??``,e.total_count===void 0?``:String(e.total_count),e.accepted_count===void 0?``:String(e.accepted_count),e.rejected_count===void 0?``:String(e.rejected_count),e.event_count===void 0?``:String(e.event_count),Ha(e.assistant_text,96),Ua(e.tool_rows),Wa(e.items)].join(`¦`)}function Ka(e){return e.status===`succeeded`||e.status===`failed`||e.status===`cancelled`||e.op===`wait`&&(e.done===!0||e.wait_status===`timeout`||e.wait_status===`aborted`)}function qa(e,t){let n=Ga(t),r=Date.now(),i=Va.get(e),a=typeof t.event_count==`number`?t.event_count:void 0,o=Ua(t.tool_rows),s=t.assistant_text;if(i&&i.signatureKey===n)return!1;let c=Ka(t),l=Lr(),u=i!==void 0&&(i.status!==t.status||a!==void 0&&(i.eventCount===void 0||a>i.eventCount)||i.toolRowsSignature!==o||i.assistantText!==s);return!c&&!u&&i&&r-i.atEpochMs<l?!1:(Va.set(e,{atEpochMs:r,signatureKey:n,status:t.status,eventCount:a,toolRowsSignature:o,assistantText:s}),!0)}function Ja(e){let t=za.get(e);if(t)return t;let n=Ge(e);return za.set(e,n),n}function Ya(e){let t=Ba.get(e);t&&(clearInterval(t),Ba.delete(e))}function Xa(e,t){if(Ba.get(e))return;let n=Ja(e),r=setInterval(()=>{let r=Ra({snapshots:t.taskStore.listTasks(),nowEpochMs:Date.now(),maxItems:5});n.publish(r),r.hasActiveTasks||Ya(e)},120);Ba.set(e,r)}function Za(e){if(!e.onUpdate||e.hasUI)return()=>{};let t=setInterval(()=>{let n=e.deps.taskStore.getTask(e.taskId);if(!n){clearInterval(t);return}if(e.isTerminalState(n.state)){clearInterval(t);return}X({details:e.snapshotToDetails(e.op,n,n.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})},120);return()=>{clearInterval(t)}}function X(e){let t=Ra({snapshots:e.deps.taskStore.listTasks(),nowEpochMs:Date.now(),maxItems:5});if(e.hasUI&&e.ui&&Ve()!==`off`?(Ja(e.ui).publish(t),t.hasActiveTasks?Xa(e.ui,e.deps):Ya(e.ui)):e.ui&&(Ya(e.ui),za.get(e.ui)?.clear()),!e.onUpdate||!qa(e.onUpdate,e.details))return;let n=t.statusLine,r=(()=>e.hasUI?ra(e.details,!1):`${n}\n\n${Fi(e.details).text}`)();e.onUpdate({content:[{type:`text`,text:r}],details:e.details})}function Qa(e,t){return xe(e,t)}function Z(e){return ye({details:e.details,toResult:U,report:t=>{X({details:t.details,deps:e.runtime.deps,hasUI:e.runtime.hasUI,ui:e.runtime.ui,onUpdate:e.runtime.onUpdate})}})}function $a(e,t){return be(t,t=>la(e,t.id,t.code,t.message))}async function eo(e,t){let n=Qa(t),r=$a(`cancel`,t.deps.taskStore.getTasks([e.id])[0]);if(a.isError(r))return U(r.error);let i=r.value,o=i.state;if(q(i.state))return Z({runtime:n,details:{...Y(`cancel`,i),summary:`Task '${i.id}' is already terminal (${i.state}); cancel not applied`,cancel_applied:!1,prior_status:o}});let s=t.deps.taskStore.markCancelled(e.id,`Cancelled ${i.subagentType}: ${i.description}`);if(a.isError(s))return Z({runtime:n,details:{op:`cancel`,status:`failed`,summary:s.error.message,backend:i.backend,task_id:e.id,error_code:s.error.code,error_message:s.error.message}});let c=s.value.state===`cancelled`;return Z({runtime:n,details:{...Y(`cancel`,s.value),cancel_applied:c,prior_status:o}})}function to(e){return e.type===`task_terminal`}function no(e){let t=[],n,r=0,i=()=>{if(n&&=(clearTimeout(n),void 0),t.length===0)return;let r=t;t=[];let i=e.deps.taskStore.appendEvents(e.taskId,r);a.isError(i)||X({details:Y(e.op,i.value),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})},o=()=>{n||=setTimeout(()=>{i()},40)};return{onEvent(e){if(r+=1,t.push(e),t.length>=24||to(e)){i();return}o()},flush:i,dispose(){n&&=(clearTimeout(n),void 0),t=[]},getStreamedEventCount(){return r}}}function ro(e){if(!e.backendEvents||e.backendEvents.length===0)return e.deps.taskStore.appendEvents(e.taskId,[]);let t=e.backendEvents.slice(Math.min(e.streamedEventCount,e.backendEvents.length));return t.length===0?e.deps.taskStore.appendEvents(e.taskId,[]):e.deps.taskStore.appendEvents(e.taskId,t)}async function io(e){await new Promise(t=>{setTimeout(t,e)})}function ao(e){let t=e.deps.taskStore.updateObservability(e.taskId,{provider:e.observability.provider,model:e.observability.model,runtime:e.observability.runtime,route:e.observability.route,promptProfile:e.observability.promptProfile,promptProfileSource:e.observability.promptProfileSource,promptProfileReason:e.observability.promptProfileReason});a.isError(t)||X({details:Y(e.op,t.value),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})}async function oo(e){let t=e.deps.taskStore.markRunning(e.taskId,`Starting ${e.subagent.name}: ${e.description}`);if(a.isError(t)){let n=W(e.deps.backend,e.config),r={id:e.taskId,state:`failed`,subagentType:e.subagent.id,description:e.description,prompt:e.prompt,followUpPrompts:[],summary:t.error.message,backend:n,provider:`unavailable`,model:`unavailable`,runtime:n,route:n,invocation:$(e.subagent.primary),totalToolCalls:0,activeToolCalls:0,startedAtEpochMs:Date.now(),updatedAtEpochMs:Date.now(),endedAtEpochMs:Date.now(),errorCode:t.error.code,errorMessage:t.error.message,events:[]};return X({details:Y(`start`,r),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),r}X({details:Y(`start`,t.value),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate});let n=no({taskId:e.taskId,op:`start`,deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),r=Za({op:`start`,taskId:e.taskId,deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate,isTerminalState:q,snapshotToDetails:Y}),i;try{i=await e.deps.backend.executeStart({taskId:e.taskId,subagent:e.subagent,description:e.description,prompt:e.prompt,cwd:e.cwd,config:e.config,signal:e.signal,onEvent:n.onEvent,onObservability:t=>{ao({op:`start`,taskId:e.taskId,observability:t,deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})}})}finally{r(),n.flush(),n.dispose()}let o=e.deps.taskStore.getTask(e.taskId);if(o&&q(o.state))return X({details:Y(`start`,o,o.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),o;if(a.isError(i)){if(i.error.code===`task_aborted`){let t=e.deps.taskStore.markCancelled(e.taskId,`Cancelled ${e.subagent.name}: ${e.description}`);if(a.isOk(t))return X({details:Y(`start`,t.value),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),t.value}let n=e.deps.taskStore.markFailed(e.taskId,i.error.message,i.error.code,i.error.message);if(a.isOk(n))return X({details:Y(`start`,n.value,n.value.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),n.value;let r={...t.value,state:`failed`,summary:n.error.message,errorCode:n.error.code,errorMessage:n.error.message,activeToolCalls:0,endedAtEpochMs:Date.now(),updatedAtEpochMs:Date.now()};return X({details:Y(`start`,r,r.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),r}let s=ro({taskId:e.taskId,streamedEventCount:n.getStreamedEventCount(),backendEvents:i.value.events,deps:e.deps});if(a.isError(s)){let t=e.deps.taskStore.markFailed(e.taskId,s.error.message,s.error.code,s.error.message);if(a.isOk(t))return X({details:Y(`start`,t.value,t.value.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),t.value}let c=e.deps.taskStore.markSucceeded(e.taskId,i.value.summary,i.value.output,{provider:i.value.provider,model:i.value.model,runtime:i.value.runtime,route:i.value.route,promptProfile:i.value.promptProfile,promptProfileSource:i.value.promptProfileSource,promptProfileReason:i.value.promptProfileReason});if(a.isError(c)){let n={...t.value,state:`failed`,summary:c.error.message,errorCode:c.error.code,errorMessage:c.error.message,activeToolCalls:0,endedAtEpochMs:Date.now(),updatedAtEpochMs:Date.now()};return X({details:Y(`start`,n,n.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),n}return X({details:Y(`start`,c.value,c.value.output),deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate}),c.value}function so(e){let t=W(e.deps.backend,e.config),n=e.deps.taskStore.createTask({taskId:e.taskId,subagent:e.subagent,description:e.description,prompt:e.prompt,backend:t,observability:{provider:`unavailable`,model:`unavailable`,runtime:t,route:t},invocation:$(e.subagent.primary)});if(a.isError(n))return a.err(J({id:e.taskId,summary:n.error.message,errorCode:n.error.code,errorMessage:n.error.message,subagentType:e.subagent.id,description:e.description}));let r=new AbortController,i=va(e.signal,r),o=e.deps.taskStore.setAbortController(e.taskId,r);return a.isError(o)?(i(),a.err(J({id:e.taskId,summary:o.error.message,errorCode:o.error.code,errorMessage:o.error.message,subagentType:e.subagent.id,description:e.description}))):a.ok({index:e.index,taskId:e.taskId,createdSnapshot:n.value,run:async()=>{let t=oo({taskId:e.taskId,subagent:e.subagent,description:e.description,prompt:e.prompt,cwd:e.cwd,config:e.config,signal:r.signal,onUpdate:e.onUpdate,hasUI:e.hasUI,ui:e.ui,deps:e.deps}).finally(()=>{i()}),o=t.then(()=>void 0),s=e.deps.taskStore.setExecutionPromise(e.taskId,o);if(a.isError(s)){r.abort();let t=e.deps.taskStore.markFailed(e.taskId,s.error.message,s.error.code,s.error.message);return a.isError(t)?xa({created:n.value,errorCode:t.error.code,errorMessage:t.error.message}):t.value}return t}})}async function co(e,t){let n=Math.min(Math.max(t,1),e.length),r=Array.from({length:e.length},()=>void 0),i=0,a=async()=>{for(;;){let t=i;if(t>=e.length)return;i+=1;let n=e[t];if(!n)return;r[t]=await n.run(),await io(0)}},o=[];for(let e=0;e<n;e+=1)o.push(a());return await Promise.all(o),e.map((e,t)=>r[t]||e.createdSnapshot)}function lo(e){return no({taskId:e.taskId,op:e.op,deps:e.deps,hasUI:e.hasUI,ui:e.ui,onUpdate:e.onUpdate})}function uo(e,t){return Z({details:t,runtime:Qa(e)})}async function fo(e,t,n){let r=W(t.deps.backend,n.config),i=$a(`send`,t.deps.taskStore.getTasks([e.id])[0]);if(a.isError(i))return U(i.error);let o=i.value;if(q(o.state))return U({op:`send`,status:`failed`,task_id:o.id,subagent_type:o.subagentType,description:o.description,summary:`Task '${o.id}' is terminal (${o.state}) and cannot be resumed`,backend:o.backend,invocation:o.invocation,error_code:`task_not_resumable`,error_message:`Task '${o.id}' is terminal (${o.state}) and cannot be resumed`});let s=Ie({subagentId:o.subagentType,config:n.config});if(!s)return U(Ca({op:`send`,backendId:r,taskId:o.id,subagentType:o.subagentType,description:o.description,invocation:o.invocation}));let c=da(s,n.config);if(a.isError(c))return U(wa({op:`send`,backendId:r,taskId:o.id,subagentType:o.subagentType,description:o.description,invocation:o.invocation,code:c.error.code,message:c.error.message}));let l=fa(s,n.config);if(a.isError(l))return U(Ta({op:`send`,backendId:r,taskId:o.id,subagentType:o.subagentType,description:o.description,invocation:o.invocation,code:l.error.code,message:l.error.message}));let u=t.deps.taskStore.markInteractionRunning(e.id,`Continuing ${s.name}: ${o.description}`,e.prompt);if(a.isError(u))return U({op:`send`,status:`failed`,task_id:e.id,summary:u.error.message,backend:r,error_code:u.error.code,error_message:u.error.message});X({details:Y(`send`,u.value),deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate});let d=lo({taskId:u.value.id,op:`send`,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate}),f=Za({op:`send`,taskId:u.value.id,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate,isTerminalState:q,snapshotToDetails:Y}),p;try{p=await t.deps.backend.executeSend({taskId:u.value.id,subagent:s,description:u.value.description,initialPrompt:u.value.prompt,followUpPrompts:u.value.followUpPrompts,prompt:e.prompt,cwd:t.cwd,config:n.config,signal:t.signal,onEvent:d.onEvent,onObservability:e=>{ao({op:`send`,taskId:u.value.id,observability:e,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate})}})}finally{f(),d.flush(),d.dispose()}if(a.isError(p)){let e=t.deps.taskStore.markFailed(u.value.id,p.error.message,p.error.code,p.error.message);if(a.isError(e))return uo(t,{op:`send`,status:`failed`,task_id:u.value.id,summary:e.error.message,backend:r,error_code:e.error.code,error_message:e.error.message});let n=U(Y(`send`,e.value,e.value.output));return X({details:n.details,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate}),n}let m=ro({taskId:u.value.id,streamedEventCount:d.getStreamedEventCount(),backendEvents:p.value.events,deps:t.deps});if(a.isError(m)){let e=t.deps.taskStore.markFailed(u.value.id,m.error.message,m.error.code,m.error.message);if(a.isError(e))return uo(t,{op:`send`,status:`failed`,task_id:u.value.id,summary:e.error.message,backend:r,error_code:e.error.code,error_message:e.error.message});let n=U(Y(`send`,e.value,e.value.output));return X({details:n.details,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate}),n}let h=t.deps.taskStore.markInteractionComplete(u.value.id,p.value.summary,p.value.output,{provider:p.value.provider,model:p.value.model,runtime:p.value.runtime,route:p.value.route,promptProfile:p.value.promptProfile,promptProfileSource:p.value.promptProfileSource,promptProfileReason:p.value.promptProfileReason});if(a.isError(h))return uo(t,{op:`send`,status:`failed`,task_id:u.value.id,summary:h.error.message,backend:r,error_code:h.error.code,error_message:h.error.message});let g=U(Y(`send`,h.value,p.value.output));return X({details:g.details,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate}),g}function po(e){let t=0,n=0,r=0,i=0;for(let a of e){if(!a.found){i+=1;continue}if(t+=1,a.status===`running`||a.status===`queued`){n+=1;continue}if(a.status===`succeeded`){r+=1;continue}i+=1}let a=e.length;return{totalCount:a,acceptedCount:t,rejectedCount:a-t,runningCount:n,succeededCount:r,failedCount:i}}function mo(e){let t=po(e),n=t.acceptedCount===0?`rejected`:t.runningCount>0?t.failedCount===0&&t.rejectedCount===0?`accepted`:`partial`:t.failedCount===0&&t.rejectedCount===0?`completed`:`partial`;return{status:t.acceptedCount===0?`failed`:t.runningCount>0?`running`:t.succeededCount===t.acceptedCount&&t.rejectedCount===0?`succeeded`:`failed`,totalCount:t.totalCount,acceptedCount:t.acceptedCount,rejectedCount:t.rejectedCount,batchStatus:n}}function ho(e){let t=po(e);return t.rejectedCount>0?`Completed batch tasks: ${t.succeededCount}/${t.acceptedCount} succeeded (${t.rejectedCount} rejected)`:`Completed batch tasks: ${t.succeededCount}/${t.totalCount} succeeded`}function go(e,t){if(t.status!==`running`)return ho(e);let n=po(e);return[`Running batch tasks: ${n.acceptedCount-n.runningCount}/${t.acceptedCount} done`,`active ${n.runningCount}`,`failed ${n.failedCount}`,`rejected ${t.rejectedCount}`].join(` · `)}function _o(e){let t=[...e.items],n=e.prepared.map(e=>e.taskId),r=e.deps.taskStore.getTasks(n),i=new Map;for(let e of r)i.set(e.id,e);for(let n of e.prepared){let e=i.get(n.taskId);e&&(t[n.index]=e.found&&e.snapshot?ja(e.snapshot):{id:e.id,found:!1,summary:e.errorMessage??`Unknown task id '${e.id}'`,output_available:!1,error_code:e.errorCode??`unknown_task_id`,error_message:e.errorMessage??`Unknown task id '${e.id}'`})}return t.map((e,t)=>e||J({id:`task_batch_${t+1}`,summary:`Batch task result unavailable`,errorCode:`task_batch_result_unavailable`,errorMessage:`Batch task result unavailable`}))}function vo(e){return e.map(e=>[e.id,e.found?`1`:`0`,e.status??`-`,e.updated_at_epoch_ms===void 0?`-`:String(e.updated_at_epoch_ms),e.event_count===void 0?`-`:String(e.event_count)].join(`:`)).join(`|`)}async function yo(e,t,n){let r=W(t.deps.backend,n.config),i=Array.from({length:e.tasks.length},()=>void 0),o=[];for(let r=0;r<e.tasks.length;r+=1){let s=e.tasks[r];if(!s){i[r]=J({id:`task_batch_${r+1}`,summary:`Missing batch task item`,errorCode:`task_batch_item_missing`,errorMessage:`Missing batch task item`});continue}let c=Ie({subagentId:s.subagent_type,config:n.config});if(!c){i[r]=J({id:`task_batch_${r+1}`,summary:`Unknown subagent_type '${s.subagent_type}'`,errorCode:`unknown_subagent_type`,errorMessage:`No subagent profile found for '${s.subagent_type}'.`,subagentType:s.subagent_type,description:s.description});continue}let l=da(c,n.config);if(a.isError(l)){i[r]=J({id:`task_batch_${r+1}`,summary:l.error.message,errorCode:l.error.code,errorMessage:l.error.message,subagentType:c.id,description:s.description});continue}let u=fa(c,n.config);if(a.isError(u)){i[r]=J({id:`task_batch_${r+1}`,summary:u.error.message,errorCode:u.error.code,errorMessage:u.error.message,subagentType:c.id,description:s.description});continue}let d=t.deps.createTaskId(),f=so({index:r,taskId:d,subagent:c,description:s.description,prompt:s.prompt,cwd:t.cwd,config:n.config,signal:t.signal,onUpdate:void 0,hasUI:t.hasUI,ui:t.ui,deps:t.deps});if(a.isError(f)){i[r]=f.error;continue}o.push(f.value),i[r]={...ja(f.value.createdSnapshot),invocation:Ea(c)}}let s=e.parallel?ba(n.config):1,c=t.onUpdate!==void 0||t.hasUI&&t.ui&&Ve()!==`off`,l,u=()=>{let e=_o({items:i,prepared:o,deps:t.deps}),n=vo(e);if(n===l)return;l=n;let a=mo(e),s=K(e,r);X({details:{op:`start`,status:a.status,summary:go(e,a),backend:r,provider:s.provider,model:s.model,runtime:s.runtime,route:s.route,...s.promptProfile?{prompt_profile:s.promptProfile}:{},...s.promptProfileSource?{prompt_profile_source:s.promptProfileSource}:{},...s.promptProfileReason?{prompt_profile_reason:s.promptProfileReason}:{},items:e,total_count:a.totalCount,accepted_count:a.acceptedCount,rejected_count:a.rejectedCount,batch_status:a.batchStatus},deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate})},d;c&&(u(),d=setInterval(()=>{u()},120));let f;try{f=await co(o,s)}finally{d&&clearInterval(d)}for(let e=0;e<o.length;e+=1){let t=o[e],n=f[e];!t||!n||(i[t.index]=ja(n))}let p=i.map((e,t)=>e||J({id:`task_batch_${t+1}`,summary:`Batch task result unavailable`,errorCode:`task_batch_result_unavailable`,errorMessage:`Batch task result unavailable`})),m=mo(p),h=K(p,r);return U({op:`start`,status:m.status,summary:ho(p),backend:r,provider:h.provider,model:h.model,runtime:h.runtime,route:h.route,...h.promptProfile?{prompt_profile:h.promptProfile}:{},...h.promptProfileSource?{prompt_profile_source:h.promptProfileSource}:{},...h.promptProfileReason?{prompt_profile_reason:h.promptProfileReason}:{},items:p,total_count:m.totalCount,accepted_count:m.acceptedCount,rejected_count:m.rejectedCount,batch_status:m.batchStatus})}async function bo(e,t,n){let r=W(t.deps.backend,n.config),i=Ie({subagentId:e.subagent_type,config:n.config});if(!i)return U(Ca({op:`start`,backendId:r,subagentType:e.subagent_type,description:e.description}));let o=da(i,n.config);if(a.isError(o))return U(wa({op:`start`,backendId:r,subagentType:i.id,description:e.description,invocation:Ea(i),code:o.error.code,message:o.error.message}));let s=fa(i,n.config);if(a.isError(s))return U(Ta({op:`start`,backendId:r,subagentType:i.id,description:e.description,invocation:Ea(i),code:s.error.code,message:s.error.message}));let c=t.deps.createTaskId(),l=so({index:0,taskId:c,subagent:i,description:e.description,prompt:e.prompt,cwd:t.cwd,config:n.config,signal:t.signal,onUpdate:t.onUpdate,hasUI:t.hasUI,ui:t.ui,deps:t.deps});if(a.isError(l))return U({op:`start`,status:`failed`,task_id:c,subagent_type:i.id,description:e.description,summary:l.error.summary,backend:r,error_code:l.error.error_code,error_message:l.error.error_message});let u=await l.value.run();return U(Y(`start`,u,u.output))}async function xo(e,t,n){if(ya(e)){let r=`tasks`in e?void 0:e.subagent_type,i=`tasks`in e?void 0:e.description;return U(Sa({backendId:W(t.deps.backend,n.config),subagentType:r,description:i}))}return`tasks`in e?yo(e,t,n):bo(e,t,n)}async function So(e,t){let n=t.deps.taskStore.getTasks(e.ids).map(e=>Ma(e)),r=ha(n,t.deps.backend.id),i=K(n,r);return Z({details:_a(`status`,n,r,!1,{provider:i.provider,model:i.model,runtime:i.runtime,route:i.route,promptProfile:i.promptProfile,promptProfileSource:i.promptProfileSource,promptProfileReason:i.promptProfileReason}).details,runtime:Qa(t,{onUpdate:void 0})})}async function Co(e){await new Promise(t=>{setTimeout(t,e)})}async function wo(e){if(!e){await new Promise(()=>void 0);return}e.aborted||await new Promise(t=>{let n=()=>{e.removeEventListener(`abort`,n),t()};e.addEventListener(`abort`,n,{once:!0})})}function To(e){return e.map(e=>{let t=e.snapshot;return[e.id,e.found?`1`:`0`,t?.state??`-`,t?.updatedAtEpochMs===void 0?`-`:String(t.updatedAtEpochMs)].join(`:`)}).join(`|`)}async function Eo(e){let t=Date.now(),n=0,r=``;for(;;){let i=e.deps.taskStore.getTasks(e.ids),a=Date.now(),o=To(i);(o!==r||a-n>=150)&&(e.onProgress?.(i),n=a,r=o);let s=[];for(let e of i)!e.found||!e.snapshot||q(e.snapshot.state)||s.push(e.id);if(s.length===0)return{lookups:i,timedOut:!1,timeoutReason:void 0};if(e.timeoutMs!==void 0&&a-t>=e.timeoutMs)return{lookups:i,timedOut:!0,timeoutReason:`timeout`};if(e.signal?.aborted)return{lookups:i,timedOut:!0,timeoutReason:`aborted`};let c=e.timeoutMs===void 0?120:Math.max(1,Math.min(120,e.timeoutMs-(a-t))),l=s.map(t=>e.deps.taskStore.getExecutionPromise(t)).filter(e=>e!==void 0).map(e=>e.catch(()=>{})),u=[Co(c),wo(e.signal)],d=[...l,...u];await Promise.race(d)}}async function Do(e,t){let n=await Eo({ids:e.ids,timeoutMs:e.timeout_ms,signal:t.signal,deps:t.deps,onProgress:e=>{let n=e.map(e=>Ma(e)),r=ha(n,t.deps.backend.id),i=K(n,r);X({details:U({op:`wait`,status:ma(n),summary:`wait for ${n.length} task(s)`,backend:r,provider:i.provider,model:i.model,runtime:i.runtime,route:i.route,...i.promptProfile?{prompt_profile:i.promptProfile}:{},...i.promptProfileSource?{prompt_profile_source:i.promptProfileSource}:{},...i.promptProfileReason?{prompt_profile_reason:i.promptProfileReason}:{},items:n,done:!1}).details,deps:t.deps,hasUI:t.hasUI,ui:t.ui,onUpdate:t.onUpdate})}}),r=n.lookups.map(e=>Ma(e)),i=ha(r,t.deps.backend.id),a=K(r,i),o=n.timeoutReason===`timeout`?`timeout`:n.timeoutReason===`aborted`?`aborted`:`completed`,s=_a(`wait`,r,i,n.timedOut,{done:o===`completed`,waitStatus:o,provider:a.provider,model:a.model,runtime:a.runtime,route:a.route,promptProfile:a.promptProfile,promptProfileSource:a.promptProfileSource,promptProfileReason:a.promptProfileReason});return Z({details:(n.timeoutReason===`timeout`?U({...s.details,error_code:`task_wait_timeout`,error_message:`Wait operation timed out before all tasks reached a terminal state`}):n.timeoutReason===`aborted`?U({...s.details,error_code:`task_wait_aborted`,error_message:`Wait operation aborted before all tasks reached a terminal state`}):s).details,runtime:Qa(t)})}function Oo(e){if(!e||typeof e!=`object`||Array.isArray(e))return`start`;let t=Reflect.get(e,`op`);return t===`start`||t===`status`||t===`wait`||t===`send`||t===`cancel`?t:t===`result`?`status`:`start`}function ko(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:Reflect.get(e,`op`)===`help`}function Ao(e,t,n,r){return{op:e,status:`failed`,summary:t,backend:`task`,error_code:n,error_message:r?`${t} (path: ${r})`:t}}function jo(e){let t=ci(e);if(a.isError(t)){let n=Oo(e);return a.err(Ao(n,t.error.message,t.error.code,typeof t.error.path==`string`?t.error.path:void 0))}return a.ok(t.value)}async function Mo(e,t){let n=await a.tryPromise({try:async()=>e.deps.loadConfig(e.cwd),catch:e=>new C({code:`task_config_load_failed`,stage:`task_tool`,cause:e,message:`Failed to load runtime config for task tool`})});if(a.isError(n))return a.err({op:t,status:`failed`,summary:n.error.message,backend:e.deps.backend.id,error_code:n.error.code,error_message:n.error.message});if(!n.value.config.features.subagents){let r=W(e.deps.backend,n.value.config);return a.err({op:t,status:`failed`,summary:`Subagents feature is disabled`,backend:r,error_code:`subagents_disabled`,error_message:`Enable features.subagents to use task orchestration and primary subagent tools`})}return a.ok(n.value)}async function No(e){return e.params.op===`start`?xo(e.params,e.toolInput,e.runtimeConfig):e.params.op===`status`?So(e.params,e.toolInput):e.params.op===`wait`?Do(e.params,e.toolInput):e.params.op===`send`?fo(e.params,e.toolInput,e.runtimeConfig):e.params.op===`cancel`?eo(e.params,e.toolInput):(e.params,U(ca(`start`)))}function Po(e){let t=[`Orchestrate subagent execution. Supports start/status/wait/send/cancel.`,`Subagent starts are synchronous and blocking. Async/background start mode is disabled.`,`Compatibility: status/wait accept either id or ids. op=result is treated as status.`,``,`Active subagent roster:`];for(let n of e){if(n.internal)continue;let e=$(n.primary);if(n.primary){t.push(`- ${n.id} (${e}): the ${n.name} is available via primary tool '${n.id}' and task start`);continue}t.push(`- ${n.id} (${e}): ${S(n)}`),Fo(t,`When to use:`,n.whenToUse),Fo(t,`When not to use:`,n.whenNotToUse),Fo(t,`Usage guidelines:`,n.usageGuidelines),Fo(t,`Examples:`,n.examples)}return t.join(`
22
+ `)}function Fo(e,t,n){if(!(!n||n.length===0)){e.push(` ${t}`);for(let t of n)e.push(` - ${t}`)}}async function Io(e){if(ko(e.params))return U({op:`status`,status:`failed`,summary:`Unsupported op 'help'. Use start, status, wait, send, or cancel.`,backend:e.deps.backend.id,error_code:`task_operation_not_supported`,error_message:`task tool supports op=start|status|wait|send|cancel (status/wait accept id or ids; result aliases status)`});let t=jo(e.params);if(a.isError(t))return U(t.error);let n=await Mo(e,t.value.op);return a.isError(n)?U(n.error):No({params:t.value,runtimeConfig:n.value,toolInput:e})}function Lo(e,t=Hr()){e.registerTool({name:`task`,label:`Task`,description:Po(t.subagents),parameters:Qr,execute:async(e,n,r,i,a)=>Io({params:n,cwd:a.cwd,signal:r,onUpdate:i,hasUI:a.hasUI,ui:a.hasUI?a.ui:void 0,deps:t}),renderCall:(e,t)=>new p(sa(e),0,0),renderResult:(e,t,n)=>{if(ia(e.details)&&!Vi())return ta(e.details,t.expanded);let r=ia(e.details)?ra(e.details,t.expanded):e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
23
23
 
24
- `);return new p(r.length>0?r:`task tool result unavailable`,0,0)}})}const Io={description:h.Optional(h.String({minLength:1})),async:h.Optional(h.Boolean())},Lo=h.Object({prompt:h.String({minLength:1}),...Io},{additionalProperties:!1}),Ro={librarian:h.Object({query:h.String({minLength:1}),context:h.Optional(h.String({minLength:1})),prompt:h.Optional(h.String({minLength:1})),...Io},{additionalProperties:!1}),oracle:h.Object({task:h.String({minLength:1}),context:h.Optional(h.String({minLength:1})),files:h.Optional(h.Array(h.String({minLength:1}),{minItems:1})),prompt:h.Optional(h.String({minLength:1})),...Io},{additionalProperties:!1}),finder:h.Object({query:h.String({minLength:1}),prompt:h.Optional(h.String({minLength:1})),...Io},{additionalProperties:!1}),default:Lo};function zo(e){let t=[S(e)];return Bo(t,`When to use:`,e.whenToUse),Bo(t,`When not to use:`,e.whenNotToUse),Bo(t,`Usage guidelines:`,e.usageGuidelines),Bo(t,`Examples:`,e.examples),t.push(``,`Invocation mode: ${$(e.primary)}`,`Task route still available via: task op=start subagent_type=${e.id}`),e.id===`librarian`?t.push(``,`Input: query (required), context (optional)`):e.id===`oracle`?t.push(``,`Input: task (required), context (optional), files[] (optional)`):e.id===`finder`?t.push(``,`Input: query (required)`):t.push(``,`Input: prompt (required)`),t.join(`
25
- `)}function Bo(e,t,n){if(!(!n||n.length===0)){e.push(``,t);for(let t of n)e.push(`- ${t}`)}}function Vo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e){if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)return t}function Ho(e){if(typeof e==`boolean`)return e}function Uo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function Wo(e){return e.filter(e=>e.trim().length>0).join(`
24
+ `);return new p(r.length>0?r:`task tool result unavailable`,0,0)}})}const Ro={description:h.Optional(h.String({minLength:1})),async:h.Optional(h.Boolean())},zo=h.Object({prompt:h.String({minLength:1}),...Ro},{additionalProperties:!1}),Bo={librarian:h.Object({query:h.String({minLength:1}),context:h.Optional(h.String({minLength:1})),prompt:h.Optional(h.String({minLength:1})),...Ro},{additionalProperties:!1}),oracle:h.Object({task:h.String({minLength:1}),context:h.Optional(h.String({minLength:1})),files:h.Optional(h.Array(h.String({minLength:1}),{minItems:1})),prompt:h.Optional(h.String({minLength:1})),...Ro},{additionalProperties:!1}),finder:h.Object({query:h.String({minLength:1}),prompt:h.Optional(h.String({minLength:1})),...Ro},{additionalProperties:!1}),default:zo};function Vo(e){let t=[S(e)];return Ho(t,`When to use:`,e.whenToUse),Ho(t,`When not to use:`,e.whenNotToUse),Ho(t,`Usage guidelines:`,e.usageGuidelines),Ho(t,`Examples:`,e.examples),t.push(``,`Invocation mode: ${$(e.primary)}`,`Task route still available via: task op=start subagent_type=${e.id}`),e.id===`librarian`?t.push(``,`Input: query (required), context (optional)`):e.id===`oracle`?t.push(``,`Input: task (required), context (optional), files[] (optional)`):e.id===`finder`?t.push(``,`Input: query (required)`):t.push(``,`Input: prompt (required)`),t.join(`
25
+ `)}function Ho(e,t,n){if(!(!n||n.length===0)){e.push(``,t);for(let t of n)e.push(`- ${t}`)}}function Uo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e){if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)return t}function Wo(e){if(typeof e==`boolean`)return e}function Go(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function Ko(e){return e.filter(e=>e.trim().length>0).join(`
26
26
 
27
- `)}function Go(e,t){if(!Vo(e))return{ok:!1,message:`Primary tool payload for '${t.id}' must be an object`};let n=Q(Reflect.get(e,`description`))??`${t.name} direct tool request`,r=Ho(Reflect.get(e,`async`)),i=Q(Reflect.get(e,`prompt`));if(t.id===`librarian`){let t=Q(Reflect.get(e,`query`))??i;if(!t)return{ok:!1,message:`librarian requires 'query' (or legacy 'prompt')`};let a=Q(Reflect.get(e,`context`));return{ok:!0,description:n,prompt:Wo([t,a?`Context:\n${a}`:``]),async:r}}if(t.id===`oracle`){let t=Q(Reflect.get(e,`task`))??i;if(!t)return{ok:!1,message:`oracle requires 'task' (or legacy 'prompt')`};let a=Q(Reflect.get(e,`context`)),o=Uo(Reflect.get(e,`files`)),s=o.length>0?[`Files:`,...o.map(e=>`- ${e}`),`Inspect these paths first.`].join(`
28
- `):``;return{ok:!0,description:n,prompt:Wo([t,a?`Context:\n${a}`:``,s]),async:r}}if(t.id===`finder`){let t=Q(Reflect.get(e,`query`))??i;return t?{ok:!0,description:n,prompt:t,async:r}:{ok:!1,message:`finder requires 'query' (or legacy 'prompt')`}}return i?{ok:!0,description:n,prompt:i,async:r}:{ok:!1,message:`primary tool '${t.id}' requires 'prompt'`}}function Ko(e){let t={contract_version:`task.v1`,op:`start`,status:`failed`,summary:e.message,backend:`task`,provider:`unavailable`,model:`unavailable`,runtime:`task`,route:`task`,subagent_type:e.subagent.id,invocation:$(e.subagent.primary),error_code:`invalid_primary_tool_payload`,error_category:`validation`,error_message:e.message};return{content:[{type:`text`,text:ia(t,!1)}],details:t}}function qo(e){return e.id===`librarian`?Ro.librarian:e.id===`oracle`?Ro.oracle:e.id===`finder`?Ro.finder:Ro.default}function Jo(e,t){let n=Go(t,e);return n.ok?`${e.id} · ${n.description}`:e.id}function Yo(e,t){if(Xo(e.details))return ia(e.details,t);let n=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
27
+ `)}function qo(e,t){if(!Uo(e))return{ok:!1,message:`Primary tool payload for '${t.id}' must be an object`};let n=Q(Reflect.get(e,`description`))??`${t.name} direct tool request`,r=Wo(Reflect.get(e,`async`)),i=Q(Reflect.get(e,`prompt`));if(t.id===`librarian`){let t=Q(Reflect.get(e,`query`))??i;if(!t)return{ok:!1,message:`librarian requires 'query' (or legacy 'prompt')`};let a=Q(Reflect.get(e,`context`));return{ok:!0,description:n,prompt:Ko([t,a?`Context:\n${a}`:``]),async:r}}if(t.id===`oracle`){let t=Q(Reflect.get(e,`task`))??i;if(!t)return{ok:!1,message:`oracle requires 'task' (or legacy 'prompt')`};let a=Q(Reflect.get(e,`context`)),o=Go(Reflect.get(e,`files`)),s=o.length>0?[`Files:`,...o.map(e=>`- ${e}`),`Inspect these paths first.`].join(`
28
+ `):``;return{ok:!0,description:n,prompt:Ko([t,a?`Context:\n${a}`:``,s]),async:r}}if(t.id===`finder`){let t=Q(Reflect.get(e,`query`))??i;return t?{ok:!0,description:n,prompt:t,async:r}:{ok:!1,message:`finder requires 'query' (or legacy 'prompt')`}}return i?{ok:!0,description:n,prompt:i,async:r}:{ok:!1,message:`primary tool '${t.id}' requires 'prompt'`}}function Jo(e){return U({contract_version:`task.v1`,op:`start`,status:`failed`,summary:e.message,backend:`task`,provider:`unavailable`,model:`unavailable`,runtime:`task`,route:`task`,subagent_type:e.subagent.id,invocation:$(e.subagent.primary),error_code:`invalid_primary_tool_payload`,error_category:`validation`,error_message:e.message})}function Yo(e){return e.id===`librarian`?Bo.librarian:e.id===`oracle`?Bo.oracle:e.id===`finder`?Bo.finder:Bo.default}function Xo(e,t){let n=qo(t,e);return n.ok?`${e.id} · ${n.description}`:e.id}function Zo(e,t){if(Qo(e.details))return oa(e.details,t);let n=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
29
29
 
30
- `);return n.length>0?n:`primary subagent tool result unavailable`}function Xo(e){return!(typeof e!=`object`||!e||!(`op`in e)||typeof e.op!=`string`||!(`status`in e)||typeof e.status!=`string`||!(`summary`in e)||typeof e.summary!=`string`||!(`backend`in e)||typeof e.backend!=`string`)}async function Zo(e){let t=Go(e.params,e.subagent);return t.ok?Po({params:{op:`start`,subagent_type:e.subagent.id,description:t.description,prompt:t.prompt,async:t.async},cwd:e.cwd,signal:e.signal,onUpdate:e.onUpdate,hasUI:e.hasUI,ui:e.ui,deps:e.deps}):Ko({subagent:e.subagent,message:t.message})}function Qo(e,t={}){let n=t.taskDeps??Hr(),r=t.catalog??x,i=new Set(t.reservedToolNames??[`task`]),a=[],o=[],s=e=>{o.push(e),t.onDiagnostic?.(e)};for(let t of r){if(t.primary!==!0)continue;let r=t.id;if(i.has(r)){s(`Skipping primary tool '${r}' due to naming collision with reserved tool namespace`);continue}i.add(r),e.registerTool({name:r,label:t.name,description:zo(t),parameters:qo(t),execute:async(e,r,i,a,o)=>Zo({subagent:t,params:r,cwd:o.cwd,signal:i,onUpdate:a,hasUI:o.hasUI,ui:o.hasUI?o.ui:void 0,deps:n}),renderCall:(e,n)=>new p(Jo(t,e),0,0),renderResult:(e,t,n)=>new p(Yo(e,t.expanded),0,0)}),a.push(r)}return{registeredTools:a,diagnostics:o}}function $o(e){return typeof e==`object`&&!!e}function es(e){if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(typeof e==`string`)return e.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0);if($o(e)){if(Array.isArray(e.args))return e.args.filter(e=>typeof e==`string`);if(typeof e.raw==`string`)return e.raw.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0)}return[]}function $(e){return e?`primary-tool`:`task-routed`}function ts(){return x.map(e=>e.id).join(`|`)}function ns(e){return Le(e).filter(t=>Ae(t,e))}function rs(e){let t=ns(e.config).map(t=>{let n=t.id!==`painter`||e.config.features.painterImagegen?`available`:`requires painter feature/package`,r=$(t.primary);return`- ${t.name} (${t.id}): ${S(t)} [${n} · ${r}]`});return[`Pi OHM: subagents`,``,`enabled: ${e.config.features.subagents?`yes`:`no`}`,`backend: ${e.config.subagentBackend}`,``,`Scaffolded subagents:`,...t,``,`Use /ohm-subagent <id> to inspect one profile.`,`loadedFrom: ${e.loadedFrom.length>0?e.loadedFrom.join(`, `):`defaults + extension settings`}`].join(`
31
- `)}function is(t){let n=t.subagent.id!==`painter`||t.config.features.painterImagegen,r=e(t.config,t.subagent.id),i=as(r),a=i!==void 0&&r?r.slice(0,r.lastIndexOf(`:`)):r;return[`Subagent: ${t.subagent.name}`,`id: ${t.subagent.id}`,`available: ${n?`yes`:`no`}`,`invocation: ${$(t.subagent.primary)}`,`model: ${a??`runtime default`}`,`thinking: ${i??`runtime default`}`,`modelPattern: ${r??`runtime default`}`,t.subagent.requiresPackage?`requiresPackage: ${t.subagent.requiresPackage}`:`requiresPackage: none`,``,`description: ${S(t.subagent)}`,``,`When to use:`,...t.subagent.whenToUse.map(e=>`- ${e}`)].join(`
32
- `)}function as(e){if(!e)return;let t=e.lastIndexOf(`:`);if(t<=0||t>=e.length-1)return;let n=e.slice(t+1).trim().toLowerCase();if(!(n!==`off`&&n!==`minimal`&&n!==`low`&&n!==`medium`&&n!==`high`&&n!==`xhigh`))return n}function os(e){let[t]=es(e),n=Ve();if(!t)return{ok:!0,mode:n,message:[`subagents live ui mode: ${n}`,`Usage: /ohm-subagents-live <off|compact|verbose>`].join(`
30
+ `);return n.length>0?n:`primary subagent tool result unavailable`}function Qo(e){return!(typeof e!=`object`||!e||!(`op`in e)||typeof e.op!=`string`||!(`status`in e)||typeof e.status!=`string`||!(`summary`in e)||typeof e.summary!=`string`||!(`backend`in e)||typeof e.backend!=`string`)}async function $o(e){let t=qo(e.params,e.subagent);return t.ok?Io({params:{op:`start`,subagent_type:e.subagent.id,description:t.description,prompt:t.prompt,async:t.async},cwd:e.cwd,signal:e.signal,onUpdate:e.onUpdate,hasUI:e.hasUI,ui:e.ui,deps:e.deps}):Jo({subagent:e.subagent,message:t.message})}function es(e,t={}){let n=t.taskDeps??Hr(),r=t.catalog??x,i=new Set(t.reservedToolNames??[`task`]),a=[],o=[],s=e=>{o.push(e),t.onDiagnostic?.(e)};for(let t of r){if(t.primary!==!0)continue;let r=t.id;if(i.has(r)){s(`Skipping primary tool '${r}' due to naming collision with reserved tool namespace`);continue}i.add(r),e.registerTool({name:r,label:t.name,description:Vo(t),parameters:Yo(t),execute:async(e,r,i,a,o)=>$o({subagent:t,params:r,cwd:o.cwd,signal:i,onUpdate:a,hasUI:o.hasUI,ui:o.hasUI?o.ui:void 0,deps:n}),renderCall:(e,n)=>new p(Xo(t,e),0,0),renderResult:(e,t,n)=>new p(Zo(e,t.expanded),0,0)}),a.push(r)}return{registeredTools:a,diagnostics:o}}function ts(e){return typeof e==`object`&&!!e}function ns(e){if(Array.isArray(e))return e.filter(e=>typeof e==`string`);if(typeof e==`string`)return e.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0);if(ts(e)){if(Array.isArray(e.args))return e.args.filter(e=>typeof e==`string`);if(typeof e.raw==`string`)return e.raw.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0)}return[]}function $(e){return e?`primary-tool`:`task-routed`}function rs(){return x.map(e=>e.id).join(`|`)}function is(e){return Le(e).filter(t=>Ae(t,e))}function as(e){let t=is(e.config).map(t=>{let n=t.id!==`painter`||e.config.features.painterImagegen?`available`:`requires painter feature/package`,r=$(t.primary);return`- ${t.name} (${t.id}): ${S(t)} [${n} · ${r}]`});return[`Pi OHM: subagents`,``,`enabled: ${e.config.features.subagents?`yes`:`no`}`,`backend: ${e.config.subagentBackend}`,``,`Scaffolded subagents:`,...t,``,`Use /ohm-subagent <id> to inspect one profile.`,`loadedFrom: ${e.loadedFrom.length>0?e.loadedFrom.join(`, `):`defaults + extension settings`}`].join(`
31
+ `)}function os(t){let n=t.subagent.id!==`painter`||t.config.features.painterImagegen,r=e(t.config,t.subagent.id),i=ss(r),a=i!==void 0&&r?r.slice(0,r.lastIndexOf(`:`)):r;return[`Subagent: ${t.subagent.name}`,`id: ${t.subagent.id}`,`available: ${n?`yes`:`no`}`,`invocation: ${$(t.subagent.primary)}`,`model: ${a??`runtime default`}`,`thinking: ${i??`runtime default`}`,`modelPattern: ${r??`runtime default`}`,t.subagent.requiresPackage?`requiresPackage: ${t.subagent.requiresPackage}`:`requiresPackage: none`,``,`description: ${S(t.subagent)}`,``,`When to use:`,...t.subagent.whenToUse.map(e=>`- ${e}`)].join(`
32
+ `)}function ss(e){if(!e)return;let t=e.lastIndexOf(`:`);if(t<=0||t>=e.length-1)return;let n=e.slice(t+1).trim().toLowerCase();if(!(n!==`off`&&n!==`minimal`&&n!==`low`&&n!==`medium`&&n!==`high`&&n!==`xhigh`))return n}function cs(e){let[t]=ns(e),n=Ve();if(!t)return{ok:!0,mode:n,message:[`subagents live ui mode: ${n}`,`Usage: /ohm-subagents-live <off|compact|verbose>`].join(`
33
33
  `)};let r=Ue(t);return r?(He(r),{ok:!0,mode:r,message:`subagents live ui mode set to '${r}'`}):{ok:!1,mode:n,message:[`Invalid mode '${t}'.`,`Use one of: off|compact|verbose`].join(`
34
- `)}}function ss(e){let t=Hr();Fo(e,t);let n=Qo(e,{taskDeps:t});return{primaryToolCount:n.registeredTools.length,diagnosticsCount:n.diagnostics.length}}function cs(e){n(e);let r=ss(e);e.on(`session_start`,async(e,n)=>{let{config:i}=await t(n.cwd);if(!n.hasUI)return;let a=i.features.subagents?`on`:`off`,o=r.primaryToolCount,s=r.diagnosticsCount;n.ui.setStatus(`ohm-subagents`,`subagents:${a} · backend:${i.subagentBackend} · primary:${o} · diag:${s}`)}),e.registerCommand(`ohm-subagents`,{description:`Show scaffolded subagents and backend status`,handler:async(e,n)=>{let{config:r,loadedFrom:i}=await t(n.cwd),a=rs({config:r,loadedFrom:i});if(!n.hasUI){console.log(a);return}await n.ui.editor(`pi-ohm subagents`,a)}}),e.registerCommand(`ohm-subagent`,{description:`Inspect one subagent scaffold/profile (${ts()} + custom profiles)`,handler:async(e,n)=>{let{config:r}=await t(n.cwd),[i=``]=es(e),a=Ie({subagentId:i,config:r}),o=ns(r).map(e=>e.id);if(!a||!o.includes(a.id)){let e=[`Usage: /ohm-subagent <id>`,``,`Valid ids: ${o.join(`, `)}`].join(`
35
- `);if(!n.hasUI){console.log(e);return}await n.ui.editor(`pi-ohm subagent usage`,e);return}let s=is({config:r,subagent:a});if(!n.hasUI){console.log(s);return}await n.ui.editor(`pi-ohm ${a.id} subagent`,s)}}),e.registerCommand(`ohm-subagents-live`,{description:`Set subagents live UI mode (off|compact|verbose)`,handler:async(e,t)=>{let n=os(e);if(!t.hasUI){console.log(n.message);return}n.mode===`off`?(t.ui.setStatus(`ohm-subagents`,void 0),t.ui.setWidget(`ohm-subagents`,void 0,{placement:`belowEditor`})):t.ui.setStatus(`ohm-subagents`,`subagents live ui: ${n.mode}`),await t.ui.editor(`pi-ohm subagents live`,n.message)}})}export{is as buildSubagentDetailText,rs as buildSubagentsOverviewText,cs as default,$ as getSubagentInvocationMode,es as normalizeCommandArgs,ss as registerSubagentTools,os as resolveSubagentsLiveUiModeCommand};
34
+ `)}}function ls(e){let t=Hr();Lo(e,t);let n=es(e,{taskDeps:t});return{primaryToolCount:n.registeredTools.length,diagnosticsCount:n.diagnostics.length}}function us(e){n(e);let r=ls(e);e.on(`session_start`,async(e,n)=>{let{config:i}=await t(n.cwd);if(!n.hasUI)return;let a=i.features.subagents?`on`:`off`,o=r.primaryToolCount,s=r.diagnosticsCount;n.ui.setStatus(`ohm-subagents`,`subagents:${a} · backend:${i.subagentBackend} · primary:${o} · diag:${s}`)}),e.registerCommand(`ohm-subagents`,{description:`Show scaffolded subagents and backend status`,handler:async(e,n)=>{let{config:r,loadedFrom:i}=await t(n.cwd),a=as({config:r,loadedFrom:i});if(!n.hasUI){console.log(a);return}await n.ui.editor(`pi-ohm subagents`,a)}}),e.registerCommand(`ohm-subagent`,{description:`Inspect one subagent scaffold/profile (${rs()} + custom profiles)`,handler:async(e,n)=>{let{config:r}=await t(n.cwd),[i=``]=ns(e),a=Ie({subagentId:i,config:r}),o=is(r).map(e=>e.id);if(!a||!o.includes(a.id)){let e=[`Usage: /ohm-subagent <id>`,``,`Valid ids: ${o.join(`, `)}`].join(`
35
+ `);if(!n.hasUI){console.log(e);return}await n.ui.editor(`pi-ohm subagent usage`,e);return}let s=os({config:r,subagent:a});if(!n.hasUI){console.log(s);return}await n.ui.editor(`pi-ohm ${a.id} subagent`,s)}}),e.registerCommand(`ohm-subagents-live`,{description:`Set subagents live UI mode (off|compact|verbose)`,handler:async(e,t)=>{let n=cs(e);if(!t.hasUI){console.log(n.message);return}n.mode===`off`?(t.ui.setStatus(`ohm-subagents`,void 0),t.ui.setWidget(`ohm-subagents`,void 0,{placement:`belowEditor`})):t.ui.setStatus(`ohm-subagents`,`subagents live ui: ${n.mode}`),await t.ui.editor(`pi-ohm subagents live`,n.message)}})}export{os as buildSubagentDetailText,as as buildSubagentsOverviewText,us as default,$ as getSubagentInvocationMode,ns as normalizeCommandArgs,ls as registerSubagentTools,cs as resolveSubagentsLiveUiModeCommand};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-ohm/subagents",
3
- "version": "0.6.4-dev.22597423022.1.b5a2ebf",
3
+ "version": "0.6.4-dev.22615359904.1.ffd8ea1",
4
4
  "homepage": "https://github.com/pi-ohm/pi-ohm/tree/dev/packages/subagents#readme",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,9 +27,9 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "@mariozechner/pi-coding-agent": "^0.54.2",
30
- "@pi-ohm/config": "0.6.4-dev.22597423022.1.b5a2ebf",
31
- "@pi-ohm/core": "0.6.4-dev.22597423022.1.b5a2ebf",
32
- "@pi-ohm/tui": "0.6.4-dev.22597423022.1.b5a2ebf",
30
+ "@pi-ohm/config": "0.6.4-dev.22615359904.1.ffd8ea1",
31
+ "@pi-ohm/core": "0.6.4-dev.22615359904.1.ffd8ea1",
32
+ "@pi-ohm/tui": "0.6.4-dev.22615359904.1.ffd8ea1",
33
33
  "better-result": "^2.6.0",
34
34
  "zod": "^4"
35
35
  },