@gencode/agents 0.10.0 → 0.10.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @gencode/agents
2
2
 
3
+ ## 0.10.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 93a0318: Agent system prompts now tell the model to place temporary and intermediate files under the workspace cleanup directories: `workspace/temp/daily/`, `workspace/temp/weekly/`, or `workspace/temp/monthly/`. These directories are created only when needed; AIMax does not pre-initialize them during startup.
8
+
9
+ ## 0.10.1
10
+
11
+ ### Patch Changes
12
+
13
+ - faaebd5: Agent runs no longer stop after a built-in default timeout. Runs started without `timeoutMs`, including subagent runs launched through `subagent_spawn` or `batch_subagent_spawn`, can continue until they finish or are cancelled by an external abort. Use `aimax run --timeout <ms>` or pass `timeoutMs` directly when a specific execution limit is required.
14
+ - 798bf31: Adds Windows platform support for process execution and improves debugging visibility. The `exec` and `process` tools now handle Windows-specific shell invocation and process tree management, enabling reliable execution on Windows systems. Additionally, command execution details are logged for better debugging and troubleshooting. These changes improve cross-platform compatibility and operational visibility without affecting existing CLI behavior.
15
+
3
16
  ## 0.10.0
4
17
 
5
18
  ### Minor Changes
package/dist/index.d.ts CHANGED
@@ -1145,7 +1145,7 @@ type AgentRunParamsBase = {
1145
1145
  maxTokens?: number; /** Flash model for lightweight tasks (e.g. title generation) */
1146
1146
  flashModel?: string;
1147
1147
  }; /** In-process progress callback */
1148
- onProgress?: (event: AgentProgressEvent$1) => Promise<void>; /** Execution timeout in milliseconds; defaults to 600000 (10 min) */
1148
+ onProgress?: (event: AgentProgressEvent$1) => Promise<void>; /** Execution timeout in milliseconds; omitted means no agent-loop timeout */
1149
1149
  timeoutMs?: number; /** Present when this run is itself a subagent; controls depth limits */
1150
1150
  subagentContext?: SubagentContext; /** AbortSignal to cancel this run from outside (used by parent kill) */
1151
1151
  abortSignal?: AbortSignal; /** Structured HITL resume state injected by CLI resume path. */
package/dist/index.js CHANGED
@@ -57,91 +57,91 @@ Preview:
57
57
  `);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
58
58
 
59
59
  `)}function zd(e){return e.role===`tool_result`}function Bd(e){return e.toolName===`skill_load`}function Vd(e){let t=Hd(e),n=t.name||`<skill-name>`,r=t.path?`skill_load(name="${n}", skillPath="${t.path}")`:`skill_load(name="${n}")`;return[`[skill content folded] The previous skill_load result for "${n}" was folded out of model-visible context.`,`The complete SKILL.md content is no longer available in the current prompt.`,`Before using this skill again, call ${r} again. Do not infer or reconstruct the skill instructions from memory or summaries.`,t.path?`Original path: ${t.path}`:``].filter(Boolean).join(`
60
- `)}function Hd(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Ud(t);if(e.name||e.path)return e}return{}}function Ud(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function Wd(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Gd(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Kd(e){let t=e.pendingUserMessage?.trim()?Z([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=Z(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=Z(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function qd(e,t,n,r){let i=k(e,t,r);await V.mkdir(H.dirname(i),{recursive:!0}),await V.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Jd(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await xd({dataDir:e.dataDir,sessionId:e.sessionId,...t});return{async getReusableRead(e,t,r){let i=await n.findReusableRead(e,t,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await n.recordRead(e)},async invalidateReadPath(e){await n.invalidatePath(e)},persistToolResult(e){return n.persistToolResult(e)},async recordModelUsage(e){await n.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(t){return Nd({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Yd(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent}):Nd({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent})}const Xd=W.Object({command:W.String({description:`Shell command to execute`}),workdir:W.Optional(W.String({description:`Working directory (relative to workspace root)`})),env:W.Optional(W.Record(W.String(),W.String())),timeout:W.Optional(W.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:W.Optional(W.Number({description:`Wait this many milliseconds before returning running state`})),background:W.Optional(W.Boolean({description:`Return immediately with running session`}))});function Zd(e,t,n){return Math.max(t,Math.min(n,e))}function Qd(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function $d(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:Zd(Math.floor(e),0,12e4)}function ef(e,t){if(!t?.trim())return e;let n=H.isAbsolute(t)?H.normalize(t):H.normalize(H.join(e,t));if(!n.startsWith(e+H.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function tf(e){let t=e.outputTail.trim();return`${t.length>0?`${t}\n\n`:``}Process is running in the background. sessionId=${e.sessionId}\nUse process(action="poll"|"log", sessionId) to continue.`}function nf(e){return af({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
61
- `)}function rf(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function af(e){let t=rf(e.stdout),n=e.stderr.trim();if(e.exitCode!==void 0&&e.exitCode!==0){let t=`Exit code: ${e.exitCode===null?`null`:e.exitCode}`;n=n.length>0?`${n}\n${t}`:t}return[t.length>0?t:`(no output)`,n,e.backgroundInfo?.trim()||``].filter(e=>e.length>0)}function of(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands. Prefer modern tools: rg (not grep), fd (not find), jq (not python/awk) for JSON. For long-running tasks set background:true and poll with process tool.`,parameters:Xd,async execute(t,n,r){if(!n.command?.trim())return{content:[{type:`text`,text:`Error: command is required.`}],details:{status:`failed`}};let i;try{i=ef(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Qd(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s&&!c){let t=await e.registry.wait(o.sessionId,e.scopeKey,void 0);t&&(l=t)}else if(!s){let t=await e.registry.wait(o.sessionId,e.scopeKey,$d(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:tf(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}};let d=e.registry.readOutput(l.sessionId,e.scopeKey),f=d?af({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[nf(l)],p=rf(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
60
+ `)}function Hd(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Ud(t);if(e.name||e.path)return e}return{}}function Ud(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function Wd(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Gd(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Kd(e){let t=e.pendingUserMessage?.trim()?Z([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=Z(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=Z(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function qd(e,t,n,r){let i=k(e,t,r);await V.mkdir(H.dirname(i),{recursive:!0}),await V.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Jd(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await xd({dataDir:e.dataDir,sessionId:e.sessionId,...t});return{async getReusableRead(e,t,r){let i=await n.findReusableRead(e,t,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await n.recordRead(e)},async invalidateReadPath(e){await n.invalidatePath(e)},persistToolResult(e){return n.persistToolResult(e)},async recordModelUsage(e){await n.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(t){return Nd({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Yd(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent}):Nd({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent})}const Xd=W.Object({command:W.String({description:`Shell command to execute`}),workdir:W.Optional(W.String({description:"Working directory, must be inside the workspace root (relative path resolved against workspace, or an absolute path under it). If the desired directory cannot be located inside the workspace, do NOT set workdir — instead adjust the command itself (e.g. prefix with `cd /abs/path && ...` or pass absolute paths as arguments)."})),env:W.Optional(W.Record(W.String(),W.String())),timeout:W.Optional(W.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:W.Optional(W.Number({description:`Wait this many milliseconds before returning running state`})),background:W.Optional(W.Boolean({description:`Return immediately with running session`}))});function Zd(e,t,n){return Math.max(t,Math.min(n,e))}function Qd(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function $d(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:Zd(Math.floor(e),0,12e4)}function ef(e,t){if(!t?.trim())return e;let n=H.isAbsolute(t)?H.normalize(t):H.normalize(H.join(e,t));if(!n.startsWith(e+H.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function tf(e){let t=e.outputTail.trim();return`${t.length>0?`${t}\n\n`:``}Process is running in the background. sessionId=${e.sessionId}\nUse process(action="poll"|"log", sessionId) to continue.`}function nf(e){return af({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
61
+ `)}function rf(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function af(e){let t=rf(e.stdout),n=e.stderr.trim();if(e.exitCode!==void 0&&e.exitCode!==0){let t=`Exit code: ${e.exitCode===null?`null`:e.exitCode}`;n=n.length>0?`${n}\n${t}`:t}return[t.length>0?t:`(no output)`,n,e.backgroundInfo?.trim()||``].filter(e=>e.length>0)}function of(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands. Prefer modern tools: rg (not grep), fd (not find), jq (not python/awk) for JSON. For long-running tasks set background:true and poll with process tool.`,parameters:Xd,async execute(t,n,r){if(!n.command?.trim())return{content:[{type:`text`,text:`Error: command is required.`}],details:{status:`failed`}};let i;try{i=ef(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Qd(n.timeout);console.log(`Executing command: ${n.command} in ${i} with timeout ${a} seconds`,{command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey});let o=e.registry.start({command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s&&!c){let t=await e.registry.wait(o.sessionId,e.scopeKey,void 0);t&&(l=t)}else if(!s){let t=await e.registry.wait(o.sessionId,e.scopeKey,$d(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:tf(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}};let d=e.registry.readOutput(l.sessionId,e.scopeKey),f=d?af({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[nf(l)],p=rf(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
62
62
  `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const sf=W.Object({action:W.String({description:`Process action: list | poll | log | kill`}),sessionId:W.Optional(W.String({description:`Session id for non-list actions`})),offset:W.Optional(W.Number({description:`Log line offset (0-based)`})),limit:W.Optional(W.Number({description:`Maximum lines to return`})),timeout:W.Optional(W.Number({description:`Poll wait time in milliseconds`}))});function cf(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function lf(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function uf(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:sf,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
63
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return lf(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,cf(n.timeout));return t?{content:[{type:`text`,text:t.status===`running`?`Session ${i} is still running.`:`Session ${i} finished with status=${t.status}, exitCode=${t.exitCode??`null`}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal,aggregated:t.status!==`running`}}:lf(`No session found for ${i}`)}if(r===`log`){let t=e.registry.readLog({sessionId:i,scopeKey:e.scopeKey,offset:n.offset,limit:n.limit});return t?{content:[{type:`text`,text:t.text.trim().length>0?t.text:`(no output)`}],details:{status:t.status,sessionId:i,totalLines:t.totalLines,totalChars:t.totalChars,truncated:t.truncated,exitCode:t.exitCode,exitSignal:t.exitSignal}}:lf(`No session found for ${i}`)}if(r===`kill`){let t=await e.registry.terminate(i,e.scopeKey);return t?{content:[{type:`text`,text:t.status===`running`?`Termination signal sent to ${i}.`:`Session ${i} terminated with status=${t.status}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal}}:lf(`No session found for ${i}`)}return lf(`Unsupported action: ${n.action}`)}}}const df=2e5;function ff(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function pf(e,t){let n=e+t;return n.length<=df?{text:n,truncated:!1}:{text:n.slice(-df),truncated:!0}}function mf(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=pf(e.output,r);e.output=i.text;let a=pf(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function hf(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:ff(e.output),stdoutTail:ff(e.stdout),stderrTail:ff(e.stderr),outputTruncated:e.outputTruncated}}function gf(e,t){return t?e.scopeKey===t:!0}function _f(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function vf(e){return e?e.split(/\r?\n/):[]}function yf(e){let t=vf(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=_f(e.limit,n?200:Math.max(1,t.length-r)),a=(n&&t.length>200?t.slice(t.length-200):t.slice(r,r+i)).join(`
64
- `);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function bf(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function xf(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),bf(e))};return{start(t){let n=bt(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:Ze(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>mf(o,`stdout`,e)),n.stderr.on(`data`,e=>mf(o,`stderr`,e));let s=_f(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,mf(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),mf(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),hf(o)},get(e,t){let n=r(e);return!n||!gf(n,t)?null:hf(n)},list(n){return[...e.values(),...t.values()].filter(e=>gf(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>hf(e))},async wait(e,t,n){let i=r(e);if(!i||!gf(i,t))return null;if(i.status!==`running`)return hf(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!gf(a,t)?null:hf(a)},readLog(e){let t=r(e.sessionId);return!t||!gf(t,e.scopeKey)?null:yf({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!gf(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!gf(n,t))return null;if(n.status!==`running`)return hf(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?hf(i):null}}}function Sf(e){return of({workspaceDir:e,registry:xf(),scopeKey:e})}const Cf=5*1024*1024,wf=2e3;async function Tf(e,t){e&&await e(t).catch(()=>{})}function Ef(e,t){return H.isAbsolute(e)?H.normalize(e):H.normalize(H.join(t,e))}const Df=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),offset:W.Optional(W.Number({description:`Line offset (1-based, default: 1)`})),limit:W.Optional(W.Number({description:`Maximum lines to read (default: 2000)`}))});function Of(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Df,async execute(n,r){let i;try{i=Ef(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await V.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await xt(s,s.length))return{content:[{type:`text`,text:`Error: read_file only supports text files. ${r.path} appears to be binary; use another tool or install an appropriate skill to handle it.`}],details:{content:``,lines:0,truncated:!1}};if(o.length>Cf){let e=o.slice(0,Cf).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Cf} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
65
- `),l=Math.max(1,r.offset??1),u=Math.min(wf,r.limit??wf),d=c.slice(l-1,l-1+u),f=d.length<c.length-(l-1),p=d.map((e,t)=>`${(l+t).toString().padStart(4)} ${e}`).join(`
63
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return lf(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,cf(n.timeout));return t?{content:[{type:`text`,text:t.status===`running`?`Session ${i} is still running.`:`Session ${i} finished with status=${t.status}, exitCode=${t.exitCode??`null`}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal,aggregated:t.status!==`running`}}:lf(`No session found for ${i}`)}if(r===`log`){let t=e.registry.readLog({sessionId:i,scopeKey:e.scopeKey,offset:n.offset,limit:n.limit});return t?{content:[{type:`text`,text:t.text.trim().length>0?t.text:`(no output)`}],details:{status:t.status,sessionId:i,totalLines:t.totalLines,totalChars:t.totalChars,truncated:t.truncated,exitCode:t.exitCode,exitSignal:t.exitSignal}}:lf(`No session found for ${i}`)}if(r===`kill`){let t=await e.registry.terminate(i,e.scopeKey);return t?{content:[{type:`text`,text:t.status===`running`?`Termination signal sent to ${i}.`:`Session ${i} terminated with status=${t.status}.`}],details:{status:t.status,sessionId:i,exitCode:t.exitCode,exitSignal:t.exitSignal}}:lf(`No session found for ${i}`)}return lf(`Unsupported action: ${n.action}`)}}}const df=process.platform===`win32`;function ff(e){return df?{shell:!0,file:process.env.ComSpec||process.env.COMSPEC||`cmd.exe`,args:[`/d`,`/s`,`/c`,`chcp 65001>nul & ${e}`]}:{file:`bash`,args:[`-lc`,e],shell:void 0}}function pf(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(df&&typeof e.pid==`number`){let n=[`/pid`,String(e.pid),`/T`];t===`SIGKILL`&&n.push(`/F`);try{bt(`taskkill`,n,{windowsHide:!0,stdio:`ignore`})}catch{try{e.kill()}catch{}}return}try{e.kill(t)}catch{}}}const mf=2e5;function hf(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function gf(e,t){let n=e+t;return n.length<=mf?{text:n,truncated:!1}:{text:n.slice(-mf),truncated:!0}}function _f(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=gf(e.output,r);e.output=i.text;let a=gf(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function vf(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:hf(e.output),stdoutTail:hf(e.stdout),stderrTail:hf(e.stderr),outputTruncated:e.outputTruncated}}function yf(e,t){return t?e.scopeKey===t:!0}function bf(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function xf(e){return e?e.split(/\r?\n/):[]}function Sf(e){let t=xf(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=bf(e.limit,n?200:Math.max(1,t.length-r)),a=(n&&t.length>200?t.slice(t.length-200):t.slice(r,r+i)).join(`
64
+ `);return{sessionId:e.record.sessionId,status:e.record.status,text:a,totalLines:t.length,totalChars:e.record.output.length,truncated:e.record.outputTruncated,exitCode:e.record.exitCode,exitSignal:e.record.exitSignal}}function Cf(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function wf(){let e=new Map,t=new Map,n=n=>{if(e.delete(n.sessionId),t.set(n.sessionId,n),t.size<=100)return;let r=Array.from(t.values()).sort((e,t)=>(e.endedAt??2**53-1)-(t.endedAt??2**53-1));for(;r.length>100;){let e=r.shift();if(!e)break;t.delete(e.sessionId)}},r=n=>e.get(n)??t.get(n)??null,i=(e,t)=>{e.endedAt===void 0&&(t?.(),e.endedAt=Date.now(),n(e),Cf(e))};return{start(t){let{file:n,args:r,shell:a}=ff(t.command),o=bt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:Ze(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:o,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:c,resolveDone:s};e.set(l.sessionId,l),o.stdout.on(`data`,e=>_f(l,`stdout`,e)),o.stderr.on(`data`,e=>_f(l,`stderr`,e));let u=bf(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,_f(l,`stderr`,Buffer.from(`\n[Timed out after ${u}s]\n`)),pf(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&pf(l.child,`SIGKILL`)},1e3))},u*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),_f(l,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),o.on(`close`,(e,t)=>{i(l,()=>{l.exitCode=e,l.exitSignal=t,l.status===`running`?l.status=e===0?`completed`:`failed`:l.status===`killed`&&e===0&&(l.status=`completed`)})}),vf(l)},get(e,t){let n=r(e);return!n||!yf(n,t)?null:vf(n)},list(n){return[...e.values(),...t.values()].filter(e=>yf(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>vf(e))},async wait(e,t,n){let i=r(e);if(!i||!yf(i,t))return null;if(i.status!==`running`)return vf(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!yf(a,t)?null:vf(a)},readLog(e){let t=r(e.sessionId);return!t||!yf(t,e.scopeKey)?null:Sf({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!yf(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!yf(n,t))return null;if(n.status!==`running`)return vf(n);n.status=`killed`,pf(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&pf(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?vf(i):null}}}function Tf(e){return of({workspaceDir:e,registry:wf(),scopeKey:e})}const Ef=5*1024*1024,Df=2e3;async function Of(e,t){e&&await e(t).catch(()=>{})}function kf(e,t){return H.isAbsolute(e)?H.normalize(e):H.normalize(H.join(t,e))}const Af=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),offset:W.Optional(W.Number({description:`Line offset (1-based, default: 1)`})),limit:W.Optional(W.Number({description:`Maximum lines to read (default: 2000)`}))});function jf(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Af,async execute(n,r){let i;try{i=kf(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await V.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await xt(s,s.length))return{content:[{type:`text`,text:`Error: read_file only supports text files. ${r.path} appears to be binary; use another tool or install an appropriate skill to handle it.`}],details:{content:``,lines:0,truncated:!1}};if(o.length>Ef){let e=o.slice(0,Ef).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Ef} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
65
+ `),l=Math.max(1,r.offset??1),u=Math.min(Df,r.limit??Df),d=c.slice(l-1,l-1+u),f=d.length<c.length-(l-1),p=d.map((e,t)=>`${(l+t).toString().padStart(4)} ${e}`).join(`
66
66
  `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
67
67
  `),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
68
- `),lines:d.length,truncated:f}}}}}const kf=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),content:W.String({description:`File content to write`})});function Af(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:kf,async execute(r,i){let a;try{a=Ef(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await V.mkdir(H.dirname(a),{recursive:!0}),await V.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await Tf(n,{type:`write`,operation:`write_file`,file:a,content:i.content,toolCallId:r,toolName:`write_file`})}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:a}}}return{content:[{type:`text`,text:`File written: ${i.path}`}],details:{path:a}}}}}const jf=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),old_string:W.String({description:`Exact text to replace`}),new_string:W.String({description:`Replacement text`})});function Mf(e,t,n){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:jf,async execute(r,i){let a;try{a=Ef(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await V.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await V.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await Tf(n,{type:`edit`,operation:`edit_file`,file:a,content:s,toolCallId:r,toolName:`edit_file`}),{content:[{type:`text`,text:`File edited: ${i.path}`}],details:{path:a,occurrences:1}}}}}const Nf=W.Object({path:W.Optional(W.String({description:`Directory path (default: workspace root)`}))});function Pf(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Nf,async execute(t,n){let r=n.path??`.`,i;try{i=Ef(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await V.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
69
- `)||`(empty directory)`}],details:{entries:a}}}}}const Ff=W.Object({input:W.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function If(e,t){let n=H.isAbsolute(e)?H.normalize(e):H.normalize(H.join(t,e));if(!n.startsWith(t+H.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Lf(e,t){let n=H.relative(t,e);return!n||n===``?H.basename(e):n.startsWith(`..`)||H.isAbsolute(n)?e:n}async function Rf(e){await V.mkdir(H.dirname(e),{recursive:!0})}async function zf(e,t){e&&await e(t).catch(()=>{})}function Bf(e){let t=[`Success. Updated the following files:`];for(let n of e.added)t.push(`A ${n}`);for(let n of e.modified)t.push(`M ${n}`);for(let n of e.deleted)t.push(`D ${n}`);return t.join(`
70
- `)}function Vf(e,t={}){return{name:`apply_patch`,label:`apply_patch`,description:`Apply a patch to one or more files using the apply_patch format. The input should include *** Begin Patch and *** End Patch markers.`,parameters:Ff,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=Uf(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let r of a.hunks){if(r.kind===`add`){let i=If(r.path,e);await Rf(i),await V.writeFile(i,r.contents,`utf-8`),await zf(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Hf(o,s,`added`,Lf(i,e));continue}if(r.kind===`delete`){let i=If(r.path,e);await V.rm(i,{force:!0,recursive:!1}),await zf(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Hf(o,s,`deleted`,Lf(i,e));continue}let i=If(r.path,e),a=await qf(i,r.chunks);if(r.movePath){let c=If(r.movePath,e);await Rf(c),await V.writeFile(c,a,`utf-8`),await V.rm(i,{force:!0,recursive:!1}),await zf(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Hf(o,s,`modified`,Lf(c,e))}else await V.writeFile(i,a,`utf-8`),await zf(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Hf(o,s,`modified`,Lf(i,e))}return{content:[{type:`text`,text:Bf(o)}],details:{summary:o}}}catch(e){if(bi(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Hf(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Uf(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Wf(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Gf(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Wf(e){let t=e[0]?.trim(),n=e[e.length-1]?.trim();if(t!==`*** Begin Patch`)throw Error(`The first line of the patch must be '*** Begin Patch'`);if(n!==`*** End Patch`)throw Error(`The last line of the patch must be '*** End Patch'`)}function Gf(e,t){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: empty hunk`);let n=e[0].trim();if(n.startsWith(`*** Add File: `)){let t=n.slice(14),r=``,i=1;for(let t of e.slice(1))if(t.startsWith(`+`))r+=`${t.slice(1)}\n`,i+=1;else break;return{hunk:{kind:`add`,path:t,contents:r},consumed:i}}if(n.startsWith(`*** Delete File: `))return{hunk:{kind:`delete`,path:n.slice(17)},consumed:1};if(n.startsWith(`*** Update File: `)){let r=n.slice(17),i=e.slice(1),a=1,o,s=i[0]?.trim();s?.startsWith(`*** Move to: `)&&(o=s.slice(13),i=i.slice(1),a+=1);let c=[];for(;i.length>0;){if(i[0].trim()===``){i=i.slice(1),a+=1;continue}if(i[0].startsWith(`***`))break;let{chunk:e,consumed:n}=Kf(i,t+a,c.length===0);c.push(e),i=i.slice(n),a+=n}if(c.length===0)throw Error(`Invalid patch hunk at line ${t}: Update file hunk for path '${r}' is empty`);return{hunk:{kind:`update`,path:r,movePath:o,chunks:c},consumed:a}}throw Error(`Invalid patch hunk at line ${t}: '${e[0]}' is not a valid hunk header.`)}function Kf(e,t,n){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: Update hunk does not contain any lines`);let r,i=0;if(e[0]===`@@`)i=1;else if(e[0].startsWith(`@@ `))r=e[0].slice(3),i=1;else if(!n)throw Error(`Invalid patch hunk at line ${t}: Expected update hunk to start with a @@ context marker.`);if(i>=e.length)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);let a={changeContext:r,oldLines:[],newLines:[],isEndOfFile:!1},o=0;for(let n of e.slice(i)){if(n===`*** End of File`){if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);a.isEndOfFile=!0,o+=1;break}let e=n[0];if(!e){a.oldLines.push(``),a.newLines.push(``),o+=1;continue}if(e===` `){let e=n.slice(1);a.oldLines.push(e),a.newLines.push(e),o+=1;continue}if(e===`+`){a.newLines.push(n.slice(1)),o+=1;continue}if(e===`-`){a.oldLines.push(n.slice(1)),o+=1;continue}if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Unexpected line found in update hunk.`);break}return{chunk:a,consumed:o+i}}async function qf(e,t){let n=(await V.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
71
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Yf(n,Jf(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
72
- `)}function Jf(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Xf(e,[a.changeContext],i,!1);if(n===null)throw Error(`Failed to find context '${a.changeContext}' in ${t}`);i=n+1}if(a.oldLines.length===0){let t=e.length>0&&e[e.length-1]===``?e.length-1:e.length;r.push([t,0,a.newLines]);continue}let n=a.oldLines,o=a.newLines,s=Xf(e,n,i,a.isEndOfFile);if(s===null&&n[n.length-1]===``&&(n=n.slice(0,-1),o.length>0&&o[o.length-1]===``&&(o=o.slice(0,-1)),s=Xf(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
73
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Yf(e,t){let n=[...e];for(let[e,r,i]of[...t].toReversed()){for(let t=0;t<r;t+=1)e<n.length&&n.splice(e,1);for(let t=0;t<i.length;t+=1)n.splice(e+t,0,i[t])}return n}function Xf(e,t,n,r){if(t.length===0)return n;if(t.length>e.length)return null;let i=e.length-t.length,a=r&&e.length>=t.length?i:n;if(a>i)return null;for(let n=a;n<=i;n+=1)if(Zf(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Zf(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Zf(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Zf(e,t,n,e=>Qf(e.trim())))return n;return null}function Zf(e,t,n,r){for(let i=0;i<t.length;i+=1)if(r(e[n+i])!==r(t[i]))return!1;return!0}function Qf(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}function $f(e){return H.join(e,`.aimax`)}function ep(e){return H.join($f(e),`MEMORY.md`)}async function $(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function tp(e,t){let n=$f(e),r=me({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?{provider:r.provider,resolvedProviderId:r.registration.id,source:`plugin`}:{provider:le({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function np(e){return pe($f(e))}async function rp(e){try{return await V.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ip(e){return rp(ep(e))}async function ap(e,t,n){let{provider:r}=tp(e,n);return await r.search(t)}async function op(e,t,n,r,i){try{let{provider:a}=tp(e,i);return await a.getLines(t,n,r)}catch{return null}}async function sp(e,t,n){let{provider:r,resolvedProviderId:i}=tp(e,n);await r.append(t),await $(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}async function cp(e,t,n,r){let{provider:i,resolvedProviderId:a}=tp(e,r),o=n===`session`&&r?.sessionId?`session-${r.sessionId}.md`:`${new Date().toISOString().slice(0,10)}.md`;if(i.appendRecent){await i.appendRecent(t,n),await $(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await $(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});return}await $(i,r?.onMemoryChanged,{reason:`appendRecent_fallback`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});let s=new Date().toISOString().slice(0,10),c=n===`session`&&r?.sessionId?`[session:${r.sessionId}]`:`[${s}]`;await i.append(`${c} ${t}\n`),await $(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await $(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function lp(e,t,n,r){let{provider:i,resolvedProviderId:a}=tp(e,r);await i.updateFile(t,n),await $(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function up(e,t,n){let{provider:r,resolvedProviderId:i}=tp(e,n);await r.deleteFile(t),await $(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const dp=W.Object({query:W.String({description:`Search query (case-insensitive substring match)`})});function fp(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search durable long-term memory docs (for stable facts, preferences, decisions, and project constraints). Use this for persistent knowledge retrieval, not for reconstructing past chat timelines. If the user asks what happened in previous sessions, use session_search instead.`,parameters:dp,async execute(n,r){let i=(await ap(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({id:e.id,file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.id?`[${e.id}] `:``}${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
74
- `)}],details:{matches:i}}}}}const pp=W.Object({file:W.String({description:`Memory file path (from memory_search results)`}),start_line:W.Number({description:`Start line number (1-based)`}),end_line:W.Number({description:`End line number (1-based)`})});function mp(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read a specific memory entry's content after memory_search identifies the target path and range`,parameters:pp,async execute(n,r){let i=await op(e,r.file,r.start_line,r.end_line,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});return i===null?{content:[{type:`text`,text:`File not found: ${r.file}`}],details:{lines:null}}:{content:[{type:`text`,text:i.map((e,t)=>`${(r.start_line+t).toString().padStart(4)} ${e}`).join(`
75
- `)||`(empty)`}],details:{lines:i}}}}}const hp=W.Object({content:W.String({description:`Content to write to memory`})});function gp(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append a small new fact or note to MEMORY.md without replacing existing sections`,parameters:hp,async execute(n,r){try{return await sp(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{appended:!0}}}catch(e){return{content:[{type:`text`,text:`Error appending to memory: ${e instanceof Error?e.message:String(e)}`}],details:{appended:!1}}}}}}const _p=W.Object({section:W.Optional(W.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:W.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:W.Union([W.Literal(`append`),W.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function vp(e,t){return{name:`memory_write`,label:`Write Memory`,description:`Write or update a section in long-term memory (MEMORY.md). Use for durable facts, preferences, decisions, and project constraints. If section is omitted, appends a flat unstructured note. Use mode "append" to add entries and "replace" to rewrite a section.`,parameters:_p,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await sp(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}let o=`${`## ${i}`}\n${r.content.trimEnd()}\n`;try{return a===`replace`?await lp(e,`MEMORY.md`,yp(await ip(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await sp(e,o,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: section "${i}" (${a})`}],details:{section:i,mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}}}}function yp(e,t,n){let r=e.split(`
68
+ `),lines:d.length,truncated:f}}}}}const Mf=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),content:W.String({description:`File content to write`})});function Nf(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Mf,async execute(r,i){let a;try{a=kf(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await V.mkdir(H.dirname(a),{recursive:!0}),await V.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await Of(n,{type:`write`,operation:`write_file`,file:a,content:i.content,toolCallId:r,toolName:`write_file`})}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:a}}}return{content:[{type:`text`,text:`File written: ${i.path}`}],details:{path:a}}}}}const Pf=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),old_string:W.String({description:`Exact text to replace`}),new_string:W.String({description:`Replacement text`})});function Ff(e,t,n){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Pf,async execute(r,i){let a;try{a=kf(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await V.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await V.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await Of(n,{type:`edit`,operation:`edit_file`,file:a,content:s,toolCallId:r,toolName:`edit_file`}),{content:[{type:`text`,text:`File edited: ${i.path}`}],details:{path:a,occurrences:1}}}}}const If=W.Object({path:W.Optional(W.String({description:`Directory path (default: workspace root)`}))});function Lf(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:If,async execute(t,n){let r=n.path??`.`,i;try{i=kf(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await V.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
69
+ `)||`(empty directory)`}],details:{entries:a}}}}}const Rf=W.Object({input:W.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function zf(e,t){let n=H.isAbsolute(e)?H.normalize(e):H.normalize(H.join(t,e));if(!n.startsWith(t+H.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Bf(e,t){let n=H.relative(t,e);return!n||n===``?H.basename(e):n.startsWith(`..`)||H.isAbsolute(n)?e:n}async function Vf(e){await V.mkdir(H.dirname(e),{recursive:!0})}async function Hf(e,t){e&&await e(t).catch(()=>{})}function Uf(e){let t=[`Success. Updated the following files:`];for(let n of e.added)t.push(`A ${n}`);for(let n of e.modified)t.push(`M ${n}`);for(let n of e.deleted)t.push(`D ${n}`);return t.join(`
70
+ `)}function Wf(e,t={}){return{name:`apply_patch`,label:`apply_patch`,description:`Apply a patch to one or more files using the apply_patch format. The input should include *** Begin Patch and *** End Patch markers.`,parameters:Rf,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=Kf(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let r of a.hunks){if(r.kind===`add`){let i=zf(r.path,e);await Vf(i),await V.writeFile(i,r.contents,`utf-8`),await Hf(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Gf(o,s,`added`,Bf(i,e));continue}if(r.kind===`delete`){let i=zf(r.path,e);await V.rm(i,{force:!0,recursive:!1}),await Hf(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Gf(o,s,`deleted`,Bf(i,e));continue}let i=zf(r.path,e),a=await Xf(i,r.chunks);if(r.movePath){let c=zf(r.movePath,e);await Vf(c),await V.writeFile(c,a,`utf-8`),await V.rm(i,{force:!0,recursive:!1}),await Hf(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Gf(o,s,`modified`,Bf(c,e))}else await V.writeFile(i,a,`utf-8`),await Hf(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Gf(o,s,`modified`,Bf(i,e))}return{content:[{type:`text`,text:Uf(o)}],details:{summary:o}}}catch(e){if(bi(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Gf(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Kf(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);qf(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Jf(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function qf(e){let t=e[0]?.trim(),n=e[e.length-1]?.trim();if(t!==`*** Begin Patch`)throw Error(`The first line of the patch must be '*** Begin Patch'`);if(n!==`*** End Patch`)throw Error(`The last line of the patch must be '*** End Patch'`)}function Jf(e,t){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: empty hunk`);let n=e[0].trim();if(n.startsWith(`*** Add File: `)){let t=n.slice(14),r=``,i=1;for(let t of e.slice(1))if(t.startsWith(`+`))r+=`${t.slice(1)}\n`,i+=1;else break;return{hunk:{kind:`add`,path:t,contents:r},consumed:i}}if(n.startsWith(`*** Delete File: `))return{hunk:{kind:`delete`,path:n.slice(17)},consumed:1};if(n.startsWith(`*** Update File: `)){let r=n.slice(17),i=e.slice(1),a=1,o,s=i[0]?.trim();s?.startsWith(`*** Move to: `)&&(o=s.slice(13),i=i.slice(1),a+=1);let c=[];for(;i.length>0;){if(i[0].trim()===``){i=i.slice(1),a+=1;continue}if(i[0].startsWith(`***`))break;let{chunk:e,consumed:n}=Yf(i,t+a,c.length===0);c.push(e),i=i.slice(n),a+=n}if(c.length===0)throw Error(`Invalid patch hunk at line ${t}: Update file hunk for path '${r}' is empty`);return{hunk:{kind:`update`,path:r,movePath:o,chunks:c},consumed:a}}throw Error(`Invalid patch hunk at line ${t}: '${e[0]}' is not a valid hunk header.`)}function Yf(e,t,n){if(e.length===0)throw Error(`Invalid patch hunk at line ${t}: Update hunk does not contain any lines`);let r,i=0;if(e[0]===`@@`)i=1;else if(e[0].startsWith(`@@ `))r=e[0].slice(3),i=1;else if(!n)throw Error(`Invalid patch hunk at line ${t}: Expected update hunk to start with a @@ context marker.`);if(i>=e.length)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);let a={changeContext:r,oldLines:[],newLines:[],isEndOfFile:!1},o=0;for(let n of e.slice(i)){if(n===`*** End of File`){if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Update hunk does not contain any lines`);a.isEndOfFile=!0,o+=1;break}let e=n[0];if(!e){a.oldLines.push(``),a.newLines.push(``),o+=1;continue}if(e===` `){let e=n.slice(1);a.oldLines.push(e),a.newLines.push(e),o+=1;continue}if(e===`+`){a.newLines.push(n.slice(1)),o+=1;continue}if(e===`-`){a.oldLines.push(n.slice(1)),o+=1;continue}if(o===0)throw Error(`Invalid patch hunk at line ${t+1}: Unexpected line found in update hunk.`);break}return{chunk:a,consumed:o+i}}async function Xf(e,t){let n=(await V.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
71
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Qf(n,Zf(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
72
+ `)}function Zf(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=$f(e,[a.changeContext],i,!1);if(n===null)throw Error(`Failed to find context '${a.changeContext}' in ${t}`);i=n+1}if(a.oldLines.length===0){let t=e.length>0&&e[e.length-1]===``?e.length-1:e.length;r.push([t,0,a.newLines]);continue}let n=a.oldLines,o=a.newLines,s=$f(e,n,i,a.isEndOfFile);if(s===null&&n[n.length-1]===``&&(n=n.slice(0,-1),o.length>0&&o[o.length-1]===``&&(o=o.slice(0,-1)),s=$f(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
73
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Qf(e,t){let n=[...e];for(let[e,r,i]of[...t].toReversed()){for(let t=0;t<r;t+=1)e<n.length&&n.splice(e,1);for(let t=0;t<i.length;t+=1)n.splice(e+t,0,i[t])}return n}function $f(e,t,n,r){if(t.length===0)return n;if(t.length>e.length)return null;let i=e.length-t.length,a=r&&e.length>=t.length?i:n;if(a>i)return null;for(let n=a;n<=i;n+=1)if(ep(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(ep(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(ep(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(ep(e,t,n,e=>tp(e.trim())))return n;return null}function ep(e,t,n,r){for(let i=0;i<t.length;i+=1)if(r(e[n+i])!==r(t[i]))return!1;return!0}function tp(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}function np(e){return H.join(e,`.aimax`)}function rp(e){return H.join(np(e),`MEMORY.md`)}async function $(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function ip(e,t){let n=np(e),r=me({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?{provider:r.provider,resolvedProviderId:r.registration.id,source:`plugin`}:{provider:le({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function ap(e){return pe(np(e))}async function op(e){try{return await V.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function sp(e){return op(rp(e))}async function cp(e,t,n){let{provider:r}=ip(e,n);return await r.search(t)}async function lp(e,t,n,r,i){try{let{provider:a}=ip(e,i);return await a.getLines(t,n,r)}catch{return null}}async function up(e,t,n){let{provider:r,resolvedProviderId:i}=ip(e,n);await r.append(t),await $(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}async function dp(e,t,n,r){let{provider:i,resolvedProviderId:a}=ip(e,r),o=n===`session`&&r?.sessionId?`session-${r.sessionId}.md`:`${new Date().toISOString().slice(0,10)}.md`;if(i.appendRecent){await i.appendRecent(t,n),await $(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await $(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});return}await $(i,r?.onMemoryChanged,{reason:`appendRecent_fallback`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});let s=new Date().toISOString().slice(0,10),c=n===`session`&&r?.sessionId?`[session:${r.sessionId}]`:`[${s}]`;await i.append(`${c} ${t}\n`),await $(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await $(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function fp(e,t,n,r){let{provider:i,resolvedProviderId:a}=ip(e,r);await i.updateFile(t,n),await $(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function pp(e,t,n){let{provider:r,resolvedProviderId:i}=ip(e,n);await r.deleteFile(t),await $(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const mp=W.Object({query:W.String({description:`Search query (case-insensitive substring match)`})});function hp(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search durable long-term memory docs (for stable facts, preferences, decisions, and project constraints). Use this for persistent knowledge retrieval, not for reconstructing past chat timelines. If the user asks what happened in previous sessions, use session_search instead.`,parameters:mp,async execute(n,r){let i=(await cp(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({id:e.id,file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.id?`[${e.id}] `:``}${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
74
+ `)}],details:{matches:i}}}}}const gp=W.Object({file:W.String({description:`Memory file path (from memory_search results)`}),start_line:W.Number({description:`Start line number (1-based)`}),end_line:W.Number({description:`End line number (1-based)`})});function _p(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read a specific memory entry's content after memory_search identifies the target path and range`,parameters:gp,async execute(n,r){let i=await lp(e,r.file,r.start_line,r.end_line,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});return i===null?{content:[{type:`text`,text:`File not found: ${r.file}`}],details:{lines:null}}:{content:[{type:`text`,text:i.map((e,t)=>`${(r.start_line+t).toString().padStart(4)} ${e}`).join(`
75
+ `)||`(empty)`}],details:{lines:i}}}}}const vp=W.Object({content:W.String({description:`Content to write to memory`})});function yp(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append a small new fact or note to MEMORY.md without replacing existing sections`,parameters:vp,async execute(n,r){try{return await up(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{appended:!0}}}catch(e){return{content:[{type:`text`,text:`Error appending to memory: ${e instanceof Error?e.message:String(e)}`}],details:{appended:!1}}}}}}const bp=W.Object({section:W.Optional(W.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:W.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:W.Union([W.Literal(`append`),W.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function xp(e,t){return{name:`memory_write`,label:`Write Memory`,description:`Write or update a section in long-term memory (MEMORY.md). Use for durable facts, preferences, decisions, and project constraints. If section is omitted, appends a flat unstructured note. Use mode "append" to add entries and "replace" to rewrite a section.`,parameters:bp,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await up(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}let o=`${`## ${i}`}\n${r.content.trimEnd()}\n`;try{return a===`replace`?await fp(e,`MEMORY.md`,Sp(await sp(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await up(e,o,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: section "${i}" (${a})`}],details:{section:i,mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}}}}function Sp(e,t,n){let r=e.split(`
76
76
  `),i=`## ${t}`,a=`${i}\n${n.trimEnd()}`.trimEnd(),o=-1;for(let e=0;e<r.length;e+=1)if(r[e]?.trim()===i){o=e;break}if(o===-1){let t=e.trimEnd();return`${t?`${t}\n`:``}${a}\n`}let s=r.length;for(let e=o+1;e<r.length;e+=1)if(/^##\s+/.test(r[e]??``)){s=e;break}return`${[r.slice(0,o).join(`
77
77
  `).trimEnd(),a,r.slice(s).join(`
78
78
  `).trimStart()].filter(e=>e.length>0).join(`
79
- `)}\n`}function bp(e,t){let n=e.split(`
79
+ `)}\n`}function Cp(e,t){let n=e.split(`
80
80
  `),r=`## ${t}`,i=-1;for(let e=0;e<n.length;e+=1)if(n[e]?.trim()===r){i=e;break}if(i===-1)return null;let a=n.length;for(let e=i+1;e<n.length;e+=1)if(/^##\s+/.test(n[e]??``)){a=e;break}let o=[n.slice(0,i).join(`
81
81
  `).trimEnd(),n.slice(a).join(`
82
82
  `).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
83
- `)}\n`:``}function xp(e,t){let n=e.split(`
83
+ `)}\n`:``}function wp(e,t){let n=e.split(`
84
84
  `);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
85
- `)}\n`:``)}function Sp(e,t,n){let r=e.split(`
85
+ `)}\n`:``)}function Tp(e,t,n){let r=e.split(`
86
86
  `);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
87
- `)}\n`)}function Cp(e){let t=e.indexOf(`#`);if(t===-1)return{filePath:e};let n=e.slice(0,t),r=e.slice(t+1),i=r.match(/^L(\d+)$/);return i?{filePath:n,line:Number(i[1])}:{filePath:n,section:r}}function wp(e,t){let n=[],r=t.split(`
88
- `);for(let t of r){let r=t.match(/^##\s+(.+)$/);if(r?.[1]){let t=r[1].trim(),i=`${e}#${t}`;n.push({id:i,heading:t})}}if(n.length===0){let t=0;for(let i of r){t+=1;let r=i.trim();if(!r||r.startsWith(`---`)||r.startsWith(`# `))continue;let a=r.length>60?`${r.slice(0,57)}...`:r;if(n.push({id:`${e}#L${t}`,heading:a}),n.length>=20)break}}return n}const Tp=W.Object({content:W.String({description:`Note to append to today's daily log`}),scope:W.Optional(W.Union([W.Literal(`daily`),W.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Ep(e,t){return{name:`memory_log`,label:`Daily Log`,description:`Append a timestamped daily or session note for short-term context, progress updates, and open questions.`,parameters:Tp,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await cp(e,r.content,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Logged to ${a} memory: ${r.content}`}],details:{date:i,scope:a}}}catch(e){throw Error(`Failed to write daily log: ${e instanceof Error?e.message:String(e)}`)}}}}const Dp=W.Object({scope:W.Optional(W.Union([W.Literal(`long-term`),W.Literal(`recent`),W.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Op(e,t){return{name:`memory_list`,label:`List Memories`,description:`List stored memories so you can inspect available entries and obtain exact ids or paths before update/delete.`,parameters:Dp,async execute(n,r){try{let n=r.scope??`all`,i=await np(e),a=[];for(let n of i.slice(0,30)){let r=await op(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
89
- `),t=wp(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
87
+ `)}\n`)}function Ep(e){let t=e.indexOf(`#`);if(t===-1)return{filePath:e};let n=e.slice(0,t),r=e.slice(t+1),i=r.match(/^L(\d+)$/);return i?{filePath:n,line:Number(i[1])}:{filePath:n,section:r}}function Dp(e,t){let n=[],r=t.split(`
88
+ `);for(let t of r){let r=t.match(/^##\s+(.+)$/);if(r?.[1]){let t=r[1].trim(),i=`${e}#${t}`;n.push({id:i,heading:t})}}if(n.length===0){let t=0;for(let i of r){t+=1;let r=i.trim();if(!r||r.startsWith(`---`)||r.startsWith(`# `))continue;let a=r.length>60?`${r.slice(0,57)}...`:r;if(n.push({id:`${e}#L${t}`,heading:a}),n.length>=20)break}}return n}const Op=W.Object({content:W.String({description:`Note to append to today's daily log`}),scope:W.Optional(W.Union([W.Literal(`daily`),W.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function kp(e,t){return{name:`memory_log`,label:`Daily Log`,description:`Append a timestamped daily or session note for short-term context, progress updates, and open questions.`,parameters:Op,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await dp(e,r.content,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Logged to ${a} memory: ${r.content}`}],details:{date:i,scope:a}}}catch(e){throw Error(`Failed to write daily log: ${e instanceof Error?e.message:String(e)}`)}}}}const Ap=W.Object({scope:W.Optional(W.Union([W.Literal(`long-term`),W.Literal(`recent`),W.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function jp(e,t){return{name:`memory_list`,label:`List Memories`,description:`List stored memories so you can inspect available entries and obtain exact ids or paths before update/delete.`,parameters:Ap,async execute(n,r){try{let n=r.scope??`all`,i=await ap(e),a=[];for(let n of i.slice(0,30)){let r=await lp(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
89
+ `),t=Dp(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
90
90
  `):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
91
91
 
92
- `)||`(no memories)`}],details:{count:a.length,scope:n,files:a}}}catch(e){throw Error(`Failed to list memories: ${e instanceof Error?e.message:String(e)}`)}}}}const kp=W.Object({id:W.Optional(W.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:W.Optional(W.String({description:`Search query used to find memories to delete`})),limit:W.Optional(W.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:W.Optional(W.Union([W.Literal(`long-term`),W.Literal(`recent`),W.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Ap(e,t){return{name:`memory_forget`,label:`Forget Memory`,description:`Delete a specific memory by its entry ID, or delete matching memories by search query. IDs with # (e.g. MEMORY.md#Preferences) delete only that section from the file. Prefer memory_list or memory_search first so you know the target.`,parameters:kp,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Cp(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=bp(await ip(e)??``,t.section);return n===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await lp(e,t.filePath,n,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}let n=await op(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=bp(n.join(`
93
- `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await lp(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}if(t.line!==void 0){let n=await op(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=xp(n.join(`
94
- `),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await lp(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten line ${t.line} from ${t.filePath}`}],details:{removed:1,id:r.id}})}return r.id===`MEMORY.md`?{content:[{type:`text`,text:`Cannot delete MEMORY.md directly. Use id with a section (e.g. MEMORY.md#SectionName) to remove individual entries, or use query mode.`}],details:{removed:0,id:r.id}}:(await up(e,r.id,i),{content:[{type:`text`,text:`Forgotten memory: ${r.id}`}],details:{removed:1,id:r.id}})}if(r.query){let t=Math.min(Math.max(r.limit??5,1),20),n=await ap(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await up(e,r.path,i),a+=1);return{content:[{type:`text`,text:`Forgotten ${a} memor${a===1?`y`:`ies`} matching: ${r.query}`}],details:{removed:a,query:r.query}}}return{content:[{type:`text`,text:`Provide id or query to forget memories.`}],details:{removed:0}}}catch(e){throw Error(`Failed to forget memory: ${e instanceof Error?e.message:String(e)}`)}}}}const jp=W.Object({id:W.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:W.String({description:`New content to replace the existing memory with`})});function Mp(e,t){return{name:`memory_update`,label:`Update Memory`,description:`Replace an existing memory's content by its entry ID. Use memory_list or memory_search first to find the correct ID. IDs with # (e.g. MEMORY.md#Preferences) update only that section; IDs without # replace the entire file.`,parameters:jp,async execute(n,r){try{let n=Cp(r.id);if(n.section){let i=yp(await ip(e)??``,n.section,r.content);return await lp(e,n.filePath,i,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (section "${n.section}")`}],details:{id:r.id}}}if(n.line!==void 0){let i=await op(e,n.filePath,1,1e4,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(!i)throw Error(`File not found: ${n.filePath}`);let a=Sp(i.join(`
95
- `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await lp(e,n.filePath,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (line ${n.line})`}],details:{id:r.id}}}return await lp(e,r.id,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id}`}],details:{id:r.id}}}catch(e){throw Error(`Failed to update memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Np=W.Object({query:W.Optional(W.String({description:`Search query; omit to browse recent sessions.`})),role_filter:W.Optional(W.Union([W.Literal(`user`),W.Literal(`assistant`),W.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:W.Optional(W.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:W.Optional(W.Union([W.Literal(`llm`),W.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Pp(e,t){return{name:`session_search`,label:`Session Search`,description:`Search past conversation transcripts across sessions for cross-session recall. Use when the user asks about what was discussed, decided, or done in previous chats (e.g. last time, before, remember when). Omit query to browse recent sessions with zero LLM cost; include query to search transcripts and return summaries. Do not use this as the only source for stable project policy/config if long-term memory docs exist (use memory_search for durable docs).`,parameters:Np,async execute(n,r){let i=Fp(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Ip(e,i,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let c=await Lp({dataDir:e,query:o,roleFilter:s,messageLimit:50,sessionLimit:i,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(c.length===0){let e={mode:`query`,query:o,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let l=[];for(let n of c){let r=Xp(o,n.snippets);if(a===`off`){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let i=await Gc({entries:qp(Kp(await m(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Yp({query:o})});l.push({session_id:n.sessionId,summary:i.trim()||r,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let u={mode:`query`,query:o,count:l.length,results:l};return{content:[{type:`text`,text:JSON.stringify(u,null,2)}],details:u}}}}function Fp(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Ip(e,t,n){let r=await y(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await P(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function Lp(e){let t=e.messageLimit??50,n=(await y(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Vp(e.query),i=(await Zp(n,6,async t=>Rp({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Gp).slice(0,t);if(i.length===0)return[];let a=new Map;for(let e of i){let t=a.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),a.set(e.sessionId,t)}let o=Array.from(a.values());for(let t of o){let n=await P(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return o.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),o.slice(0,e.sessionLimit)}async function Rp(t){let n=await l(e(t.dataDir,t.sessionId,{storeName:t.storeName}));if(n===null)return[];let r=[],i=n.split(`
96
- `);for(let e of i){let n=e.trim();if(!n||!zp(n,t.terms))continue;let i;try{i=JSON.parse(n)}catch{continue}if(!Bp(i.role)||t.roleFilter&&i.role!==t.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Up(i.content,t.terms,i.role);if(a<=0)continue;let o=Wp(i.content);r.push({sessionId:t.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),r.length>20&&(r.sort(Gp),r.length=20)}return r.sort(Gp),r}function zp(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Bp(e){return e===`user`||e===`assistant`||e===`tool_result`}function Vp(e){let t=e.toLowerCase().trim(),n=new Set;t.length>0&&n.add(t);let r=t.match(/[\p{L}\p{N}_-]+/gu)??[];for(let e of r)e.length>=2&&n.add(e);let i=Array.from(t).filter(e=>Hp(e)).join(``);if(i.length>=2)for(let e=0;e<=i.length-2;e+=1)n.add(i.slice(e,e+2));return Array.from(n).slice(0,30)}function Hp(e){let t=e.codePointAt(0)??0;return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=12352&&t<=12543||t>=44032&&t<=55215}function Up(e,t,n){let r=e.toLowerCase(),i=0;for(let e of t)e&&r.includes(e)&&(i+=1);if(i===0)return 0;let a=n===`user`?1.2:n===`assistant`?1:.7;return i*i*a}function Wp(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Gp(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Kp(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function qp(e,t,n){if(e.length===0)return e;let r=Vp(t);if(e.reduce((e,t)=>e+t.content.length,0)<=n)return e;let i=[];for(let t=0;t<e.length;t+=1){let n=e[t].content.toLowerCase();r.some(e=>e&&n.includes(e))&&i.push(t)}if(i.length===0)return Jp(e,n);let a=i[0],o=i[0],s=e[a].content.length;for(;s<n&&(a>0||o<e.length-1);){if(o<e.length-1){let t=e[o+1].content.length;if(s+t<=n)o+=1,s+=t;else break}if(a>0){let t=e[a-1].content.length;if(s+t<=n)--a,s+=t;else break}}return e.slice(a,o+1)}function Jp(e,t){let n=[],r=0;for(let i=e.length-1;i>=0;--i){let a=e[i];if(r+a.content.length>t)break;n.push(a),r+=a.content.length}return n.reverse()}function Yp(e){let t=e.languageHint?.trim(),n=[`Summarize this past session for retrieval use.`,`Focus query: ${e.query}`,`Prioritize: final outcome, key actions, concrete evidence (files/commands/ids), unresolved items.`,`Do not invent facts. If evidence is missing, say so explicitly.`,`Keep it concise and factual.`];return t&&n.push(`Respond in: ${t}`),n.join(`
97
- `)}function Xp(e,t){return t.length===0?`No direct transcript snippet was extracted for query: ${e}`:`Extractive summary for "${e}":\n${t.slice(0,3).map((e,t)=>`${t+1}. ${e}`).join(`
98
- `)}`}async function Zp(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}function Qp(e){return H.join(e,`.aimax`,`skills`)}function $p(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function em(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${$p(n)}\n`)}function tm(e){let t=$e(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
99
- `);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}function nm(e){let t=$e(e),n=t.data.metadata,r=(n&&typeof n==`object`&&!Array.isArray(n)?n.version:void 0)??t.data.version;return r==null?``:String(r).trim()}async function rm(e){return(await V.stat(e)).mtime.toISOString()}async function im(e){return om([Qp(e)])}async function am(e,t,n=[]){return om([...n,...t,Qp(e)])}async function om(e){let t=new Map;for(let n of e){let e;try{e=await V.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=H.join(n,e,`SKILL.md`),i;try{i=await V.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=tm(i),o=nm(i),s=await rm(r)}catch(t){em(e,r,t);continue}t.set(e,{name:e,description:a,location:r,version:o,skillFileMtime:s})}}return Array.from(t.values()).slice(0,50)}async function sm(e,t){let n=t.trim();if(!n)return;let r=(await om(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:H.dirname(r.location)}}async function cm(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=H.resolve(r),a=H.basename(i)===`SKILL.md`?i:H.join(i,`SKILL.md`);if(H.basename(a)!==`SKILL.md`)return;let o;try{o=await V.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=tm(o),c=nm(o),l=await rm(a)}catch(e){em(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:H.dirname(a)}}async function lm(e,t,n){let r=n?.trim()?await cm(t,n):await sm(e,t);if(!r)return;let i=await V.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function um(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
92
+ `)||`(no memories)`}],details:{count:a.length,scope:n,files:a}}}catch(e){throw Error(`Failed to list memories: ${e instanceof Error?e.message:String(e)}`)}}}}const Mp=W.Object({id:W.Optional(W.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:W.Optional(W.String({description:`Search query used to find memories to delete`})),limit:W.Optional(W.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:W.Optional(W.Union([W.Literal(`long-term`),W.Literal(`recent`),W.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Np(e,t){return{name:`memory_forget`,label:`Forget Memory`,description:`Delete a specific memory by its entry ID, or delete matching memories by search query. IDs with # (e.g. MEMORY.md#Preferences) delete only that section from the file. Prefer memory_list or memory_search first so you know the target.`,parameters:Mp,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Ep(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Cp(await sp(e)??``,t.section);return n===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await fp(e,t.filePath,n,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}let n=await lp(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=Cp(n.join(`
93
+ `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await fp(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}if(t.line!==void 0){let n=await lp(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=wp(n.join(`
94
+ `),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await fp(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten line ${t.line} from ${t.filePath}`}],details:{removed:1,id:r.id}})}return r.id===`MEMORY.md`?{content:[{type:`text`,text:`Cannot delete MEMORY.md directly. Use id with a section (e.g. MEMORY.md#SectionName) to remove individual entries, or use query mode.`}],details:{removed:0,id:r.id}}:(await pp(e,r.id,i),{content:[{type:`text`,text:`Forgotten memory: ${r.id}`}],details:{removed:1,id:r.id}})}if(r.query){let t=Math.min(Math.max(r.limit??5,1),20),n=await cp(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await pp(e,r.path,i),a+=1);return{content:[{type:`text`,text:`Forgotten ${a} memor${a===1?`y`:`ies`} matching: ${r.query}`}],details:{removed:a,query:r.query}}}return{content:[{type:`text`,text:`Provide id or query to forget memories.`}],details:{removed:0}}}catch(e){throw Error(`Failed to forget memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Pp=W.Object({id:W.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:W.String({description:`New content to replace the existing memory with`})});function Fp(e,t){return{name:`memory_update`,label:`Update Memory`,description:`Replace an existing memory's content by its entry ID. Use memory_list or memory_search first to find the correct ID. IDs with # (e.g. MEMORY.md#Preferences) update only that section; IDs without # replace the entire file.`,parameters:Pp,async execute(n,r){try{let n=Ep(r.id);if(n.section){let i=Sp(await sp(e)??``,n.section,r.content);return await fp(e,n.filePath,i,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (section "${n.section}")`}],details:{id:r.id}}}if(n.line!==void 0){let i=await lp(e,n.filePath,1,1e4,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(!i)throw Error(`File not found: ${n.filePath}`);let a=Tp(i.join(`
95
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await fp(e,n.filePath,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (line ${n.line})`}],details:{id:r.id}}}return await fp(e,r.id,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id}`}],details:{id:r.id}}}catch(e){throw Error(`Failed to update memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Ip=W.Object({query:W.Optional(W.String({description:`Search query; omit to browse recent sessions.`})),role_filter:W.Optional(W.Union([W.Literal(`user`),W.Literal(`assistant`),W.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:W.Optional(W.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:W.Optional(W.Union([W.Literal(`llm`),W.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Lp(e,t){return{name:`session_search`,label:`Session Search`,description:`Search past conversation transcripts across sessions for cross-session recall. Use when the user asks about what was discussed, decided, or done in previous chats (e.g. last time, before, remember when). Omit query to browse recent sessions with zero LLM cost; include query to search transcripts and return summaries. Do not use this as the only source for stable project policy/config if long-term memory docs exist (use memory_search for durable docs).`,parameters:Ip,async execute(n,r){let i=Rp(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await zp(e,i,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let c=await Bp({dataDir:e,query:o,roleFilter:s,messageLimit:50,sessionLimit:i,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(c.length===0){let e={mode:`query`,query:o,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let l=[];for(let n of c){let r=$p(o,n.snippets);if(a===`off`){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let i=await Gc({entries:Xp(Yp(await m(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Qp({query:o})});l.push({session_id:n.sessionId,summary:i.trim()||r,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let u={mode:`query`,query:o,count:l.length,results:l};return{content:[{type:`text`,text:JSON.stringify(u,null,2)}],details:u}}}}function Rp(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function zp(e,t,n){let r=await y(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await P(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function Bp(e){let t=e.messageLimit??50,n=(await y(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Wp(e.query),i=(await em(n,6,async t=>Vp({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Jp).slice(0,t);if(i.length===0)return[];let a=new Map;for(let e of i){let t=a.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),a.set(e.sessionId,t)}let o=Array.from(a.values());for(let t of o){let n=await P(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return o.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),o.slice(0,e.sessionLimit)}async function Vp(t){let n=await l(e(t.dataDir,t.sessionId,{storeName:t.storeName}));if(n===null)return[];let r=[],i=n.split(`
96
+ `);for(let e of i){let n=e.trim();if(!n||!Hp(n,t.terms))continue;let i;try{i=JSON.parse(n)}catch{continue}if(!Up(i.role)||t.roleFilter&&i.role!==t.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Kp(i.content,t.terms,i.role);if(a<=0)continue;let o=qp(i.content);r.push({sessionId:t.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),r.length>20&&(r.sort(Jp),r.length=20)}return r.sort(Jp),r}function Hp(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Up(e){return e===`user`||e===`assistant`||e===`tool_result`}function Wp(e){let t=e.toLowerCase().trim(),n=new Set;t.length>0&&n.add(t);let r=t.match(/[\p{L}\p{N}_-]+/gu)??[];for(let e of r)e.length>=2&&n.add(e);let i=Array.from(t).filter(e=>Gp(e)).join(``);if(i.length>=2)for(let e=0;e<=i.length-2;e+=1)n.add(i.slice(e,e+2));return Array.from(n).slice(0,30)}function Gp(e){let t=e.codePointAt(0)??0;return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=12352&&t<=12543||t>=44032&&t<=55215}function Kp(e,t,n){let r=e.toLowerCase(),i=0;for(let e of t)e&&r.includes(e)&&(i+=1);if(i===0)return 0;let a=n===`user`?1.2:n===`assistant`?1:.7;return i*i*a}function qp(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Jp(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Yp(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function Xp(e,t,n){if(e.length===0)return e;let r=Wp(t);if(e.reduce((e,t)=>e+t.content.length,0)<=n)return e;let i=[];for(let t=0;t<e.length;t+=1){let n=e[t].content.toLowerCase();r.some(e=>e&&n.includes(e))&&i.push(t)}if(i.length===0)return Zp(e,n);let a=i[0],o=i[0],s=e[a].content.length;for(;s<n&&(a>0||o<e.length-1);){if(o<e.length-1){let t=e[o+1].content.length;if(s+t<=n)o+=1,s+=t;else break}if(a>0){let t=e[a-1].content.length;if(s+t<=n)--a,s+=t;else break}}return e.slice(a,o+1)}function Zp(e,t){let n=[],r=0;for(let i=e.length-1;i>=0;--i){let a=e[i];if(r+a.content.length>t)break;n.push(a),r+=a.content.length}return n.reverse()}function Qp(e){let t=e.languageHint?.trim(),n=[`Summarize this past session for retrieval use.`,`Focus query: ${e.query}`,`Prioritize: final outcome, key actions, concrete evidence (files/commands/ids), unresolved items.`,`Do not invent facts. If evidence is missing, say so explicitly.`,`Keep it concise and factual.`];return t&&n.push(`Respond in: ${t}`),n.join(`
97
+ `)}function $p(e,t){return t.length===0?`No direct transcript snippet was extracted for query: ${e}`:`Extractive summary for "${e}":\n${t.slice(0,3).map((e,t)=>`${t+1}. ${e}`).join(`
98
+ `)}`}async function em(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}function tm(e){return H.join(e,`.aimax`,`skills`)}function nm(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function rm(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${nm(n)}\n`)}function im(e){let t=$e(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
99
+ `);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}function am(e){let t=$e(e),n=t.data.metadata,r=(n&&typeof n==`object`&&!Array.isArray(n)?n.version:void 0)??t.data.version;return r==null?``:String(r).trim()}async function om(e){return(await V.stat(e)).mtime.toISOString()}async function sm(e){return lm([tm(e)])}async function cm(e,t,n=[]){return lm([...n,...t,tm(e)])}async function lm(e){let t=new Map;for(let n of e){let e;try{e=await V.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=H.join(n,e,`SKILL.md`),i;try{i=await V.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=im(i),o=am(i),s=await om(r)}catch(t){rm(e,r,t);continue}t.set(e,{name:e,description:a,location:r,version:o,skillFileMtime:s})}}return Array.from(t.values()).slice(0,50)}async function um(e,t){let n=t.trim();if(!n)return;let r=(await lm(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:H.dirname(r.location)}}async function dm(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=H.resolve(r),a=H.basename(i)===`SKILL.md`?i:H.join(i,`SKILL.md`);if(H.basename(a)!==`SKILL.md`)return;let o;try{o=await V.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=im(o),c=am(o),l=await om(a)}catch(e){rm(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:H.dirname(a)}}async function fm(e,t,n){let r=n?.trim()?await dm(t,n):await um(e,t);if(!r)return;let i=await V.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function pm(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
100
100
  `)).join(`
101
- `)}\n</available_skills>`}const dm=W.Object({category:W.Optional(W.String({description:`Reserved category filter field. Not used yet.`}))}),fm=W.Object({name:W.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:W.Optional(W.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function pm(e,t,n=[]){return[...n,...t,Qp(e)]}function mm(e,t,n=[]){let r=pm(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:dm,async execute(e,t){let n=await om(r),i={skills:n.map(e=>({name:e.name,description:e.description})),count:n.length};return{content:[{type:`text`,text:JSON.stringify({success:!0,...i,hint:`Use skill_load(name) to load the skill's SKILL.md entrypoint.`})}],details:i}}}}function hm(e){let t=pm(e.dataDir,e.pluginDirs,e.skillsLoadPaths),n=new Set;return{name:`skill_load`,label:`Skill Load`,description:`Load a skill's SKILL.md entrypoint. Optionally override lookup with skillPath.`,parameters:fm,async execute(r,i){let a=await lm(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``,version:``,skillFileMtime:``}}}}}const gm=W.Object({});function _m(e,t,n){return{name:`get_goal`,label:`Get Goal`,description:`Get the current thread goal, including status, budget, token and time usage, and remaining token budget. Returns null when no goal is set.`,parameters:gm,async execute(r,i){let a=await z(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null})}],details:{}};let o=await B(e,t,a,{storeName:n}),s={goal:{...a,objective:o,remainingTokens:a.tokenBudget===null?void 0:Math.max(0,a.tokenBudget-a.tokensUsed)}};return{content:[{type:`text`,text:JSON.stringify(s,null,2)}],details:{}}}}}const vm=W.Object({status:W.String({description:`Status to set. Only 'complete' is allowed.`})});function ym(e,t,n,r,i=t){return{name:`update_goal`,label:`Update Goal`,description:`Update the existing goal. Only supports marking the goal as complete. Use this only when the objective has actually been achieved and no required work remains. Do not mark a goal complete merely because its budget is nearly exhausted or because you are stopping work.`,parameters:vm,async execute(a,o){if(o.status!==`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Invalid status: "${o.status}". Only "complete" is allowed via this tool.`},null,2)}],details:{}};let s=await z(e,t,{storeName:n});if(!s)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`No active goal exists for this session. Use the CLI to set a goal first.`},null,2)}],details:{}};if(s.status===`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:s},null,2)}],details:{}};let c=await I(e,t,{status:`complete`},{storeName:n,eventSource:`tool`});if(!c)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Failed to update goal.`},null,2)}],details:{}};r&&await pl(r,i,{before:s,after:c,action:`completed`});let l={goal:{...c,remainingTokens:c.tokenBudget===null?void 0:Math.max(0,c.tokenBudget-c.tokensUsed)}};return{content:[{type:`text`,text:JSON.stringify(l,null,2)}],details:{}}}}}const bm=W.Object({task:W.String({description:`The task description for the subagent to execute`}),label:W.Optional(W.String({description:`Optional short label to identify this subagent`})),agent:W.Optional(W.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),xm=W.Object({task:W.String({description:`The task description for the subagent to execute`}),label:W.Optional(W.String({description:`Optional short label to identify this subagent`})),agent:W.Optional(W.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),Sm=W.Object({tasks:W.Array(bm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Cm(e){let t=e.label?`"${e.label}"`:`task: ${We(e.task)}`;return e.status===`done`?`${t}\n\n${wm(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function wm(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}async function Tm(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(q.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:si(p)}),!p){let e={status:`error`,error:`task must not be empty`};return q.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return q.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Ze(),v=new AbortController,y=t,b=Mr(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return q.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await C(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return q.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}q.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let w=f({dataDir:s,sessionId:y,message:b?Rr(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,w),q.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await w,q.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let T=Cm({task:p,label:m,status:S.status,result:S.result,error:S.error});if(S.status===`done`){let e={status:`done`,childSessionId:y,runId:_,result:S.result??``};return q.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:T}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return q.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:T}],isError:!0,details:E}}function Em(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. `+(r===0?"IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. You MUST also use this tool when the user mentions '@<agent-name>' where <agent-name> matches a custom agent listed in the Custom Agents section — set the `agent` field to that exact name. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. ":`WARNING: You are already running as a subagent (depth ${r}). Spawning further subagents creates deeply nested hierarchies that are expensive and error-prone. Only use this tool if the current task genuinely cannot be completed with available tools directly. Prefer direct tool calls (exec, read_file, write_file, etc.) over spawning another subagent. `)+`Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:xm,async execute(e,t){return Tm(u,e,t)}}}function Dm(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:Sm,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}q.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await Tm(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`Batch subagents: ${o.length-d.length}/${o.length} completed.`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${wm(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
101
+ `)}\n</available_skills>`}const mm=W.Object({category:W.Optional(W.String({description:`Reserved category filter field. Not used yet.`}))}),hm=W.Object({name:W.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:W.Optional(W.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function gm(e,t,n=[]){return[...n,...t,tm(e)]}function _m(e,t,n=[]){let r=gm(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:mm,async execute(e,t){let n=await lm(r),i={skills:n.map(e=>({name:e.name,description:e.description})),count:n.length};return{content:[{type:`text`,text:JSON.stringify({success:!0,...i,hint:`Use skill_load(name) to load the skill's SKILL.md entrypoint.`})}],details:i}}}}function vm(e){let t=gm(e.dataDir,e.pluginDirs,e.skillsLoadPaths),n=new Set;return{name:`skill_load`,label:`Skill Load`,description:`Load a skill's SKILL.md entrypoint. Optionally override lookup with skillPath.`,parameters:hm,async execute(r,i){let a=await fm(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``,version:``,skillFileMtime:``}}}}}const ym=W.Object({});function bm(e,t,n){return{name:`get_goal`,label:`Get Goal`,description:`Get the current thread goal, including status, budget, token and time usage, and remaining token budget. Returns null when no goal is set.`,parameters:ym,async execute(r,i){let a=await z(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null})}],details:{}};let o=await B(e,t,a,{storeName:n}),s={goal:{...a,objective:o,remainingTokens:a.tokenBudget===null?void 0:Math.max(0,a.tokenBudget-a.tokensUsed)}};return{content:[{type:`text`,text:JSON.stringify(s,null,2)}],details:{}}}}}const xm=W.Object({status:W.String({description:`Status to set. Only 'complete' is allowed.`})});function Sm(e,t,n,r,i=t){return{name:`update_goal`,label:`Update Goal`,description:`Update the existing goal. Only supports marking the goal as complete. Use this only when the objective has actually been achieved and no required work remains. Do not mark a goal complete merely because its budget is nearly exhausted or because you are stopping work.`,parameters:xm,async execute(a,o){if(o.status!==`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Invalid status: "${o.status}". Only "complete" is allowed via this tool.`},null,2)}],details:{}};let s=await z(e,t,{storeName:n});if(!s)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`No active goal exists for this session. Use the CLI to set a goal first.`},null,2)}],details:{}};if(s.status===`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:s},null,2)}],details:{}};let c=await I(e,t,{status:`complete`},{storeName:n,eventSource:`tool`});if(!c)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Failed to update goal.`},null,2)}],details:{}};r&&await pl(r,i,{before:s,after:c,action:`completed`});let l={goal:{...c,remainingTokens:c.tokenBudget===null?void 0:Math.max(0,c.tokenBudget-c.tokensUsed)}};return{content:[{type:`text`,text:JSON.stringify(l,null,2)}],details:{}}}}}const Cm=W.Object({task:W.String({description:`The task description for the subagent to execute`}),label:W.Optional(W.String({description:`Optional short label to identify this subagent`})),agent:W.Optional(W.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),wm=W.Object({task:W.String({description:`The task description for the subagent to execute`}),label:W.Optional(W.String({description:`Optional short label to identify this subagent`})),agent:W.Optional(W.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),Tm=W.Object({tasks:W.Array(Cm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Em(e){let t=e.label?`"${e.label}"`:`task: ${We(e.task)}`;return e.status===`done`?`${t}\n\n${Dm(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Dm(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}async function Om(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(q.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:si(p)}),!p){let e={status:`error`,error:`task must not be empty`};return q.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return q.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Ze(),v=new AbortController,y=t,b=Mr(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return q.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await C(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return q.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}q.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let w=f({dataDir:s,sessionId:y,message:b?Rr(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,w),q.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await w,q.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let T=Em({task:p,label:m,status:S.status,result:S.result,error:S.error});if(S.status===`done`){let e={status:`done`,childSessionId:y,runId:_,result:S.result??``};return q.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:T}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return q.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:T}],isError:!0,details:E}}function km(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. `+(r===0?"IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. You MUST also use this tool when the user mentions '@<agent-name>' where <agent-name> matches a custom agent listed in the Custom Agents section — set the `agent` field to that exact name. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. ":`WARNING: You are already running as a subagent (depth ${r}). Spawning further subagents creates deeply nested hierarchies that are expensive and error-prone. Only use this tool if the current task genuinely cannot be completed with available tools directly. Prefer direct tool calls (exec, read_file, write_file, etc.) over spawning another subagent. `)+`Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:wm,async execute(e,t){return Om(u,e,t)}}}function Am(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:Tm,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}q.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await Om(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`Batch subagents: ${o.length-d.length}/${o.length} completed.`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${Dm(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
102
102
 
103
- `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const Om=W.Object({action:W.Union([`list`,`kill`].map(e=>W.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:W.Optional(W.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function km(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m${Math.floor(e%6e4/1e3)}s`}function Am(e,t){let n=parseInt(t,10);return!isNaN(n)&&n>=1&&n<=e.length?e[n-1]:e.find(e=>e.runId.startsWith(t)||e.runId===t)||(e.find(e=>e.label&&e.label.toLowerCase()===t.toLowerCase())??null)}function jm(e,t){return{name:`subagents`,label:`Subagents`,description:`List or kill subagents spawned by this session. Use list to check status, kill to stop one or all.`,parameters:Om,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let t=o.map((t,n)=>{let r=t.status===`running`?`running`:e.isAnnounced(t.runId)?`delivered`:`pending`;return{index:n+1,runId:t.runId,label:t.label??t.task.slice(0,40),task:t.task,status:t.status,deliveryStatus:r,depth:t.depth,runtimeMs:t.endedAt?t.endedAt-t.startedAt:a-t.startedAt,...t.result===void 0?{}:{result:t.result},...t.error===void 0?{}:{error:t.error}}}),n={action:`list`,runs:t,text:(t.length===0?[`(no subagents)`]:t.map(e=>{let t=e.deliveryStatus===`running`?``:`, ${e.deliveryStatus}`,n=e.result===void 0?e.error===void 0?``:`\n error: ${e.error}`:`\n result: ${e.result}`;return`${e.index}. [${e.status}${t}] ${e.label} (${km(e.runtimeMs)})${n}`})).join(`
104
- `)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Am(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}function Mm(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function Nm(e){let t=Mm(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=H.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function Pm(e){let t=e.watchFactory??((e,t,n)=>U.watch(e,t,n)),n=H.join(e.dataDir,`.aimax`),r=[{target:H.join(n,`MEMORY.md`),kind:`memory-file`},{target:H.join(n,`memory.md`),kind:`memory-file-lower`},{target:H.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=Nm({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}function Fm(e){return e.projectDir?.trim()||H.join(e.dataDir,`workspace`)}async function Im(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Fm(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=zm(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:h?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=H.join(t.dataDir,`.aimax`),h=me({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),g=h?.provider??le({dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),_=h?.registration.id??g.id,v=h?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:h?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!h}}).catch(()=>{});let y=Pm({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await p(t.dataDir,i,e,Rm({sessionOptions:X(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function Lm(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Rm(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function zm(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}const Bm=W.Object({image:W.String({description:`Image path or URL`}),prompt:W.Optional(W.String({description:`Prompt for image analysis`})),model:W.Optional(W.String({description:`Optional model override`})),maxBytesMb:W.Optional(W.Number({description:`Optional size cap in MB`}))});function Vm(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Bm,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}const Hm=W.Object({reason:W.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Um(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??Hm,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=qe(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new xi(e,i,t,e,o,s,n);throw Ai(r),r}}}function Wm(e,t){let n=Fm({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=xf(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await O(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[of({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),uf({registry:i,scopeKey:n}),Of(n,t?.contextManager),Af(n,t?.contextManager,s),Mf(n,t?.contextManager,s),Pf(n),Vf(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[_m(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),ym(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId)]:[],fp(e,r),Pp(e,r),mp(e,r),vp(e,r),Ep(e,r),Op(e,r),Ap(e,r),Mp(e,r),mm(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),hm({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(Eo(e),Do(e),Oo(e),ko(e)),t&&c.push(Em(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Dm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),jm(t.registry,t.parentSessionId)),c}function Gm(e){return e.length===0?``:[`## Auto-Skills`,`Auto-skills are learned from prior completed tasks and are stored separately from curated/user/plugin skills.`,`Auto-skill categories are single-level routing slugs in the current MVP.`,`Prefer curated/user/plugin skills from <available_skills> when both options apply.`,`Use auto-skills only when they clearly match the current task, especially project-specific or previously learned workflows.`,"Match the task to one or more category paths below, call `auto_skill_list({ categoryPath })`, then call `auto_skill_view({ skillId })` for the best match.","If no category is clear but an auto-skill may help, call `auto_skill_search({ query, limit: 5 })`.",`Archived auto-skills are not listed or loaded.`,`<auto_skill_categories>`,[...e].sort((e,t)=>e.path.localeCompare(t.path)).map(e=>e.description?` - ${e.path} | ${e.description}`:` - ${e.path}`).join(`
103
+ `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const jm=W.Object({action:W.Union([`list`,`kill`].map(e=>W.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:W.Optional(W.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Mm(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m${Math.floor(e%6e4/1e3)}s`}function Nm(e,t){let n=parseInt(t,10);return!isNaN(n)&&n>=1&&n<=e.length?e[n-1]:e.find(e=>e.runId.startsWith(t)||e.runId===t)||(e.find(e=>e.label&&e.label.toLowerCase()===t.toLowerCase())??null)}function Pm(e,t){return{name:`subagents`,label:`Subagents`,description:`List or kill subagents spawned by this session. Use list to check status, kill to stop one or all.`,parameters:jm,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let t=o.map((t,n)=>{let r=t.status===`running`?`running`:e.isAnnounced(t.runId)?`delivered`:`pending`;return{index:n+1,runId:t.runId,label:t.label??t.task.slice(0,40),task:t.task,status:t.status,deliveryStatus:r,depth:t.depth,runtimeMs:t.endedAt?t.endedAt-t.startedAt:a-t.startedAt,...t.result===void 0?{}:{result:t.result},...t.error===void 0?{}:{error:t.error}}}),n={action:`list`,runs:t,text:(t.length===0?[`(no subagents)`]:t.map(e=>{let t=e.deliveryStatus===`running`?``:`, ${e.deliveryStatus}`,n=e.result===void 0?e.error===void 0?``:`\n error: ${e.error}`:`\n result: ${e.result}`;return`${e.index}. [${e.status}${t}] ${e.label} (${Mm(e.runtimeMs)})${n}`})).join(`
104
+ `)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Nm(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}function Fm(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function Im(e){let t=Fm(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=H.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function Lm(e){let t=e.watchFactory??((e,t,n)=>U.watch(e,t,n)),n=H.join(e.dataDir,`.aimax`),r=[{target:H.join(n,`MEMORY.md`),kind:`memory-file`},{target:H.join(n,`memory.md`),kind:`memory-file-lower`},{target:H.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=Im({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}function Rm(e){return e.projectDir?.trim()||H.join(e.dataDir,`workspace`)}async function zm(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Rm(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Hm(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:h?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=H.join(t.dataDir,`.aimax`),h=me({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),g=h?.provider??le({dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),_=h?.registration.id??g.id,v=h?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:h?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!h}}).catch(()=>{});let y=Lm({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await p(t.dataDir,i,e,Vm({sessionOptions:X(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function Bm(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Vm(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function Hm(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}const Um=W.Object({image:W.String({description:`Image path or URL`}),prompt:W.Optional(W.String({description:`Prompt for image analysis`})),model:W.Optional(W.String({description:`Optional model override`})),maxBytesMb:W.Optional(W.Number({description:`Optional size cap in MB`}))});function Wm(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Um,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}const Gm=W.Object({reason:W.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Km(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??Gm,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=qe(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new xi(e,i,t,e,o,s,n);throw Ai(r),r}}}function qm(e,t){let n=Rm({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=wf(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await O(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[of({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),uf({registry:i,scopeKey:n}),jf(n,t?.contextManager),Nf(n,t?.contextManager,s),Ff(n,t?.contextManager,s),Lf(n),Wf(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[bm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),Sm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId)]:[],hp(e,r),Lp(e,r),_p(e,r),xp(e,r),kp(e,r),jp(e,r),Np(e,r),Fp(e,r),_m(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),vm({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(Eo(e),Do(e),Oo(e),ko(e)),t&&c.push(km(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Am(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Pm(t.registry,t.parentSessionId)),c}function Jm(e){return e.length===0?``:[`## Auto-Skills`,`Auto-skills are learned from prior completed tasks and are stored separately from curated/user/plugin skills.`,`Auto-skill categories are single-level routing slugs in the current MVP.`,`Prefer curated/user/plugin skills from <available_skills> when both options apply.`,`Use auto-skills only when they clearly match the current task, especially project-specific or previously learned workflows.`,"Match the task to one or more category paths below, call `auto_skill_list({ categoryPath })`, then call `auto_skill_view({ skillId })` for the best match.","If no category is clear but an auto-skill may help, call `auto_skill_search({ query, limit: 5 })`.",`Archived auto-skills are not listed or loaded.`,`<auto_skill_categories>`,[...e].sort((e,t)=>e.path.localeCompare(t.path)).map(e=>e.description?` - ${e.path} | ${e.description}`:` - ${e.path}`).join(`
105
105
  `),`</auto_skill_categories>`,``].join(`
106
- `)}const Km={get_goal:`Get the current thread goal including status, budget, and usage`,update_goal:`Mark the existing thread goal as complete when the objective is achieved`,read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,auto_skill_categories:`List learned auto-skill categories`,auto_skill_list:`List active learned auto-skills by category`,auto_skill_search:`Search active learned auto-skills`,auto_skill_view:`Load an active learned auto-skill by exact skillId`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},qm=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`get_goal`,`update_goal`,`auto_skill_categories`,`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function Jm(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...qm.filter(e=>t.has(e)),...n.filter(e=>!qm.includes(e)).sort()],displayName:t}}function Ym(e){let{ordered:t,displayName:n}=Jm(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??Km[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
106
+ `)}const Ym={get_goal:`Get the current thread goal including status, budget, and usage`,update_goal:`Mark the existing thread goal as complete when the objective is achieved`,read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,auto_skill_categories:`List learned auto-skill categories`,auto_skill_list:`List active learned auto-skills by category`,auto_skill_search:`Search active learned auto-skills`,auto_skill_view:`Load an active learned auto-skill by exact skillId`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Xm=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`get_goal`,`update_goal`,`auto_skill_categories`,`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function Zm(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...Xm.filter(e=>t.has(e)),...n.filter(e=>!Xm.includes(e)).sort()],displayName:t}}function Qm(e){let{ordered:t,displayName:n}=Zm(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??Ym[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
107
107
  `),``].join(`
108
- `)}function Xm(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Use `get_goal` to view the current goal, its status, budget, and usage.",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,'- When you have completed the objective and verified it against the requirements, use `update_goal` with `status: "complete"`.',"- Do NOT call `update_goal(complete)` merely because the budget is nearly exhausted or work is paused.",`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, `get_goal` returns null and `update_goal` reports an error.",``].join(`
109
- `)}function Zm(){return[`## Safety`,`You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.`,`Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards.`,`Do not attempt to bypass approvals, safety rails, or access boundaries.`,`Never print, reveal, or echo environment variable values. If configuration must be shown, use placeholders plus brief meanings instead, such as {{API_KEY}}: model access credential.`,``].join(`
110
- `)}function Qm(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
111
- `)}function $m(e){return e?``:[`## Tool Call Style`,`Default: call routine low-risk tools directly without narrating every step.`,`Narrate briefly when actions are sensitive, long-running, or likely surprising.`,`When approvals are required, keep the command text exact and complete.`,``].join(`
112
- `)}function eh(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
108
+ `)}function $m(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Use `get_goal` to view the current goal, its status, budget, and usage.",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,'- When you have completed the objective and verified it against the requirements, use `update_goal` with `status: "complete"`.',"- Do NOT call `update_goal(complete)` merely because the budget is nearly exhausted or work is paused.",`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, `get_goal` returns null and `update_goal` reports an error.",``].join(`
109
+ `)}function eh(){return[`## Safety`,`You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.`,`Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards.`,`Do not attempt to bypass approvals, safety rails, or access boundaries.`,`Never print, reveal, or echo environment variable values. If configuration must be shown, use placeholders plus brief meanings instead, such as {{API_KEY}}: model access credential.`,``].join(`
110
+ `)}function th(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
111
+ `)}function nh(e){return e?``:[`## Tool Call Style`,`Default: call routine low-risk tools directly without narrating every step.`,`Narrate briefly when actions are sensitive, long-running, or likely surprising.`,`When approvals are required, keep the command text exact and complete.`,``].join(`
112
+ `)}function rh(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
113
113
  `)).join(`
114
114
  `)}\n</available_skills>`,``].join(`
115
- `)}function th(e=[]){let t=Gm(e).trim();return t?`${t}\n`:``}function nh(){return[`## Scenes`,'If the user message contains a `<scenes category="..." type="..." items="...">...</scenes>` tag, treat it as an explicit scene activation request.',"In this tag, `category` means the scene category, `type` means the scene name, and `items` means the item list required by that scene.","The `category`, `type`, and `items` attributes may each contain one or more comma-separated values. You must split them on commas, trim whitespace, and use every requested value.","Before executing the task, you must enumerate every requested `<category, scene, item>` combination derived from those attributes.","For each requested item, you must call `skill_load(name=<item>, skillPath=/aimax_pvc/scenes/<category>/<scene>/<item>)` to load that item's `SKILL.md`.","If one `<scenes ...>` tag requests multiple items for the same scene, you must load them one by one. Do not stop after the first matching item.","Do not start implementation, analysis, tool execution, or user-facing conclusions until all required scene skills have been loaded with `skill_load`.","After loading those scene `SKILL.md` files through `skill_load`, you must follow their instructions as mandatory task-specific guidance unless a higher-priority instruction overrides them.","For scene skills, if the exact scene SKILL.md is not visible, reload it again with the original `skillPath`.","Scene skills are not loaded by default. Only load them when the user explicitly includes the `<scenes ...>` tag.","Outside explicit scene activation, normal shared skills from `<available_skills>` must still be loaded with `skill_load(name=<skill-name>)` rather than direct file reads.","When a scene is activated, you must load scene instructions only through `skill_load` with `skillPath` pointing at `/aimax_pvc/scenes/<category>/<scene>/<item>` or that directory's `SKILL.md`.","Do not load, match, or fall back to scene instructions from `<dataDir>/.aimax/skills`.","Do not load, match, or fall back to scene instructions from `/aimax/extensions/`.","Do not load, match, or fall back to scene instructions from any path declared in `<available_skills>`.",`Do not ignore, rewrite, or drop the scene tag semantics even if the natural-language request looks answerable without scene skills.`,``].join(`
116
- `)}function rh(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: write durable long-term memory to MEMORY.md (facts, preferences, rules, decisions).`,`- memory_log: append short-lived daily/session notes to memory/YYYY-MM-DD.md or session logs.`,`- Choose exactly one write surface per fact by default: long-term -> memory_write; daily/session log -> memory_log.`,`- Do not write the same fact to both memory_write and memory_log unless the user explicitly requests dual-write.`,`- Before memory_update or memory_forget, first run memory_list or memory_search to get the exact id/path.`,`- If the user explicitly names a listed memory tool, prefer calling that exact tool.`,`- Pattern: write/log for new memory; list/search -> update/forget for existing memory.`,``].join(`
117
- `)}function ih(e){return[`## Memory & session recall`,`Choose the right recall surface:`,"- **Durable memory (Markdown / MEMORY.md / memory/ logs)**: stable facts, preferences, policies, decisions. Prefer `memory_search`, then `memory_get` when you need the full passage. Do not guess entry IDs or file paths.","- **Past chat transcripts across sessions** (what was said or done in earlier conversations): use `session_search`. Omit `query` to browse recent sessions; include `query` to search transcripts. Do not use `memory_search` alone to reconstruct a cross-session chat timeline.",'- **Ambiguous** ("last time" could mean chat or written notes): run `session_search` first for conversational evidence, then `memory_search` for durable notes; merge and attribute each source.',"If a listed memory tool call fails, report the failure; do not claim the tool is unavailable. Use `memory_list` before update/delete when needed.","Short tool chains: `memory_search` → `memory_get`; `memory_list` → `memory_update`; `memory_search` → `memory_forget`.",`Routing examples (intent → tool):`,'1) "上次聊天我们怎么修的" → `session_search` with keywords from the bug/symptom.','2) "团队对 release 的硬性规范是什么" → `memory_search` (durable policy).','3) "最近几个会话在忙什么" → `session_search` with no query (recent mode).','4) "把这条写进长期记忆" → `memory_write` (default), not `memory_log` or `session_search`.','5) "昨天日志里有没有记过 X" → `memory_search` on daily logs / `memory_list`.','6) "上次口头结论 vs 正式文档" → `session_search` then `memory_search`.',e===`off`?`Citations are disabled: do not include memory file paths or line numbers unless the user explicitly asks.`:`When useful, include memory evidence as Source: <path#line>.`,``].join(`
118
- `)}function ah(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`,o=e.projectDir?.trim(),s=o?[`Current project directory: ${o}`,`Treat this project directory as the default cwd for repository/code work unless the user specifies another directory.`]:[];return[`## Workspace`,`Your cloud working directory is: ${r}`,...s,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, MEMORY.md, and the memory/ directory belong under ${t}.`,`Only create or update those files at their real .aimax paths. Never create cloud workspace copies like ${r}/AGENTS.md or ${r}/MEMORY.md unless the user explicitly asks for separate cloud documents.`,``].join(`
119
- `)}function oh(e){if(!e?.enabled)return``;let t=[`## Sandbox`,`You are running in a containerized cloud CLI runtime.`];return e.containerWorkspaceDir?.trim()&&t.push(`Container workdir: ${e.containerWorkspaceDir.trim()}`),e.hostWorkspaceDir?.trim()&&t.push(`Host-mounted workspace: ${e.hostWorkspaceDir.trim()}`),t.push(``),t.join(`
120
- `)}function sh(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=ch(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
121
- `)}function ch(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(Date.UTC(n,r-1,i));return Number.isNaN(a.getTime())||a.getUTCFullYear()!==n||a.getUTCMonth()!==r-1||a.getUTCDate()!==i?null:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][a.getUTCDay()]}function lh(e){if(e.isMinimal||!e.enabled)return``;let t=(e.channels??[]).map(e=>e.trim()).filter(Boolean);return[`## Messaging`,`Reply in the current session for user-visible responses.`,`Use subagent tools only when the user or system instructions explicitly require subagents, delegation, or parallel agent execution; otherwise stay in the current agent.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
122
- `)}function uh(e){if(!e)return``;let t=[e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
123
- `)}function dh(e){return e.isMinimal?``:[`## Silent Replies`,`Do not send empty or filler replies.`,`If a tool already delivered the user-visible output, keep your final reply minimal and avoid duplication.`,``].join(`
124
- `)}function fh(e){let t=e.contextFiles,n=(e.bootstrapWarnings??[]).map(e=>e.trim()).filter(Boolean);if(t.length===0&&n.length===0)return``;let r=t.some(e=>(e.path.split(`/`).pop()?.toLowerCase()??``)===`soul.md`),i=[`# Project Context`,``];if(n.length>0){i.push(`⚠ Bootstrap truncation warning:`);for(let e of n)i.push(`- ${e}`);i.push(``)}t.length>0&&(i.push(`The following project context files have been loaded:`),i.push(`These are source-of-truth cloud files at their shown paths. If you update them, use the exact path shown in the heading, especially for files under .aimax.`)),r&&i.push(`If SOUL.md is present, embody its persona and tone. Avoid stiff, generic replies; follow its guidance unless higher-priority instructions override it.`),i.push(``);for(let e of t)i.push(`## ${e.path}`,``,e.content,``);return i.join(`
125
- `)}function ph(e){return e<=0?``:[`## Subagent Constraint`,`You are running as a subagent (nesting depth: ${e}). Your role is to complete the delegated task directly using available tools.`,`Do NOT spawn further subagents unless the task absolutely cannot be completed any other way.`,`If you find yourself wanting to use subagent_spawn, first ask whether a direct tool call (exec, read_file, write_file, edit_file, etc.) can achieve the same result.`,`Subagent nesting adds overhead and complexity — prefer direct execution in all but the most exceptional cases.`,``].join(`
126
- `)}function mh(e){return e?.trim()?[`## Prior Conversation Summary`,`The following is a summary of the conversation history that occurred before the current context window.`,`Use it to maintain continuity with earlier work.`,``,e.trim(),``].join(`
127
- `):``}function hh(e){let t=e.promptMode??`full`,n=t===`minimal`,r=e.activeAgentSystemPrompt?.trim()||e.presetSystemPrompt||`You are a personal assistant running inside AiMax.`;if(t===`none`)return r;let i=e.toolNames&&e.toolNames.length>0?e.toolNames:[...qm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,ph(e.subagentDepth??0),Ym({toolNames:i,toolSummaries:e.toolSummaries}),$m(n),Xm(),Zm(),Lr(e.availableAgents??[]),eh(a),th(e.autoSkillCategories),nh(),rh(),ih(e.memoryCitationsMode??`off`),ah({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),oh(e.sandboxInfo),sh({currentDate:e.currentDate,timezone:e.timezone}),Qm(),lh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),dh({isMinimal:n}),uh(e.runtimeInfo),fh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),mh(e.priorConversationSummary)].filter(Boolean).join(`
128
- `)}const gh=Symbol(`pluginToolOwner`);var _h=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,gh,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=Um({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,gh,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function vh(e){return e[gh]}function yh(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=vh(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Gr({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h;try{h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r)}catch(e){if(bi(e))return Ei(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}for(let e of h)e&&(e.params&&(d=e.params),e.block&&(f=!0,p=e.blockReason));if(f)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:p??`blocked by plugin`,durationMs:Date.now()-u},n,r),{content:[{type:`text`,text:p??`Tool blocked by plugin`}],isError:!0,details:{}};try{let o=await m(async()=>await i.execute(e,d,c,l));return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}catch(i){if(bi(i)){Ei(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}const bh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function xh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Sh(e){let t=xh(e?.warningThreshold,bh.warningThreshold),n=xh(e?.criticalThreshold,bh.criticalThreshold),r=xh(e?.globalCircuitBreakerThreshold,bh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??bh.enabled,historySize:xh(e?.historySize,bh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??bh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??bh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??bh.detectors.pingPong}}}function Ch(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function wh(e,t){return`${e}:${Dh(t)}`}function Th(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Th).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Th(t[e])}`).join(`,`)}}`}function Eh(e){try{return Th(e)}catch{return e==null?`${e}`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:e instanceof Error?`${e.name}:${e.message}`:Object.prototype.toString.call(e)}}function Dh(e){let t=Eh(e);return Xe(`sha256`).update(t).digest(`hex`)}function Oh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Ch(t))return!1;let n=t.action;return n===`poll`||n===`log`}function kh(e){return!Ch(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Ch(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
129
- `).trim()}function Ah(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Th(e)}function jh(e,t,n,r){if(r!==void 0)return`error:${Dh(Ah(r))}`;if(!Ch(n))return n===void 0?void 0:Dh(n);let i=Ch(n.details)?n.details:{},a=kh(n);if(Oh(e,t)&&e===`process`&&Ch(t)){let e=t.action;if(e===`poll`)return Dh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Dh({action:e,status:i.status,totalLines:i.totalLines??null,totalChars:i.totalChars??null,truncated:i.truncated??null,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,text:a})}return Dh({details:i,text:a})}function Mh(e,t,n){let r=0,i;for(let a=e.length-1;a>=0;--a){let o=e[a];if(!(!o||o.toolName!==t||o.argsHash!==n)&&!(typeof o.resultHash!=`string`||!o.resultHash)){if(!i){i=o.resultHash,r=1;continue}if(o.resultHash!==i)break;r+=1}}return{count:r,latestResultHash:i}}function Nh(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function Ph(e,t){return[e,t].toSorted().join(`|`)}function Fh(e,t,n,r){let i=Sh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=wh(t,n),s=Mh(a,t,o),c=s.count,l=Oh(t,n),u=Nh(a,o);if(c>=i.globalCircuitBreakerThreshold)return{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:c,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${c} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.criticalThreshold)return{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:c,message:`CRITICAL: Called ${t} with identical arguments and no progress ${c} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:c,message:`WARNING: You have called ${t} ${c} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};let d=u.pairedSignature?`pingpong:${Ph(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function Ih(e,t,n,r,i){let a=Sh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:wh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Lh(e,t){let n=Sh(t.config),r=jh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=wh(t.toolName,t.toolParams),a=!1;for(let n=e.toolCallHistory.length-1;n>=0;--n){let o=e.toolCallHistory[n];if(o&&!(t.toolCallId&&o.toolCallId!==t.toolCallId)&&!(o.toolName!==t.toolName||o.argsHash!==i)&&o.resultHash===void 0){o.resultHash=r,a=!0;break}}a||e.toolCallHistory.push({toolName:t.toolName,argsHash:i,toolCallId:t.toolCallId,resultHash:r,timestamp:Date.now()}),e.toolCallHistory.length>n.historySize&&e.toolCallHistory.splice(0,e.toolCallHistory.length-n.historySize)}function Rh(e,t,n){e.toolLoopWarningBuckets||=new Map;let r=Math.floor(n/10);if(r<=(e.toolLoopWarningBuckets.get(t)??0))return!1;if(e.toolLoopWarningBuckets.set(t,r),e.toolLoopWarningBuckets.size>256){let t=e.toolLoopWarningBuckets.keys().next().value;t&&e.toolLoopWarningBuckets.delete(t)}return!0}function zh(e){return e&&e.trim()||`tool`}function Bh(e,t,n){if(!e.execute)return e;let r=zh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Fh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Rh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Ih(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Lh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Lh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Vh(e,t,n){return e.map(e=>Bh(e,t,n))}function Hh(e){let t=e.streamFn??lt;return(e,n,r)=>(e.api===`anthropic-messages`&&Uh(e),t(e,n,{...r,...Xh(e,r)}))}function Uh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Kh(Yh(e),n)?(globalThis.fetch=t,Wh(await t(e,qh(e,r)))):t(e,r))}function Wh(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
130
-
131
- `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Gh))),a.enqueue(r.encode(e+`
132
-
133
- `))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Gh=`event: message_start
115
+ `)}function ih(e=[]){let t=Jm(e).trim();return t?`${t}\n`:``}function ah(){return[`## Scenes`,'If the user message contains a `<scenes category="..." type="..." items="...">...</scenes>` tag, treat it as an explicit scene activation request.',"In this tag, `category` means the scene category, `type` means the scene name, and `items` means the item list required by that scene.","The `category`, `type`, and `items` attributes may each contain one or more comma-separated values. You must split them on commas, trim whitespace, and use every requested value.","Before executing the task, you must enumerate every requested `<category, scene, item>` combination derived from those attributes.","For each requested item, you must call `skill_load(name=<item>, skillPath=/aimax_pvc/scenes/<category>/<scene>/<item>)` to load that item's `SKILL.md`.","If one `<scenes ...>` tag requests multiple items for the same scene, you must load them one by one. Do not stop after the first matching item.","Do not start implementation, analysis, tool execution, or user-facing conclusions until all required scene skills have been loaded with `skill_load`.","After loading those scene `SKILL.md` files through `skill_load`, you must follow their instructions as mandatory task-specific guidance unless a higher-priority instruction overrides them.","For scene skills, if the exact scene SKILL.md is not visible, reload it again with the original `skillPath`.","Scene skills are not loaded by default. Only load them when the user explicitly includes the `<scenes ...>` tag.","Outside explicit scene activation, normal shared skills from `<available_skills>` must still be loaded with `skill_load(name=<skill-name>)` rather than direct file reads.","When a scene is activated, you must load scene instructions only through `skill_load` with `skillPath` pointing at `/aimax_pvc/scenes/<category>/<scene>/<item>` or that directory's `SKILL.md`.","Do not load, match, or fall back to scene instructions from `<dataDir>/.aimax/skills`.","Do not load, match, or fall back to scene instructions from `/aimax/extensions/`.","Do not load, match, or fall back to scene instructions from any path declared in `<available_skills>`.",`Do not ignore, rewrite, or drop the scene tag semantics even if the natural-language request looks answerable without scene skills.`,``].join(`
116
+ `)}function oh(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: write durable long-term memory to MEMORY.md (facts, preferences, rules, decisions).`,`- memory_log: append short-lived daily/session notes to memory/YYYY-MM-DD.md or session logs.`,`- Choose exactly one write surface per fact by default: long-term -> memory_write; daily/session log -> memory_log.`,`- Do not write the same fact to both memory_write and memory_log unless the user explicitly requests dual-write.`,`- Before memory_update or memory_forget, first run memory_list or memory_search to get the exact id/path.`,`- If the user explicitly names a listed memory tool, prefer calling that exact tool.`,`- Pattern: write/log for new memory; list/search -> update/forget for existing memory.`,``].join(`
117
+ `)}function sh(e){return[`## Memory & session recall`,`Choose the right recall surface:`,"- **Durable memory (Markdown / MEMORY.md / memory/ logs)**: stable facts, preferences, policies, decisions. Prefer `memory_search`, then `memory_get` when you need the full passage. Do not guess entry IDs or file paths.","- **Past chat transcripts across sessions** (what was said or done in earlier conversations): use `session_search`. Omit `query` to browse recent sessions; include `query` to search transcripts. Do not use `memory_search` alone to reconstruct a cross-session chat timeline.",'- **Ambiguous** ("last time" could mean chat or written notes): run `session_search` first for conversational evidence, then `memory_search` for durable notes; merge and attribute each source.',"If a listed memory tool call fails, report the failure; do not claim the tool is unavailable. Use `memory_list` before update/delete when needed.","Short tool chains: `memory_search` → `memory_get`; `memory_list` → `memory_update`; `memory_search` → `memory_forget`.",`Routing examples (intent → tool):`,'1) "上次聊天我们怎么修的" → `session_search` with keywords from the bug/symptom.','2) "团队对 release 的硬性规范是什么" → `memory_search` (durable policy).','3) "最近几个会话在忙什么" → `session_search` with no query (recent mode).','4) "把这条写进长期记忆" → `memory_write` (default), not `memory_log` or `session_search`.','5) "昨天日志里有没有记过 X" → `memory_search` on daily logs / `memory_list`.','6) "上次口头结论 vs 正式文档" → `session_search` then `memory_search`.',e===`off`?`Citations are disabled: do not include memory file paths or line numbers unless the user explicitly asks.`:`When useful, include memory evidence as Source: <path#line>.`,``].join(`
118
+ `)}function ch(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`,o=e.projectDir?.trim(),s=o?[`Current project directory: ${o}`,`Treat this project directory as the default cwd for repository/code work unless the user specifies another directory.`]:[];return[`## Workspace`,`Your cloud working directory is: ${r}`,...s,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, MEMORY.md, and the memory/ directory belong under ${t}.`,`Only create or update those files at their real .aimax paths. Never create cloud workspace copies like ${r}/AGENTS.md or ${r}/MEMORY.md unless the user explicitly asks for separate cloud documents.`,`Use the workspace temp directories for temporary or intermediate files:`,`- ${r}/temp/daily/ for short-lived files that can be cleaned daily.`,`- ${r}/temp/weekly/ for files that should remain available for about a week.`,`- ${r}/temp/monthly/ for files that should remain available for about a month.`,`Do not pre-initialize these directories; create them only when you actually need to write temporary files.`,``].join(`
119
+ `)}function lh(e){if(!e?.enabled)return``;let t=[`## Sandbox`,`You are running in a containerized cloud CLI runtime.`];return e.containerWorkspaceDir?.trim()&&t.push(`Container workdir: ${e.containerWorkspaceDir.trim()}`),e.hostWorkspaceDir?.trim()&&t.push(`Host-mounted workspace: ${e.hostWorkspaceDir.trim()}`),t.push(``),t.join(`
120
+ `)}function uh(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=dh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
121
+ `)}function dh(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(Date.UTC(n,r-1,i));return Number.isNaN(a.getTime())||a.getUTCFullYear()!==n||a.getUTCMonth()!==r-1||a.getUTCDate()!==i?null:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][a.getUTCDay()]}function fh(e){if(e.isMinimal||!e.enabled)return``;let t=(e.channels??[]).map(e=>e.trim()).filter(Boolean);return[`## Messaging`,`Reply in the current session for user-visible responses.`,`Use subagent tools only when the user or system instructions explicitly require subagents, delegation, or parallel agent execution; otherwise stay in the current agent.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
122
+ `)}function ph(e){if(!e)return``;let t=[e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
123
+ `)}function mh(e){return e.isMinimal?``:[`## Silent Replies`,`Do not send empty or filler replies.`,`If a tool already delivered the user-visible output, keep your final reply minimal and avoid duplication.`,``].join(`
124
+ `)}function hh(e){let t=e.contextFiles,n=(e.bootstrapWarnings??[]).map(e=>e.trim()).filter(Boolean);if(t.length===0&&n.length===0)return``;let r=t.some(e=>(e.path.split(`/`).pop()?.toLowerCase()??``)===`soul.md`),i=[`# Project Context`,``];if(n.length>0){i.push(`⚠ Bootstrap truncation warning:`);for(let e of n)i.push(`- ${e}`);i.push(``)}t.length>0&&(i.push(`The following project context files have been loaded:`),i.push(`These are source-of-truth cloud files at their shown paths. If you update them, use the exact path shown in the heading, especially for files under .aimax.`)),r&&i.push(`If SOUL.md is present, embody its persona and tone. Avoid stiff, generic replies; follow its guidance unless higher-priority instructions override it.`),i.push(``);for(let e of t)i.push(`## ${e.path}`,``,e.content,``);return i.join(`
125
+ `)}function gh(e){return e<=0?``:[`## Subagent Constraint`,`You are running as a subagent (nesting depth: ${e}). Your role is to complete the delegated task directly using available tools.`,`Do NOT spawn further subagents unless the task absolutely cannot be completed any other way.`,`If you find yourself wanting to use subagent_spawn, first ask whether a direct tool call (exec, read_file, write_file, edit_file, etc.) can achieve the same result.`,`Subagent nesting adds overhead and complexity — prefer direct execution in all but the most exceptional cases.`,``].join(`
126
+ `)}function _h(e){return e?.trim()?[`## Prior Conversation Summary`,`The following is a summary of the conversation history that occurred before the current context window.`,`Use it to maintain continuity with earlier work.`,``,e.trim(),``].join(`
127
+ `):``}function vh(e){let t=e.promptMode??`full`,n=t===`minimal`,r=e.activeAgentSystemPrompt?.trim()||e.presetSystemPrompt||`You are a personal assistant running inside AiMax.`;if(t===`none`)return r;let i=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Xm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,gh(e.subagentDepth??0),Qm({toolNames:i,toolSummaries:e.toolSummaries}),nh(n),$m(),eh(),Lr(e.availableAgents??[]),rh(a),ih(e.autoSkillCategories),ah(),oh(),sh(e.memoryCitationsMode??`off`),ch({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),lh(e.sandboxInfo),uh({currentDate:e.currentDate,timezone:e.timezone}),th(),fh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),mh({isMinimal:n}),ph(e.runtimeInfo),hh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),_h(e.priorConversationSummary)].filter(Boolean).join(`
128
+ `)}const yh=Symbol(`pluginToolOwner`);var bh=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,yh,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=Km({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,yh,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function xh(e){return e[yh]}function Sh(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=xh(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Gr({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h;try{h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r)}catch(e){if(bi(e))return Ei(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}for(let e of h)e&&(e.params&&(d=e.params),e.block&&(f=!0,p=e.blockReason));if(f)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:p??`blocked by plugin`,durationMs:Date.now()-u},n,r),{content:[{type:`text`,text:p??`Tool blocked by plugin`}],isError:!0,details:{}};try{let o=await m(async()=>await i.execute(e,d,c,l));return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}catch(i){if(bi(i)){Ei(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}const Ch={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function wh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Th(e){let t=wh(e?.warningThreshold,Ch.warningThreshold),n=wh(e?.criticalThreshold,Ch.criticalThreshold),r=wh(e?.globalCircuitBreakerThreshold,Ch.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Ch.enabled,historySize:wh(e?.historySize,Ch.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Ch.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Ch.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Ch.detectors.pingPong}}}function Eh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Dh(e,t){return`${e}:${Ah(t)}`}function Oh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Oh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Oh(t[e])}`).join(`,`)}}`}function kh(e){try{return Oh(e)}catch{return e==null?`${e}`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:e instanceof Error?`${e.name}:${e.message}`:Object.prototype.toString.call(e)}}function Ah(e){let t=kh(e);return Xe(`sha256`).update(t).digest(`hex`)}function jh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Eh(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Mh(e){return!Eh(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Eh(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
129
+ `).trim()}function Nh(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Oh(e)}function Ph(e,t,n,r){if(r!==void 0)return`error:${Ah(Nh(r))}`;if(!Eh(n))return n===void 0?void 0:Ah(n);let i=Eh(n.details)?n.details:{},a=Mh(n);if(jh(e,t)&&e===`process`&&Eh(t)){let e=t.action;if(e===`poll`)return Ah({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Ah({action:e,status:i.status,totalLines:i.totalLines??null,totalChars:i.totalChars??null,truncated:i.truncated??null,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,text:a})}return Ah({details:i,text:a})}function Fh(e,t,n){let r=0,i;for(let a=e.length-1;a>=0;--a){let o=e[a];if(!(!o||o.toolName!==t||o.argsHash!==n)&&!(typeof o.resultHash!=`string`||!o.resultHash)){if(!i){i=o.resultHash,r=1;continue}if(o.resultHash!==i)break;r+=1}}return{count:r,latestResultHash:i}}function Ih(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function Lh(e,t){return[e,t].toSorted().join(`|`)}function Rh(e,t,n,r){let i=Th(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Dh(t,n),s=Fh(a,t,o),c=s.count,l=jh(t,n),u=Ih(a,o);if(c>=i.globalCircuitBreakerThreshold)return{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:c,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${c} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.criticalThreshold)return{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:c,message:`CRITICAL: Called ${t} with identical arguments and no progress ${c} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:c,message:`WARNING: You have called ${t} ${c} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};let d=u.pairedSignature?`pingpong:${Lh(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function zh(e,t,n,r,i){let a=Th(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Dh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Bh(e,t){let n=Th(t.config),r=Ph(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Dh(t.toolName,t.toolParams),a=!1;for(let n=e.toolCallHistory.length-1;n>=0;--n){let o=e.toolCallHistory[n];if(o&&!(t.toolCallId&&o.toolCallId!==t.toolCallId)&&!(o.toolName!==t.toolName||o.argsHash!==i)&&o.resultHash===void 0){o.resultHash=r,a=!0;break}}a||e.toolCallHistory.push({toolName:t.toolName,argsHash:i,toolCallId:t.toolCallId,resultHash:r,timestamp:Date.now()}),e.toolCallHistory.length>n.historySize&&e.toolCallHistory.splice(0,e.toolCallHistory.length-n.historySize)}function Vh(e,t,n){e.toolLoopWarningBuckets||=new Map;let r=Math.floor(n/10);if(r<=(e.toolLoopWarningBuckets.get(t)??0))return!1;if(e.toolLoopWarningBuckets.set(t,r),e.toolLoopWarningBuckets.size>256){let t=e.toolLoopWarningBuckets.keys().next().value;t&&e.toolLoopWarningBuckets.delete(t)}return!0}function Hh(e){return e&&e.trim()||`tool`}function Uh(e,t,n){if(!e.execute)return e;let r=Hh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Rh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Vh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}zh(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Bh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Bh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Wh(e,t,n){return e.map(e=>Uh(e,t,n))}function Gh(e){let t=e.streamFn??lt;return(e,n,r)=>(e.api===`anthropic-messages`&&Kh(e),t(e,n,{...r,...$h(e,r)}))}function Kh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Yh(Qh(e),n)?(globalThis.fetch=t,qh(await t(e,Xh(e,r)))):t(e,r))}function qh(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
130
+
131
+ `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Jh))),a.enqueue(r.encode(e+`
132
+
133
+ `))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Jh=`event: message_start
134
134
  data: {"type":"message_start","message":{"id":"","type":"message","role":"assistant","content":[],"model":"","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}
135
135
 
136
- `;function Kh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function qh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Jh(e)&&n.delete(e);return{...t,headers:n}}function Jh(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function Yh(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function Xh(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function Zh(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,autoSkillCategories:u,effectivePromptText:f,pluginTools:p,pluginSkillDirs:h,skillsLoadPaths:g,presetSystemPrompt:_},dependencies:{registry:v,spawnFn:y,createModel:b,abortSignal:x}}=e,S=t.autoSkills?.load?.enabled===!0,C=t.agentPolicy?.activeAgent,w=t.channel===`CRON`,T=w?[]:await m(t.dataDir,n,X(t)),E={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},D=await Jd({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=w?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Yd({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:x,hooks:r,hookCtx:i,contextManager:D,dataDir:t.dataDir,sessionId:n});await eg({sessionId:n,historyResult:O,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let k=t.subagentContext?.depth??0,A=d(t.dataDir,n,X(t)),j=Ir([...Wm(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:A,registry:v,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:g,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:h,skillsLoadPaths:g,reportSkillUsed:async e=>{await o.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:o,spawnFn:y,baseEnv:t.env}),...p],C),M=j.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),N={};for(let e of j){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||N[t]||(N[t]=n)}let ee=t.messaging?.enabled??t.channel!==`CRON`,P=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],F=hh({dataDir:t.dataDir,projectDir:t.projectDir,skills:Fr(l,C),autoSkillCategories:S?u:[],contextFiles:s,toolNames:M,toolSummaries:N,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:ee,channels:P},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:vt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});F=await Qh({systemPrompt:F,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let te=await r.dispatch(`before_prompt_build`,{prompt:f},i,{eventDispatcher:o});for(let e of te)e&&(e.systemPrompt&&(F=e.systemPrompt),e.prependContext&&(F=`${e.prependContext}\n\n${F}`));await r.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:F},i,{eventDispatcher:o});let ne=Vh(yh(j,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},Qs),I=C?.model??t.llm.model,L=await r.dispatch(`before_model_resolve`,{prompt:f},i,{eventDispatcher:o});for(let e of L)e&&e.modelOverride&&(I=e.modelOverride);let R=b({...t.llm,model:I},n,t.messageId,t.channel),z=new et({initialState:{systemPrompt:F,model:R,tools:ne,messages:[]},getApiKey:e=>t.llm.apiKey,streamFn:Hh({})});return O.messages.length>0&&z.replaceMessages(O.messages),{agent:z,resolvedModelId:I,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:a.workspaceDir}}async function Qh(e){if((await f(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})).length<=8)return e.systemPrompt;let t=`Older CRON execution records for this session are stored outside the main transcript at ${j(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})}. The main transcript keeps only the latest 8 CRON summaries. Read that jsonl file explicitly if older CRON outcomes matter.`;return`${e.systemPrompt}\n\n${t}`}async function $h(e){let{session:t,runtime:n,effectivePromptText:r,dependencies:i}=e,{runParams:a,sessionId:o,hookRegistry:s,hookContext:c,runContext:l,eventDispatcher:u}=t,{abortSignal:d}=i;if(a.channel===`CRON`)return{status:`skipped`,reason:`CRON runs do not persist transcript history.`};let f=await il({entries:await m(a.dataDir,o,X(a)),contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.flashModel??a.llm.model},instructions:va,signal:d,hooks:s,hookCtx:c});if(f.status!==`compacted`)return{status:`skipped`,reason:f.reason};await eg({sessionId:o,historyResult:{messages:[],priorSummary:void 0,compactionEntry:f.entry,stats:{originalCount:f.keptCount+f.droppedCount,keptCount:f.keptCount,estimatedTokens:f.estimatedTokens,compacted:!0},compactionEvents:[{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`,estimatedTokensFreed:Math.max(0,f.droppedCount),affectedEntries:f.droppedCount,snapshotVersion:2}]},runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),await u.dispatchProgress(o,{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`});let p={model:a.llm.model,api:a.llm.apiFormat??`openai-completions`},h=await Yd({entries:await m(a.dataDir,o,X(a)),modelInfo:p,contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.model,flashModel:a.llm.flashModel},historyLimit:a.historyLimit,topicSegmentation:a.topicSegmentation,channel:a.channel,isSubagent:!!a.subagentContext,compactionEnabled:!0,pendingUserMessage:r,signal:d,hooks:s,hookCtx:c,contextManager:n.contextManager,dataDir:a.dataDir,sessionId:o});return await eg({sessionId:o,historyResult:h,runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),n.historyResult=h,n.historyMessages=h.messages,n.agent.replaceMessages(h.messages),{status:`compacted`}}async function eg(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount,s=tg(await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i})),c=s.injectRecall?{...n.compactionEntry,content:`${s.injectRecall.trim()}\n\n${n.compactionEntry.content}`}:n.compactionEntry;if(s.skipPersist){await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!s.injectRecall}});return}await r.appendTranscriptEntry(c),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o,{eventDispatcher:i})}}function tg(e){let t=!1,n=[];for(let r of e)r&&(r.skipPersist&&(t=!0),typeof r.injectRecall==`string`&&r.injectRecall.trim().length>0&&n.push(r.injectRecall.trim()));return{skipPersist:t,injectRecall:n.length>0?n.join(`
136
+ `;function Yh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Xh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Zh(e)&&n.delete(e);return{...t,headers:n}}function Zh(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function Qh(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function $h(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function eg(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,autoSkillCategories:u,effectivePromptText:f,pluginTools:p,pluginSkillDirs:h,skillsLoadPaths:g,presetSystemPrompt:_},dependencies:{registry:v,spawnFn:y,createModel:b,abortSignal:x}}=e,S=t.autoSkills?.load?.enabled===!0,C=t.agentPolicy?.activeAgent,w=t.channel===`CRON`,T=w?[]:await m(t.dataDir,n,X(t)),E={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},D=await Jd({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=w?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Yd({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:x,hooks:r,hookCtx:i,contextManager:D,dataDir:t.dataDir,sessionId:n});await rg({sessionId:n,historyResult:O,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let k=t.subagentContext?.depth??0,A=d(t.dataDir,n,X(t)),j=Ir([...qm(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:A,registry:v,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:g,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:h,skillsLoadPaths:g,reportSkillUsed:async e=>{await o.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:o,spawnFn:y,baseEnv:t.env}),...p],C),M=j.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),N={};for(let e of j){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||N[t]||(N[t]=n)}let ee=t.messaging?.enabled??t.channel!==`CRON`,P=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],F=vh({dataDir:t.dataDir,projectDir:t.projectDir,skills:Fr(l,C),autoSkillCategories:S?u:[],contextFiles:s,toolNames:M,toolSummaries:N,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:ee,channels:P},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:vt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});F=await tg({systemPrompt:F,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let te=await r.dispatch(`before_prompt_build`,{prompt:f},i,{eventDispatcher:o});for(let e of te)e&&(e.systemPrompt&&(F=e.systemPrompt),e.prependContext&&(F=`${e.prependContext}\n\n${F}`));await r.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:F},i,{eventDispatcher:o});let ne=Wh(Sh(j,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},Qs),I=C?.model??t.llm.model,L=await r.dispatch(`before_model_resolve`,{prompt:f},i,{eventDispatcher:o});for(let e of L)e&&e.modelOverride&&(I=e.modelOverride);let R=b({...t.llm,model:I},n,t.messageId,t.channel),z=new et({initialState:{systemPrompt:F,model:R,tools:ne,messages:[]},getApiKey:e=>t.llm.apiKey,streamFn:Gh({})});return O.messages.length>0&&z.replaceMessages(O.messages),{agent:z,resolvedModelId:I,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:a.workspaceDir}}async function tg(e){if((await f(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})).length<=8)return e.systemPrompt;let t=`Older CRON execution records for this session are stored outside the main transcript at ${j(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})}. The main transcript keeps only the latest 8 CRON summaries. Read that jsonl file explicitly if older CRON outcomes matter.`;return`${e.systemPrompt}\n\n${t}`}async function ng(e){let{session:t,runtime:n,effectivePromptText:r,dependencies:i}=e,{runParams:a,sessionId:o,hookRegistry:s,hookContext:c,runContext:l,eventDispatcher:u}=t,{abortSignal:d}=i;if(a.channel===`CRON`)return{status:`skipped`,reason:`CRON runs do not persist transcript history.`};let f=await il({entries:await m(a.dataDir,o,X(a)),contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.flashModel??a.llm.model},instructions:va,signal:d,hooks:s,hookCtx:c});if(f.status!==`compacted`)return{status:`skipped`,reason:f.reason};await rg({sessionId:o,historyResult:{messages:[],priorSummary:void 0,compactionEntry:f.entry,stats:{originalCount:f.keptCount+f.droppedCount,keptCount:f.keptCount,estimatedTokens:f.estimatedTokens,compacted:!0},compactionEvents:[{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`,estimatedTokensFreed:Math.max(0,f.droppedCount),affectedEntries:f.droppedCount,snapshotVersion:2}]},runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),await u.dispatchProgress(o,{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`});let p={model:a.llm.model,api:a.llm.apiFormat??`openai-completions`},h=await Yd({entries:await m(a.dataDir,o,X(a)),modelInfo:p,contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.model,flashModel:a.llm.flashModel},historyLimit:a.historyLimit,topicSegmentation:a.topicSegmentation,channel:a.channel,isSubagent:!!a.subagentContext,compactionEnabled:!0,pendingUserMessage:r,signal:d,hooks:s,hookCtx:c,contextManager:n.contextManager,dataDir:a.dataDir,sessionId:o});return await rg({sessionId:o,historyResult:h,runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),n.historyResult=h,n.historyMessages=h.messages,n.agent.replaceMessages(h.messages),{status:`compacted`}}async function rg(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount,s=ig(await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i})),c=s.injectRecall?{...n.compactionEntry,content:`${s.injectRecall.trim()}\n\n${n.compactionEntry.content}`}:n.compactionEntry;if(s.skipPersist){await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!s.injectRecall}});return}await r.appendTranscriptEntry(c),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o,{eventDispatcher:i})}}function ig(e){let t=!1,n=[];for(let r of e)r&&(r.skipPersist&&(t=!0),typeof r.injectRecall==`string`&&r.injectRecall.trim().length>0&&n.push(r.injectRecall.trim()));return{skipPersist:t,injectRecall:n.length>0?n.join(`
137
137
 
138
- `):void 0}}async function ng(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!c?.aborted&&n.needsAnnounce(r)&&d<10;){d++,q.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){q.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}q.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:d,completedCount:e.length,runIds:e.map(e=>e.runId).join(`,`),statuses:e.map(e=>e.status).join(`,`)});for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=rg(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Fa({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,onTurnRecordProduced:async(e,t)=>{e&&await u(e);for(let e of t)await u(e)}});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),n.markAnnounced(e.map(e=>e.runId));let v={sessionId:r,announceRound:d,completedCount:e.length,inputTokens:_.inputTokens,outputTokens:_.outputTokens,hasError:!!_.error,error:_.error,responseTextLength:_.text.length};_.error?q.warn(`subagent announce round completed with error`,v):q.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&q.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function rg(e){if(e.length===1){let t=e[0];return Cm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Cm({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
138
+ `):void 0}}async function ag(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!c?.aborted&&n.needsAnnounce(r)&&d<10;){d++,q.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){q.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}q.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:d,completedCount:e.length,runIds:e.map(e=>e.runId).join(`,`),statuses:e.map(e=>e.status).join(`,`)});for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=og(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Fa({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,onTurnRecordProduced:async(e,t)=>{e&&await u(e);for(let e of t)await u(e)}});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),n.markAnnounced(e.map(e=>e.runId));let v={sessionId:r,announceRound:d,completedCount:e.length,inputTokens:_.inputTokens,outputTokens:_.outputTokens,hasError:!!_.error,error:_.error,responseTextLength:_.text.length};_.error?q.warn(`subagent announce round completed with error`,v):q.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&q.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function og(e){if(e.length===1){let t=e[0];return Em({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Em({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
139
139
 
140
140
  ---
141
141
 
142
- `)}`}function ig(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ag(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function og(){let e=vt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function sg(e){let t=e.trim(),n=og();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?H.join(n,t.slice(2)):void 0:H.resolve(t)}const cg=new St({allErrors:!0,strict:!1}),lg=new Map;function ug(e,t){let n=lg.get(t);if(n)return n;let r=cg.compile(e);return lg.set(t,r),r}function dg(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ug(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function fg(e){let t=ag(e?.allow),n=ag(e?.deny),r=ag(e?.load?.paths),i=e?.entries??{},a=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),entries:i,slots:a}}function pg(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=dg({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function mg(e){try{return U.realpathSync(e)}catch{return null}}function hg(e){try{return U.statSync(e)}catch{return null}}function gg(e,t){let n=H.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!H.isAbsolute(n)}function _g(e){return`0o${e.toString(8).padStart(3,`0`)}`}const vg=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),yg=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function bg(e){let t=H.join(e,`package.json`);if(U.existsSync(t))try{let e=JSON.parse(U.readFileSync(t,`utf-8`));return ig(e)?e:void 0}catch{return}}function xg(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function Sg(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Cg(e){let t=mg(e.source),n=mg(e.rootDir);return!t||!n||gg(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function wg(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=H.resolve(r);if(n.has(t))continue;n.add(t);let i=hg(r);if(!i)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let a=i.mode&511;if(a&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:a};if(e.origin!==`bundled`&&e.uid!==null&&typeof i.uid==`number`&&i.uid!==e.uid&&i.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:i.uid,expectedUid:e.uid}}return null}function Tg(e){return Cg({source:e.source,rootDir:e.rootDir})||wg({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Sg(e.ownershipUid)})}function Eg(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${_g(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Dg(e){let t=Tg({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Eg(t),source:e.source}),!0):!1}function Og(e){return H.basename(e,H.extname(e))}function kg(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function Ag(e){for(let t of yg){let n=H.join(e,t);if(U.existsSync(n))return n}return null}function jg(e){let t;try{t=U.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=H.join(e.rootDir,n.name);if(n.isFile()){if(!vg.has(H.extname(n.name)))continue;let r=H.dirname(t);if(Dg({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(kg({idHint:Og(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=bg(t),i=xg(r);if(i.status===`ok`){for(let n of i.entries){let i=H.resolve(t,n);if(!gg(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!U.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!vg.has(H.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Dg({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Og(i)}`:Og(i);e.candidates.push(kg({idHint:o,source:i,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let a=Ag(t);a&&(Dg({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(kg({idHint:H.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Mg(e){return e?e.map(sg).filter(e=>typeof e==`string`&&e.length>0):[]}function Ng(){let e=og();if(e)return H.join(e,`.aimax`,`extensions`)}function Pg(e){return H.join(e,`.aimax`,`extensions`)}function Fg(e){return H.join(e,`.aimax`,`extensions`)}function Ig(e={}){let t=[],n=[],r=Mg(e.extraPaths);for(let i of r){if(!U.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=hg(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!vg.has(H.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=H.dirname(i);if(Dg({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(kg({idHint:Og(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&jg({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?jg({rootDir:Pg(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&jg({rootDir:Fg(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Ng();return i?jg({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&jg({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Lg(e){let t=e.rejectHardlinks??!0,n=mg(e.rootPath),r=mg(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!gg(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=U.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:U.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Rg=`aimax.plugin.json`,zg=[Rg];function Bg(e){for(let t of zg){let n=H.join(e,t);if(U.existsSync(n))return n}return H.join(e,Rg)}function Vg(e,t=!0){let n=Bg(e),r=Lg({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(U.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{U.closeSync(r.fd)}if(!ig(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=ig(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let s=typeof i.kind==`string`?i.kind:void 0,c=typeof i.name==`string`?i.name.trim():void 0,l=typeof i.description==`string`?i.description.trim():void 0,u=typeof i.version==`string`?i.version.trim():void 0,d=ag(i.skills),f;return ig(i.uiHints)&&(f=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:s,name:c,description:l,version:u,skills:d,uiHints:f},manifestPath:n}}function Hg(e){let t=new Map,n=[];for(let r of e){let e=Vg(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let Ug=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Wg(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Ug.ERROR){q.error(i);return}if(e===Ug.WARN){q.warn(i);return}q.info(i)}function Gg(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Wg(Ug.INFO,e.pluginId,t,n),warn:n=>Wg(Ug.WARN,e.pluginId,t,n),error:n=>Wg(Ug.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}function Kg(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function qg(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function Jg(e){let t=[...e.registry.diagnostics],n=new _h,r=new qr,i=[],a=[],o=e.runtime?.llm?li({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Yg(e.runtime?.llmAllowlist),c=Ct(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Kg({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=qg({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f;try{f=c(l.source)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let p=f&&typeof f==`object`&&`default`in f?f.default:f,m=typeof p==`function`?p:p&&typeof p==`object`&&typeof p.register==`function`?p.register:void 0;if(!m){d.status=`error`,d.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let h=Gg({pluginId:l.id,env:e.runtime?.env}),g=e.plugins.entries[l.id]?.config,_={id:l.id,source:l.source,rootDir:l.rootDir,config:g,runtime:h,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Xg(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);se({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);he({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=H.isAbsolute(e)?e:H.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Kr(l.id)};try{m(_)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=H.isAbsolute(e)?e:H.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Yg(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Xg(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Zg(e={}){let t=fg(e.config),n=Ig({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Hg(n.candidates),i=pg({config:t,registry:r}),a=Jg({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t}}function Qg(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Zg({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new qr,pluginSkillDirs:o?.registry.skills??[],pluginTools:[...o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...o?.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function $g(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Fm(t),o=n,s=!o,c=X(t);o?(await r(t.dataDir,o,c)||(s=!0),await g(t.dataDir,o,c)):o=await C(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel},u=Qg({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await Im({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:i,hookRegistry:d});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:d,pluginContext:u,runContext:f,start:e=>lc({sessionId:o,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:i,...e})}}function e_(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function t_(e){if(!(e instanceof Error))return{errorValue:e_(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=e_(n[e]));return t}async function n_(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...t_(e.error)}})}function r_(e,t,n){return H.join(d(e,t,n),`pending-ui-tool.json`)}async function i_(e,t,n,r){let i=d(e,t,r);await V.mkdir(i,{recursive:!0}),await a(r_(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function a_(e,t,n){let r=await l(r_(e,t,n));return r===null?null:JSON.parse(r)}async function o_(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await i_(e,t,a,r),a}async function s_(e,t,n,r,i){let a=await a_(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await i_(e,t,o,i),o}async function c_(e,t,n){try{await V.unlink(r_(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function l_(e,t,n,r){let i=await z(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function u_(e,t,n,r,i,a){let o=await z(e,t,{storeName:a?.storeName});await l_(e,t,n,a);let s=await Tt(e,t,n,r,a);return s.goal&&await pl(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function d_(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ke(t))}async function f_(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=wi();if(i=await Ti(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(bi(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=p_(i),s=i&&typeof i==`object`?i.details:void 0,c=s&&typeof s==`object`?s.toolResultRef:void 0;return await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_end`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs,output:o,isError:a}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:o,isError:a,...c?{toolResultRef:c}:{},timestamp:new Date().toISOString()}),{text:o,error:a?o:void 0}}function p_(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}const m_=2e4,h_=15e4,g_=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function __(e){return H.join(e,`.aimax`)}async function v_(e){let t=__(e),n=[];for(let e of g_){let r=H.join(t,e);try{let t=await V.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await V.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function y_(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
142
+ `)}`}function sg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cg(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function lg(){let e=vt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function ug(e){let t=e.trim(),n=lg();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?H.join(n,t.slice(2)):void 0:H.resolve(t)}const dg=new St({allErrors:!0,strict:!1}),fg=new Map;function pg(e,t){let n=fg.get(t);if(n)return n;let r=dg.compile(e);return fg.set(t,r),r}function mg(e){let t=e.cacheKey??JSON.stringify(e.schema),n=pg(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function hg(e){let t=cg(e?.allow),n=cg(e?.deny),r=cg(e?.load?.paths),i=e?.entries??{},a=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),entries:i,slots:a}}function gg(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=mg({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function _g(e){try{return U.realpathSync(e)}catch{return null}}function vg(e){try{return U.statSync(e)}catch{return null}}function yg(e,t){let n=H.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!H.isAbsolute(n)}function bg(e){return`0o${e.toString(8).padStart(3,`0`)}`}const xg=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Sg=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Cg(e){let t=H.join(e,`package.json`);if(U.existsSync(t))try{let e=JSON.parse(U.readFileSync(t,`utf-8`));return sg(e)?e:void 0}catch{return}}function wg(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function Tg(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Eg(e){let t=_g(e.source),n=_g(e.rootDir);return!t||!n||yg(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Dg(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=H.resolve(r);if(n.has(t))continue;n.add(t);let i=vg(r);if(!i)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let a=i.mode&511;if(a&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:a};if(e.origin!==`bundled`&&e.uid!==null&&typeof i.uid==`number`&&i.uid!==e.uid&&i.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:i.uid,expectedUid:e.uid}}return null}function Og(e){return Eg({source:e.source,rootDir:e.rootDir})||Dg({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Tg(e.ownershipUid)})}function kg(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${bg(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Ag(e){let t=Og({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:kg(t),source:e.source}),!0):!1}function jg(e){return H.basename(e,H.extname(e))}function Mg(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function Ng(e){for(let t of Sg){let n=H.join(e,t);if(U.existsSync(n))return n}return null}function Pg(e){let t;try{t=U.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=H.join(e.rootDir,n.name);if(n.isFile()){if(!xg.has(H.extname(n.name)))continue;let r=H.dirname(t);if(Ag({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Mg({idHint:jg(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Cg(t),i=wg(r);if(i.status===`ok`){for(let n of i.entries){let i=H.resolve(t,n);if(!yg(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!U.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!xg.has(H.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Ag({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${jg(i)}`:jg(i);e.candidates.push(Mg({idHint:o,source:i,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let a=Ng(t);a&&(Ag({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Mg({idHint:H.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Fg(e){return e?e.map(ug).filter(e=>typeof e==`string`&&e.length>0):[]}function Ig(){let e=lg();if(e)return H.join(e,`.aimax`,`extensions`)}function Lg(e){return H.join(e,`.aimax`,`extensions`)}function Rg(e){return H.join(e,`.aimax`,`extensions`)}function zg(e={}){let t=[],n=[],r=Fg(e.extraPaths);for(let i of r){if(!U.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=vg(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!xg.has(H.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=H.dirname(i);if(Ag({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Mg({idHint:jg(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Pg({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Pg({rootDir:Lg(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Pg({rootDir:Rg(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Ig();return i?Pg({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&Pg({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Bg(e){let t=e.rejectHardlinks??!0,n=_g(e.rootPath),r=_g(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!yg(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=U.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:U.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Vg=`aimax.plugin.json`,Hg=[Vg];function Ug(e){for(let t of Hg){let n=H.join(e,t);if(U.existsSync(n))return n}return H.join(e,Vg)}function Wg(e,t=!0){let n=Ug(e),r=Bg({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(U.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{U.closeSync(r.fd)}if(!sg(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=sg(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let s=typeof i.kind==`string`?i.kind:void 0,c=typeof i.name==`string`?i.name.trim():void 0,l=typeof i.description==`string`?i.description.trim():void 0,u=typeof i.version==`string`?i.version.trim():void 0,d=cg(i.skills),f;return sg(i.uiHints)&&(f=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:s,name:c,description:l,version:u,skills:d,uiHints:f},manifestPath:n}}function Gg(e){let t=new Map,n=[];for(let r of e){let e=Wg(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let Kg=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function qg(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Kg.ERROR){q.error(i);return}if(e===Kg.WARN){q.warn(i);return}q.info(i)}function Jg(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>qg(Kg.INFO,e.pluginId,t,n),warn:n=>qg(Kg.WARN,e.pluginId,t,n),error:n=>qg(Kg.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}function Yg(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function Xg(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function Zg(e){let t=[...e.registry.diagnostics],n=new bh,r=new qr,i=[],a=[],o=e.runtime?.llm?li({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Qg(e.runtime?.llmAllowlist),c=Ct(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Yg({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Xg({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f;try{f=c(l.source)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let p=f&&typeof f==`object`&&`default`in f?f.default:f,m=typeof p==`function`?p:p&&typeof p==`object`&&typeof p.register==`function`?p.register:void 0;if(!m){d.status=`error`,d.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let h=Jg({pluginId:l.id,env:e.runtime?.env}),g=e.plugins.entries[l.id]?.config,_={id:l.id,source:l.source,rootDir:l.rootDir,config:g,runtime:h,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!$g(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);se({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);he({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=H.isAbsolute(e)?e:H.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Kr(l.id)};try{m(_)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=H.isAbsolute(e)?e:H.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Qg(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function $g(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function e_(e={}){let t=hg(e.config),n=zg({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Gg(n.candidates),i=gg({config:t,registry:r}),a=Zg({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t}}function t_(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?e_({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new qr,pluginSkillDirs:o?.registry.skills??[],pluginTools:[...o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...o?.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function n_(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Rm(t),o=n,s=!o,c=X(t);o?(await r(t.dataDir,o,c)||(s=!0),await g(t.dataDir,o,c)):o=await C(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel},u=t_({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await zm({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:i,hookRegistry:d});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:d,pluginContext:u,runContext:f,start:e=>lc({sessionId:o,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:i,...e})}}function r_(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function i_(e){if(!(e instanceof Error))return{errorValue:r_(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=r_(n[e]));return t}async function a_(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...i_(e.error)}})}function o_(e,t,n){return H.join(d(e,t,n),`pending-ui-tool.json`)}async function s_(e,t,n,r){let i=d(e,t,r);await V.mkdir(i,{recursive:!0}),await a(o_(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function c_(e,t,n){let r=await l(o_(e,t,n));return r===null?null:JSON.parse(r)}async function l_(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await s_(e,t,a,r),a}async function u_(e,t,n,r,i){let a=await c_(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await s_(e,t,o,i),o}async function d_(e,t,n){try{await V.unlink(o_(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function f_(e,t,n,r){let i=await z(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function p_(e,t,n,r,i,a){let o=await z(e,t,{storeName:a?.storeName});await f_(e,t,n,a);let s=await Tt(e,t,n,r,a);return s.goal&&await pl(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function m_(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ke(t))}async function h_(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=wi();if(i=await Ti(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(bi(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=g_(i),s=i&&typeof i==`object`?i.details:void 0,c=s&&typeof s==`object`?s.toolResultRef:void 0;return await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_end`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs,output:o,isError:a}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:o,isError:a,...c?{toolResultRef:c}:{},timestamp:new Date().toISOString()}),{text:o,error:a?o:void 0}}function g_(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}const __=2e4,v_=15e4,y_=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function b_(e){return H.join(e,`.aimax`)}async function x_(e){let t=b_(e),n=[];for(let e of y_){let r=H.join(t,e);try{let t=await V.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await V.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function S_(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
143
143
  `),s].join(`
144
- `),truncated:!0,originalLength:r.length}}function b_(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function x_(e,t){let n=t?.maxChars??m_,r=Math.max(1,t?.totalMaxChars??Math.max(n,h_)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=b_(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=y_(a.content??``,a.name,e),l=b_(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const S_=`You are a personal assistant running inside AiMax.`;async function C_(e){try{return{presetSystemPrompt:$e(await V.readFile(e,`utf-8`)).content.trim()||S_}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:S_};throw e}}async function w_(){return C_(`/aimax_pvc/system_prompt.md`)}async function T_(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await v_(t.dataDir),o=[],s=x_(a,{warn:e=>o.push(e)}),c=await w_();await i.dispatchDiagnostic(n,{level:o.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length}}),q.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await am(t.dataDir,r.pluginSkillDirs,l),d=await kr({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),q.info(`skills loaded`,{sessionId:n,skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length}),await i.dispatchDiagnostic(n,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,agents:d.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),q.info(`custom agents loaded`,{sessionId:n,agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,requestedAgentName:m.requestedAgentName}),{contextFiles:s,bootstrapWarnings:o,skills:u,autoSkillCategories:await E_({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function E_(e){if(!e.enabled)return[];try{let t=await new K({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var D_=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const O_=`crons`;function k_(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:si(e.message)}}async function A_(e,t){oi(e.dataDir),tc();let n=Date.now(),r=new ci(e),i=ml(e);q.info(`agent invocation prepared`,{requestedSessionId:i.requestedSessionId,previousSessionId:i.previousSessionId,inputMode:i.inputMode,hasSlashCommand:!!i.slashCommandSource,resetAction:i.resetCommand?.action,resetShortCircuit:i.resetShortCircuit,transcriptLength:i.transcriptMessage.length,messageForRunLength:i.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await $g({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,h=c.pluginContext,g=c.runContext,_=(await m(e.dataDir,l,{storeName:e.sessionStoreName})).length;q.info(`agent run started`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:u,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),q.info(u?`session created`:`session resumed`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await N(e.dataDir,Lm({sessionId:l,title:cc(a),channel:e.channel}),X(e)),e.pendingGoal&&await L(e.dataDir,l,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`}),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(o=await g.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let v=new AbortController;e.abortSignal?.aborted?v.abort():e.abortSignal?.addEventListener(`abort`,()=>v.abort());let y=await T_({runParams:e,sessionId:l,pluginContext:h,eventDispatcher:r}),b=e=>g.appendTranscriptEntry(e),x=await gl({invocation:i,skills:y.skills,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(x.kind===`completed`)return q.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!x.result.error,paused:!!x.result.paused,uiToolPending:!!x.result.uiToolPending,textLength:x.result.text.length}),x.result;let S=x.effectivePrompt;a=x.transcriptMessage;let C=typeof S==`string`?S:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof S==`string`?`string`:`messages`,transcriptLength:a.length}}),q.info(`invocation resolved`,{sessionId:l,promptType:typeof S==`string`?`string`:`messages`,transcriptLength:a.length});let w=await Zh({session:{runParams:y.runParamsWithAgentPolicy,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},runtimeInputs:{contextFiles:y.contextFiles,bootstrapWarnings:y.bootstrapWarnings,skills:y.skills,autoSkillCategories:y.autoSkillCategories,effectivePromptText:C,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:y.skillsLoadPaths,presetSystemPrompt:y.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>A_(e,new Xs),createModel:Sr,abortSignal:v.signal}}),T=w.agent,E=w.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:E,historyMessageCount:w.historyMessages.length,pluginToolCount:h.pluginTools.length}}),q.info(`agent runtime created`,{sessionId:l,modelId:E,historyMessageCount:w.historyMessages.length,pluginToolCount:h.pluginTools.length});let D=I_(e.timeoutMs),O=!1,k=setTimeout(()=>{O=!0,v.abort(),T.abort(),r.dispatchDiagnostic(l,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:D}}),q.warn(`agent run timed out`,{sessionId:l,timeoutMs:D})},D);v.signal.addEventListener(`abort`,()=>T.abort());let A=new D_,j=``,M,ee=!1,P=new wt;await l_(e.dataDir,l,P,{storeName:e.sessionStoreName});let F=new ya,te={runParams:y.runParamsWithAgentPolicy,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},ne={registry:t,spawnFn:e=>A_(e,new Xs),createModel:Sr,abortSignal:v.signal},I=(e,t,n)=>({turnKind:e,budget:F,reloadHistory:()=>$h({session:te,runtime:n,effectivePromptText:t,dependencies:ne}),onPhase:async(e,t)=>{await r.dispatchDiagnostic(l,{level:e.includes(`failed`)||e.includes(`skipped`)?`warn`:`info`,scope:`runner`,phase:e,message:e.replace(/_/g,` `),details:t})}});try{if(d_(e)){let t=await f_({params:e,agent:T,sessionId:l,eventDispatcher:r,appendEntry:b,abortSignal:v.signal});return j=t.text,fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(a);ee=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let i=await zt(e.dataDir,l,S,{storeName:e.sessionStoreName});q.info(`first agent turn started`,{sessionId:l,modelId:E});let s=typeof i.prompt==`string`?i.prompt:C,c=await Fa({agent:T,message:i.prompt,continueFromHistory:!!e.uiToolResume,sessionId:l,channel:e.channel,modelId:E,historyMessages:w.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,retry:e.llmRetry,contextLimitRecovery:I(`first`,s,w),onTurnRecordProduced:async(e,t)=>{e&&await b(e);for(let e of t)await b(e)}});j=c.text,A.add(c.inputTokens,c.outputTokens),c.error&&(M=c.error);let d=!!c.contextLimitRecoverySucceeded;i.hadObjectiveUpdatedSteering&&!c.error&&await Bt(e.dataDir,l,{storeName:e.sessionStoreName}),await r.dispatchDiagnostic(l,{level:c.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let m={sessionId:l,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?q.warn(`first agent turn completed with error`,m):q.info(`first agent turn completed`,m);let h=await u_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`});h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),q.info(`announce loop started`,{sessionId:l});let _=await ng({agent:T,registry:t,sessionId:l,resolvedModelId:E,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,retry:e.llmRetry,appendEntry:b});if(_.text&&(j=_.text),A.add(_.inputTokens,_.outputTokens),_.error&&!M&&(M=_.error),await r.dispatchDiagnostic(l,{level:_.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens}}),h=await u_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`}),h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Pt()){let n=new Nt;n.reset(),c.error&&!d&&(n.lastTurnHadOutput=!1);let i=!0,a=Ue;for(;i&&n.continuationCount<a&&!v.signal.aborted;)if(i=await Lt({agent:T,dataDir:e.dataDir,sessionId:l,sessionStoreName:e.sessionStoreName,state:n,accounting:P,abortSignal:v.signal,executeTurn:async t=>{let n=await Fa({agent:T,message:t,continueFromHistory:!1,sessionId:l,channel:e.channel,modelId:E,historyMessages:w.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,contextLimitRecovery:I(`continuation`,t,w),onTurnRecordProduced:async(e,t)=>{await Rt(b,e,t)}});A.add(n.inputTokens,n.outputTokens),j=n.text||j,n.error&&!M&&(M=n.error);let i=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:i}},flushAccountingAfterTurn:async()=>{(await u_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),i){let e=await ng({agent:T,registry:t,sessionId:l,resolvedModelId:E,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,appendEntry:b});A.add(e.inputTokens,e.outputTokens),e.text&&(j=e.text),e.error&&!M&&(M=e.error)}}let y={sessionId:l,hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens};_.error?q.warn(`announce loop completed with error`,y):q.info(`announce loop completed`,y)}catch(t){if(bi(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await be(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),q.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={...A.snapshot()};return await j_({runtime:w,resolvedModelId:E,usage:c,currentUserEntryCoveredByUsage:ee}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Si(t)){let i=t,o=i.request.outputSchema.properties??{};await o_(e.dataDir,l,i.request,X(e)),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length}}),q.info(`agent paused for UI tool input`,{sessionId:l,requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length});let s={...A.snapshot()};return await j_({runtime:w,resolvedModelId:E,usage:s,currentUserEntryCoveredByUsage:ee}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j||``,usage:s,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}if(O&&L_(t))M=`Run timed out after ${D}ms`;else throw await n_({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),q.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{clearTimeout(k);try{await u_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}P.clearActiveGoal(),$s(l),g.stop()}let R=A.snapshot();O&&(M=`Run timed out after ${D}ms`),await r.dispatchDiagnostic(l,{level:M?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:R.input,outputTokens:R.output,totalTokens:R.total,hasError:!!M,error:M}});let z={sessionId:l,durationMs:Date.now()-n,inputTokens:R.input,outputTokens:R.output,totalTokens:R.total,hasError:!!M,error:M};return M?q.warn(`agent run completed with error`,z):q.info(`agent run completed`,z),await j_({runtime:w,resolvedModelId:E,usage:R,currentUserEntryCoveredByUsage:ee}),await ks({sessionId:l,runParams:y.runParamsWithAgentPolicy,eventDispatcher:r,transcriptStartIndex:_,result:{text:j,usage:R,durationMs:Date.now()-n,error:M}}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:R,error:M})}async function j_(e){let{runtime:t,resolvedModelId:n,usage:r,currentUserEntryCoveredByUsage:i}=e;r.input<=0&&r.total<=0||await t.contextManager.recordModelUsage({model:n,inputTokens:r.input,outputTokens:r.output,totalTokens:r.total,coveredTranscriptEntryCount:t.usageBaselineTranscriptEntryCount+(i?1:0)})}async function M_(e){oi(e.dataDir);let n=Date.now(),i=new ci(e),a=ml(e),o=a.transcriptMessage.trim()||`CRON task`,s=e.sessionStoreName;q.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:s,...k_(e)});let c=a.requestedSessionId,l=!c;c?(await r(e.dataDir,c,{storeName:s})||(l=!0),await g(e.dataDir,c,{storeName:s})):c=await C(e.dataDir,e.channel,{storeName:s}),l&&await N(e.dataDir,Lm({sessionId:c,title:cc(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:O_});await i.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:u,task:o}),q.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:u,taskLength:o.length,taskPreview:si(o)});let d={...e,sessionId:u,sessionStoreName:O_,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await A_(d,new Xs),f.error&&(m=`error`)}catch(t){let r=t instanceof Error?t.message:String(t);f={sessionId:u,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:h(e.dataDir,u,{storeName:O_}),toolResultsDir:S(e.dataDir,u,{storeName:O_})}},m=`error`,q.error(`cron child run failed`,{parentSessionId:c,childSessionId:u,error:r})}await i.dispatchProgress(c,{type:`subagent_complete`,childSessionId:u,task:o,status:m}),q.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let _=Cm({task:o,status:m,result:f.text,error:f.error}),v=new Date().toISOString();await p(e.dataDir,c,{role:`assistant`,content:_,timestamp:v,source:`cron`},{storeName:s});let y={task:o,status:m,content:_,childSessionId:u,createdAt:v};return await b(e.dataDir,c,y,{storeName:s}),await t(e.dataDir,c,e=>N_(e,8),{storeName:s}),await x(e.dataDir,c,{},{storeName:s}),{...f,sessionId:c,context:{snapshotPath:h(e.dataDir,c,{storeName:s}),toolResultsDir:S(e.dataDir,c,{storeName:s})}}}function N_(e,t){if(t<=0)return e.filter(e=>!P_(e));let n=e.reduce((e,t,n)=>(P_(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!P_(e)||r.has(t))}function P_(e){return`source`in e&&e.source===`cron`}async function F_(e,t){if(oi(e.dataDir),q.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...k_(e)}),e.channel===`CRON`&&!e.subagentContext)return M_(e);let n=t??new Xs;try{return await A_(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:t_(t)}),q.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}function I_(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:6e5}function L_(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const R_={"AGENTS.md":`---
144
+ `),truncated:!0,originalLength:r.length}}function C_(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function w_(e,t){let n=t?.maxChars??__,r=Math.max(1,t?.totalMaxChars??Math.max(n,v_)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=C_(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=S_(a.content??``,a.name,e),l=C_(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const T_=`You are a personal assistant running inside AiMax.`;async function E_(e){try{return{presetSystemPrompt:$e(await V.readFile(e,`utf-8`)).content.trim()||T_}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:T_};throw e}}async function D_(){return E_(`/aimax_pvc/system_prompt.md`)}async function O_(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await x_(t.dataDir),o=[],s=w_(a,{warn:e=>o.push(e)}),c=await D_();await i.dispatchDiagnostic(n,{level:o.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length}}),q.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await cm(t.dataDir,r.pluginSkillDirs,l),d=await kr({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),q.info(`skills loaded`,{sessionId:n,skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length}),await i.dispatchDiagnostic(n,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,agents:d.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),q.info(`custom agents loaded`,{sessionId:n,agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,requestedAgentName:m.requestedAgentName}),{contextFiles:s,bootstrapWarnings:o,skills:u,autoSkillCategories:await k_({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function k_(e){if(!e.enabled)return[];try{let t=await new K({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var A_=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const j_=`crons`;function M_(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:si(e.message)}}async function N_(e,t){oi(e.dataDir),tc();let n=Date.now(),r=new ci(e),i=ml(e);q.info(`agent invocation prepared`,{requestedSessionId:i.requestedSessionId,previousSessionId:i.previousSessionId,inputMode:i.inputMode,hasSlashCommand:!!i.slashCommandSource,resetAction:i.resetCommand?.action,resetShortCircuit:i.resetShortCircuit,transcriptLength:i.transcriptMessage.length,messageForRunLength:i.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await n_({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,h=c.pluginContext,g=c.runContext,_=(await m(e.dataDir,l,{storeName:e.sessionStoreName})).length;q.info(`agent run started`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:u,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),q.info(u?`session created`:`session resumed`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await N(e.dataDir,Bm({sessionId:l,title:cc(a),channel:e.channel}),X(e)),e.pendingGoal&&await L(e.dataDir,l,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`}),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(o=await g.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let v=new AbortController;e.abortSignal?.aborted?v.abort():e.abortSignal?.addEventListener(`abort`,()=>v.abort());let y=await O_({runParams:e,sessionId:l,pluginContext:h,eventDispatcher:r}),b=e=>g.appendTranscriptEntry(e),x=await gl({invocation:i,skills:y.skills,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(x.kind===`completed`)return q.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!x.result.error,paused:!!x.result.paused,uiToolPending:!!x.result.uiToolPending,textLength:x.result.text.length}),x.result;let S=x.effectivePrompt;a=x.transcriptMessage;let C=typeof S==`string`?S:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof S==`string`?`string`:`messages`,transcriptLength:a.length}}),q.info(`invocation resolved`,{sessionId:l,promptType:typeof S==`string`?`string`:`messages`,transcriptLength:a.length});let w=await eg({session:{runParams:y.runParamsWithAgentPolicy,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},runtimeInputs:{contextFiles:y.contextFiles,bootstrapWarnings:y.bootstrapWarnings,skills:y.skills,autoSkillCategories:y.autoSkillCategories,effectivePromptText:C,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:y.skillsLoadPaths,presetSystemPrompt:y.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>N_(e,new Xs),createModel:Sr,abortSignal:v.signal}}),T=w.agent,E=w.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:E,historyMessageCount:w.historyMessages.length,pluginToolCount:h.pluginTools.length}}),q.info(`agent runtime created`,{sessionId:l,modelId:E,historyMessageCount:w.historyMessages.length,pluginToolCount:h.pluginTools.length});let D=z_(e.timeoutMs),O=!1,k=D===void 0?void 0:setTimeout(()=>{O=!0,v.abort(),T.abort(),r.dispatchDiagnostic(l,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:D}}),q.warn(`agent run timed out`,{sessionId:l,timeoutMs:D})},D);v.signal.addEventListener(`abort`,()=>T.abort());let A=new A_,j=``,M,ee=!1,P=new wt;await f_(e.dataDir,l,P,{storeName:e.sessionStoreName});let F=new ya,te={runParams:y.runParamsWithAgentPolicy,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},ne={registry:t,spawnFn:e=>N_(e,new Xs),createModel:Sr,abortSignal:v.signal},I=(e,t,n)=>({turnKind:e,budget:F,reloadHistory:()=>ng({session:te,runtime:n,effectivePromptText:t,dependencies:ne}),onPhase:async(e,t)=>{await r.dispatchDiagnostic(l,{level:e.includes(`failed`)||e.includes(`skipped`)?`warn`:`info`,scope:`runner`,phase:e,message:e.replace(/_/g,` `),details:t})}});try{if(m_(e)){let t=await h_({params:e,agent:T,sessionId:l,eventDispatcher:r,appendEntry:b,abortSignal:v.signal});return j=t.text,fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(a);ee=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let i=await zt(e.dataDir,l,S,{storeName:e.sessionStoreName});q.info(`first agent turn started`,{sessionId:l,modelId:E});let s=typeof i.prompt==`string`?i.prompt:C,c=await Fa({agent:T,message:i.prompt,continueFromHistory:!!e.uiToolResume,sessionId:l,channel:e.channel,modelId:E,historyMessages:w.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,retry:e.llmRetry,contextLimitRecovery:I(`first`,s,w),onTurnRecordProduced:async(e,t)=>{e&&await b(e);for(let e of t)await b(e)}});j=c.text,A.add(c.inputTokens,c.outputTokens),c.error&&(M=c.error);let d=!!c.contextLimitRecoverySucceeded;i.hadObjectiveUpdatedSteering&&!c.error&&await Bt(e.dataDir,l,{storeName:e.sessionStoreName}),await r.dispatchDiagnostic(l,{level:c.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let m={sessionId:l,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?q.warn(`first agent turn completed with error`,m):q.info(`first agent turn completed`,m);let h=await p_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`});h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),q.info(`announce loop started`,{sessionId:l});let _=await ag({agent:T,registry:t,sessionId:l,resolvedModelId:E,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,retry:e.llmRetry,appendEntry:b});if(_.text&&(j=_.text),A.add(_.inputTokens,_.outputTokens),_.error&&!M&&(M=_.error),await r.dispatchDiagnostic(l,{level:_.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens}}),h=await p_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`}),h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Pt()){let n=new Nt;n.reset(),c.error&&!d&&(n.lastTurnHadOutput=!1);let i=!0,a=Ue;for(;i&&n.continuationCount<a&&!v.signal.aborted;)if(i=await Lt({agent:T,dataDir:e.dataDir,sessionId:l,sessionStoreName:e.sessionStoreName,state:n,accounting:P,abortSignal:v.signal,executeTurn:async t=>{let n=await Fa({agent:T,message:t,continueFromHistory:!1,sessionId:l,channel:e.channel,modelId:E,historyMessages:w.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,contextLimitRecovery:I(`continuation`,t,w),onTurnRecordProduced:async(e,t)=>{await Rt(b,e,t)}});A.add(n.inputTokens,n.outputTokens),j=n.text||j,n.error&&!M&&(M=n.error);let i=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:i}},flushAccountingAfterTurn:async()=>{(await p_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),i){let e=await ag({agent:T,registry:t,sessionId:l,resolvedModelId:E,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,appendEntry:b});A.add(e.inputTokens,e.outputTokens),e.text&&(j=e.text),e.error&&!M&&(M=e.error)}}let y={sessionId:l,hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens};_.error?q.warn(`announce loop completed with error`,y):q.info(`announce loop completed`,y)}catch(t){if(bi(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await be(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),q.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={...A.snapshot()};return await P_({runtime:w,resolvedModelId:E,usage:c,currentUserEntryCoveredByUsage:ee}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Si(t)){let i=t,o=i.request.outputSchema.properties??{};await l_(e.dataDir,l,i.request,X(e)),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length}}),q.info(`agent paused for UI tool input`,{sessionId:l,requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length});let s={...A.snapshot()};return await P_({runtime:w,resolvedModelId:E,usage:s,currentUserEntryCoveredByUsage:ee}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j||``,usage:s,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}if(O&&B_(t))M=`Run timed out after ${D}ms`;else throw await a_({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),q.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{k!==void 0&&clearTimeout(k);try{await p_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}P.clearActiveGoal(),$s(l),g.stop()}let R=A.snapshot();O&&(M=`Run timed out after ${D}ms`),await r.dispatchDiagnostic(l,{level:M?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:R.input,outputTokens:R.output,totalTokens:R.total,hasError:!!M,error:M}});let z={sessionId:l,durationMs:Date.now()-n,inputTokens:R.input,outputTokens:R.output,totalTokens:R.total,hasError:!!M,error:M};return M?q.warn(`agent run completed with error`,z):q.info(`agent run completed`,z),await P_({runtime:w,resolvedModelId:E,usage:R,currentUserEntryCoveredByUsage:ee}),await ks({sessionId:l,runParams:y.runParamsWithAgentPolicy,eventDispatcher:r,transcriptStartIndex:_,result:{text:j,usage:R,durationMs:Date.now()-n,error:M}}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:R,error:M})}async function P_(e){let{runtime:t,resolvedModelId:n,usage:r,currentUserEntryCoveredByUsage:i}=e;r.input<=0&&r.total<=0||await t.contextManager.recordModelUsage({model:n,inputTokens:r.input,outputTokens:r.output,totalTokens:r.total,coveredTranscriptEntryCount:t.usageBaselineTranscriptEntryCount+(i?1:0)})}async function F_(e){oi(e.dataDir);let n=Date.now(),i=new ci(e),a=ml(e),o=a.transcriptMessage.trim()||`CRON task`,s=e.sessionStoreName;q.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:s,...M_(e)});let c=a.requestedSessionId,l=!c;c?(await r(e.dataDir,c,{storeName:s})||(l=!0),await g(e.dataDir,c,{storeName:s})):c=await C(e.dataDir,e.channel,{storeName:s}),l&&await N(e.dataDir,Bm({sessionId:c,title:cc(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:j_});await i.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:u,task:o}),q.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:u,taskLength:o.length,taskPreview:si(o)});let d={...e,sessionId:u,sessionStoreName:j_,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await N_(d,new Xs),f.error&&(m=`error`)}catch(t){let r=t instanceof Error?t.message:String(t);f={sessionId:u,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:h(e.dataDir,u,{storeName:j_}),toolResultsDir:S(e.dataDir,u,{storeName:j_})}},m=`error`,q.error(`cron child run failed`,{parentSessionId:c,childSessionId:u,error:r})}await i.dispatchProgress(c,{type:`subagent_complete`,childSessionId:u,task:o,status:m}),q.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let _=Em({task:o,status:m,result:f.text,error:f.error}),v=new Date().toISOString();await p(e.dataDir,c,{role:`assistant`,content:_,timestamp:v,source:`cron`},{storeName:s});let y={task:o,status:m,content:_,childSessionId:u,createdAt:v};return await b(e.dataDir,c,y,{storeName:s}),await t(e.dataDir,c,e=>I_(e,8),{storeName:s}),await x(e.dataDir,c,{},{storeName:s}),{...f,sessionId:c,context:{snapshotPath:h(e.dataDir,c,{storeName:s}),toolResultsDir:S(e.dataDir,c,{storeName:s})}}}function I_(e,t){if(t<=0)return e.filter(e=>!L_(e));let n=e.reduce((e,t,n)=>(L_(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!L_(e)||r.has(t))}function L_(e){return`source`in e&&e.source===`cron`}async function R_(e,t){if(oi(e.dataDir),q.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...M_(e)}),e.channel===`CRON`&&!e.subagentContext)return F_(e);let n=t??new Xs;try{return await N_(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:i_(t)}),q.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}function z_(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function B_(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const V_={"AGENTS.md":`---
145
145
  title: "AGENTS.md Template"
146
146
  summary: ".aimax template for AGENTS.md"
147
147
  read_when:
@@ -434,7 +434,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
434
434
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
435
435
 
436
436
  Add whatever helps you do your job. This is your cheat sheet.
437
- `},z_=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function B_(e,t){try{if(!(await V.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await V.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function V_(e,t,n){try{if(!(await V.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await V.mkdir(H.dirname(e),{recursive:!0});try{await V.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function H_(e){let t=__(e);return[e,t,H.join(t,`skills`),H.join(t,`sessions`),H.join(t,`memory`),H.join(e,`workspace`)]}function U_(e){let t=__(e);return[...z_.filter(e=>e!==`BOOTSTRAP.md`).map(e=>H.join(t,e)),H.join(t,`MEMORY.md`)]}function W_(e){return H.join(__(e),`.bootstrapped`)}async function G_(e){try{return(await V.stat(W_(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function K_(e){let t=W_(e);await V.mkdir(H.dirname(t),{recursive:!0}),await V.writeFile(t,``,{encoding:`utf-8`})}async function q_(e){let t=[],n=[];for(let n of H_(e))try{(await V.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of U_(e))try{(await V.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function J_(e){return(await q_(e)).ready}async function Y_(e){if(await G_(e))return{ready:!0,performedBootstrap:!1};if((await q_(e)).ready)return await K_(e),{ready:!0,performedBootstrap:!1};let t=await X_(e);return await K_(e),{ready:!0,performedBootstrap:!0,result:t}}async function X_(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=__(e),r=H.join(e,`workspace`),i=H.join(n,`skills`),a=H.join(n,`sessions`),o=H.join(n,`memory`);await B_(e,t),await B_(n,t),await B_(i,t),await B_(a,t),await B_(o,t),await B_(r,t);for(let e of z_){let r=R_[e]??``;await V_(H.join(n,e),r,t)}return await V_(H.join(n,`MEMORY.md`),``,t),t}async function Z_(e){let t=H.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await V.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function Q_(e,t){let n=H.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await V.mkdir(H.dirname(n),{recursive:!0}),await V.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function $_(e,t){let n=await Z_(e),r=[];for(let e of n.values())if(e.parentSessionId===t){let{abortController:t,...n}=e;r.push({...n,version:1})}return r.sort((e,t)=>e.startedAt-t.startedAt)}async function ev(e,t=7){let n=await Z_(e),r=Date.now()-t*24*60*60*1e3,i=0;for(let[e,t]of n.entries())t.endedAt&&t.endedAt<r&&(n.delete(e),i++);return i>0&&await Q_(e,n),i}var tv=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function nv(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function rv(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await z(t,n,s);if(!l)return{action:`created`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let u=(await B(t,n,l,s)).trim();if(u!==c){if(!a)throw new tv(`A different goal already exists for this session. Use --force to replace it.`,nv(u));return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})}}if(l.status===`complete`&&!a)throw new tv(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,nv(u));if(a)return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await I(t,n,d,{storeName:o,eventSource:`cli`})}}async function iv(e,t,n,r){let i=await Ce(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ge(i.request)?(await ye(e,t,n,`expired`,void 0,{storeName:r}),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:i}:{valid:!1,reason:`HITL request is already "${i.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${i.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${i.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function av(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await Se(t,n,r,{storeName:a});if(o){let e=o.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:o,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${o.status}", cannot resume`)}let s=await iv(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await ye(t,n,r,`resolved`,i,{storeName:a});if(!c)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:c,idempotentReplay:!1}}const ov={clarify:{label:`澄清问题`,description:`当你需要更多信息才能继续时,向用户提出澄清问题。提供清晰的问题,并可选给出候选选项。任务会暂停,直到用户回复。`,title:`需要你补充信息`,placeholder:`请输入你的回复`},approval:{label:`请求授权`,description:"仅当用户或系统明确要求调用 `request_approval` 时使用。不要把它用于一般确认、澄清或推断式授权检查。说明要执行的动作,以及为什么必须显式授权。任务会暂停,直到用户同意或拒绝。",choices:{approve:{label:`同意`,description:`允许继续执行该操作`},deny:{label:`拒绝`,description:`不允许执行该操作`}},summary:{approved:`已授权。`,denied:`已拒绝。`,timeout:`由于超时,视为拒绝。`}},review:{label:`请求审阅`,description:`在继续之前,将草稿、文档或输出提交给用户审阅。包含需要审阅的内容,以及你希望获得的反馈类型。任务会暂停,直到用户完成审阅并回复。`,choices:{approve:{label:`通过`,description:`内容没有问题,继续执行`},revise:{label:`需要修改`,description:`提供反馈后再修改`},reject:{label:`拒绝`,description:`放弃当前草稿`}}}};function sv(e){return e.action===`timeout`?ov.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?ov.approval.summary.approved:ov.approval.summary.denied}function cv(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:sv(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function lv(e){let t=e.values?.text??e.values?.selectedChoiceIds?.join(`, `)??``;return JSON.stringify({action:e.action,answer:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function uv(e){let t=(e.values?.selectedChoiceIds??[])[0]??e.action,n=e.values?.text??``;return JSON.stringify({action:e.action,verdict:t,feedback:n,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function dv(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
437
+ `},H_=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function U_(e,t){try{if(!(await V.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await V.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function W_(e,t,n){try{if(!(await V.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await V.mkdir(H.dirname(e),{recursive:!0});try{await V.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function G_(e){let t=b_(e);return[e,t,H.join(t,`skills`),H.join(t,`sessions`),H.join(t,`memory`),H.join(e,`workspace`)]}function K_(e){let t=b_(e);return[...H_.filter(e=>e!==`BOOTSTRAP.md`).map(e=>H.join(t,e)),H.join(t,`MEMORY.md`)]}function q_(e){return H.join(b_(e),`.bootstrapped`)}async function J_(e){try{return(await V.stat(q_(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Y_(e){let t=q_(e);await V.mkdir(H.dirname(t),{recursive:!0}),await V.writeFile(t,``,{encoding:`utf-8`})}async function X_(e){let t=[],n=[];for(let n of G_(e))try{(await V.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of K_(e))try{(await V.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function Z_(e){return(await X_(e)).ready}async function Q_(e){if(await J_(e))return{ready:!0,performedBootstrap:!1};if((await X_(e)).ready)return await Y_(e),{ready:!0,performedBootstrap:!1};let t=await $_(e);return await Y_(e),{ready:!0,performedBootstrap:!0,result:t}}async function $_(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=b_(e),r=H.join(e,`workspace`),i=H.join(n,`skills`),a=H.join(n,`sessions`),o=H.join(n,`memory`);await U_(e,t),await U_(n,t),await U_(i,t),await U_(a,t),await U_(o,t),await U_(r,t);for(let e of H_){let r=V_[e]??``;await W_(H.join(n,e),r,t)}return await W_(H.join(n,`MEMORY.md`),``,t),t}async function ev(e){let t=H.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await V.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function tv(e,t){let n=H.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await V.mkdir(H.dirname(n),{recursive:!0}),await V.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function nv(e,t){let n=await ev(e),r=[];for(let e of n.values())if(e.parentSessionId===t){let{abortController:t,...n}=e;r.push({...n,version:1})}return r.sort((e,t)=>e.startedAt-t.startedAt)}async function rv(e,t=7){let n=await ev(e),r=Date.now()-t*24*60*60*1e3,i=0;for(let[e,t]of n.entries())t.endedAt&&t.endedAt<r&&(n.delete(e),i++);return i>0&&await tv(e,n),i}var iv=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function av(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function ov(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await z(t,n,s);if(!l)return{action:`created`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let u=(await B(t,n,l,s)).trim();if(u!==c){if(!a)throw new iv(`A different goal already exists for this session. Use --force to replace it.`,av(u));return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})}}if(l.status===`complete`&&!a)throw new iv(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,av(u));if(a)return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await I(t,n,d,{storeName:o,eventSource:`cli`})}}async function sv(e,t,n,r){let i=await Ce(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ge(i.request)?(await ye(e,t,n,`expired`,void 0,{storeName:r}),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:i}:{valid:!1,reason:`HITL request is already "${i.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${i.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${i.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function cv(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await Se(t,n,r,{storeName:a});if(o){let e=o.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:o,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${o.status}", cannot resume`)}let s=await sv(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await ye(t,n,r,`resolved`,i,{storeName:a});if(!c)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:c,idempotentReplay:!1}}const lv={clarify:{label:`澄清问题`,description:`当你需要更多信息才能继续时,向用户提出澄清问题。提供清晰的问题,并可选给出候选选项。任务会暂停,直到用户回复。`,title:`需要你补充信息`,placeholder:`请输入你的回复`},approval:{label:`请求授权`,description:"仅当用户或系统明确要求调用 `request_approval` 时使用。不要把它用于一般确认、澄清或推断式授权检查。说明要执行的动作,以及为什么必须显式授权。任务会暂停,直到用户同意或拒绝。",choices:{approve:{label:`同意`,description:`允许继续执行该操作`},deny:{label:`拒绝`,description:`不允许执行该操作`}},summary:{approved:`已授权。`,denied:`已拒绝。`,timeout:`由于超时,视为拒绝。`}},review:{label:`请求审阅`,description:`在继续之前,将草稿、文档或输出提交给用户审阅。包含需要审阅的内容,以及你希望获得的反馈类型。任务会暂停,直到用户完成审阅并回复。`,choices:{approve:{label:`通过`,description:`内容没有问题,继续执行`},revise:{label:`需要修改`,description:`提供反馈后再修改`},reject:{label:`拒绝`,description:`放弃当前草稿`}}}};function uv(e){return e.action===`timeout`?lv.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?lv.approval.summary.approved:lv.approval.summary.denied}function dv(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:uv(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function fv(e){let t=e.values?.text??e.values?.selectedChoiceIds?.join(`, `)??``;return JSON.stringify({action:e.action,answer:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function pv(e){let t=(e.values?.selectedChoiceIds??[])[0]??e.action,n=e.values?.text??``;return JSON.stringify({action:e.action,verdict:t,feedback:n,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function mv(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
438
438
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
439
439
  `)):(n.push(`动作:用户已提交结果。`),e.values?.selectedChoiceIds&&e.values.selectedChoiceIds.length>0&&n.push(`已选项:${e.values.selectedChoiceIds.join(`, `)}`),e.values?.text&&n.push(`用户文本:${e.values.text}`),e.values?.form&&n.push(`表单数据:${JSON.stringify(e.values.form)}`),n.join(`
440
- `))}export{K as AutoSkillsLoader,g_ as BOOTSTRAP_FILE_NAMES,m_ as BOOTSTRAP_MAX_CHARS,h_ as BOOTSTRAP_TOTAL_MAX_CHARS,Nt as ContinuationState,A as DEFAULT_SESSION_STORE_NAME,Mt as ENV_GOAL_CONTINUATION,hc as GOAL_MULTILINE_TEMPLATE_EXAMPLE,wt as GoalAccounting,tv as GoalConflictError,ov as HITL_MESSAGES,yi as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,Ys as MAX_CHILDREN_PER_SESSION,Js as MAX_SUBAGENT_DEPTH,de as MemoryIndexManager,Rg as PLUGIN_MANIFEST_FILENAME,zg as PLUGIN_MANIFEST_FILENAMES,qr as PluginHookRegistry,_h as PluginToolRegistry,Cr as SYSTEM_AGENTS_DIR,Xs as SubagentRegistry,xi as UiToolPauseSignal,ze as addAgent,Fe as addBinding,Tr as agentDirCandidates,Nr as agentVisibility,__ as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,te as appendGoalEvent,cp as appendRecentToMemory,o as appendSessionFile,sp as appendToMemory,p as appendTranscriptEntry,rv as applyCliGoalBeforeRun,sv as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,wn as autoSkillsDir,X_ as bootstrapMountLayout,Lr as buildAgentDelegationPrompt,Rr as buildAgentTaskPrompt,_c as buildAimaxGoalCliHelpExtra,x_ as buildBootstrapContextFiles,Ot as buildBudgetLimitPrompt,Dt as buildContinuationPrompt,At as buildGoalContextItem,gc as buildGoalSlashHelpText,kt as buildObjectiveUpdatedPrompt,dv as buildResumeNarration,um as buildSkillsPrompt,Cm as buildSubagentAnnounceMessage,hh as buildSystemPrompt,ev as cleanupOldSubagentRecords,we as clearPendingHitl,c_ as clearPendingUiTool,k as collapseLogPath,Bt as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,It as continuationTurnHadMeaningfulOutput,Dr as createAgentDefinitionsContext,Wm as createAgentTools,Vf as createApplyPatchTool,Eo as createAutoSkillCategoriesTool,Do as createAutoSkillListTool,Oo as createAutoSkillSearchTool,ko as createAutoSkillViewTool,Vn as createAutoSkillsLoader,Sf as createBashTool,Dm as createBatchSubagentSpawnTool,le as createBuiltinMemoryProvider,Jd as createContextManager,Mf as createEditFileTool,of as createExecTool,Vm as createImageTool,Pf as createListDirTool,gp as createMemoryAppendTool,Ap as createMemoryForgetTool,mp as createMemoryGetTool,Op as createMemoryListTool,Ep as createMemoryLogTool,fp as createMemorySearchTool,Mp as createMemoryUpdateTool,vp as createMemoryWriteTool,be as createPendingHitl,o_ as createPendingUiTool,Kr as createPluginProgressEmitter,Gg as createPluginRuntime,uf as createProcessTool,Of as createReadFileTool,C as createSession,xd as createSessionContextStore,Pp as createSessionSearchTool,mm as createSkillListTool,hm as createSkillLoadTool,Em as createSubagentSpawnTool,jm as createSubagentsTool,Um as createUiTool,Af as createWriteFileTool,j as cronExecutionsPath,Hm as defaultUiToolInputSchema,ie as deleteGoal,up as deleteMemoryFile,Ig as discoverAIMaxPlugins,fl as emitGoalUpdatedProgress,Y_ as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,Fr as filterSkillsForAgent,Ir as filterToolsForAgent,Mr as findAgentDefinition,sm as findSkillByName,Tt as flushAccounting,cv as formatApprovalResolution,lv as formatClarifyResolution,uv as formatReviewResolution,rc as generateSessionTitle,Me as getAgentConfig,op as getMemoryLines,F as goalEventsPath,R as goalObjectiveMdPath,re as goalPath,G_ as hasBootstrapSentinel,ve as hitlHistoryPath,Zg as initializePluginSystem,q_ as inspectBootstrapMountLayout,D as inspectSession,J_ as isBootstrapMountLayoutReady,Pt as isContinuationEnabled,jt as isGoalContext,bi as isHitlPauseSignal,Si as isUiToolPauseSignal,Ee as listAgents,Oc as listAvailableSlashCommands,Ie as listBindings,np as listMemoryFiles,w as listSessionSummaries,y as listSessions,$_ as listSubagentRunsFromDisk,Ar as loadAgentDefinitionsFromDir,Re as loadAgentsConfig,v as loadArtifactOperations,v_ as loadBootstrapFiles,f as loadCronExecutionRecords,Ce as loadPendingHitl,Ce as readPendingHitl,a_ as loadPendingUiTool,a_ as readPendingUiTool,Vg as loadPluginManifest,Hg as loadPluginManifestRegistry,Jg as loadPlugins,M as loadSessionContextSnapshot,P as loadSessionMetadata,lm as loadSkillView,im as loadSkills,om as loadSkillsFromDirs,am as loadSkillsWithPluginDirs,Z_ as loadSubagentRegistryFromDisk,m as loadTranscript,Lt as maybeContinueGoalIfIdle,$f as memoryDir,ee as metadataPath,ne as mirrorGoalStatusToSession,De as normalizeAgentId,fg as normalizePluginsConfig,u as normalizeSessionStoreName,jr as parseAgentDefinition,_e as pendingHitlPath,r_ as pendingUiToolPath,zt as prependObjectiveUpdatedSteeringIfNeeded,ep as primaryMemoryPath,Pr as publicAgentDefinitions,z as readGoal,xe as readHitlHistory,rp as readMemoryFile,ip as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,se as registerEmbeddingProvider,he as registerMemoryProvider,Ne as removeAgent,Be as removeBindings,lp as replaceMemoryFile,ae as resetEmbeddingProviderRegistryForTests,ge as resetMemoryProviderRegistryForTests,kr as resolveAgentDefinitionsContext,Oe as resolveAgentDir,ke as resolveAgentIdByBinding,Le as resolveAgentsConfigPath,Pe as resolveDefaultAgentId,ue as resolveEmbeddingProvider,B as resolveGoalObjective,av as resolveHitlRequest,av as resolvePendingHitl,me as resolveMemoryProvider,je as resolveModelFallbacks,Ae as resolveModelString,s_ as resolvePendingUiTool,Bg as resolvePluginManifestPath,t as rewriteTranscript,F_ as runAgent,Te as saveAgentsConfig,N as saveSessionMetadata,Q_ as saveSubagentRegistryToDisk,Er as scanAgentDefinitions,ap as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,Ft as shouldContinueGoal,Qp as skillsDir,S as toolResultsDir,e as transcriptPath,ye as transitionHitlStatus,Ve as updateAgent,He as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,pg as validatePluginsConfig,iv as validateResume,yh as wrapToolsWithHooks,L as writeGoal,a as writeSessionFile};
440
+ `))}export{K as AutoSkillsLoader,y_ as BOOTSTRAP_FILE_NAMES,__ as BOOTSTRAP_MAX_CHARS,v_ as BOOTSTRAP_TOTAL_MAX_CHARS,Nt as ContinuationState,A as DEFAULT_SESSION_STORE_NAME,Mt as ENV_GOAL_CONTINUATION,hc as GOAL_MULTILINE_TEMPLATE_EXAMPLE,wt as GoalAccounting,iv as GoalConflictError,lv as HITL_MESSAGES,yi as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,Ys as MAX_CHILDREN_PER_SESSION,Js as MAX_SUBAGENT_DEPTH,de as MemoryIndexManager,Vg as PLUGIN_MANIFEST_FILENAME,Hg as PLUGIN_MANIFEST_FILENAMES,qr as PluginHookRegistry,bh as PluginToolRegistry,Cr as SYSTEM_AGENTS_DIR,Xs as SubagentRegistry,xi as UiToolPauseSignal,ze as addAgent,Fe as addBinding,Tr as agentDirCandidates,Nr as agentVisibility,b_ as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,te as appendGoalEvent,dp as appendRecentToMemory,o as appendSessionFile,up as appendToMemory,p as appendTranscriptEntry,ov as applyCliGoalBeforeRun,uv as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,wn as autoSkillsDir,$_ as bootstrapMountLayout,Lr as buildAgentDelegationPrompt,Rr as buildAgentTaskPrompt,_c as buildAimaxGoalCliHelpExtra,w_ as buildBootstrapContextFiles,Ot as buildBudgetLimitPrompt,Dt as buildContinuationPrompt,At as buildGoalContextItem,gc as buildGoalSlashHelpText,kt as buildObjectiveUpdatedPrompt,mv as buildResumeNarration,pm as buildSkillsPrompt,Em as buildSubagentAnnounceMessage,vh as buildSystemPrompt,rv as cleanupOldSubagentRecords,we as clearPendingHitl,d_ as clearPendingUiTool,k as collapseLogPath,Bt as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,It as continuationTurnHadMeaningfulOutput,Dr as createAgentDefinitionsContext,qm as createAgentTools,Wf as createApplyPatchTool,Eo as createAutoSkillCategoriesTool,Do as createAutoSkillListTool,Oo as createAutoSkillSearchTool,ko as createAutoSkillViewTool,Vn as createAutoSkillsLoader,Tf as createBashTool,Am as createBatchSubagentSpawnTool,le as createBuiltinMemoryProvider,Jd as createContextManager,Ff as createEditFileTool,of as createExecTool,Wm as createImageTool,Lf as createListDirTool,yp as createMemoryAppendTool,Np as createMemoryForgetTool,_p as createMemoryGetTool,jp as createMemoryListTool,kp as createMemoryLogTool,hp as createMemorySearchTool,Fp as createMemoryUpdateTool,xp as createMemoryWriteTool,be as createPendingHitl,l_ as createPendingUiTool,Kr as createPluginProgressEmitter,Jg as createPluginRuntime,uf as createProcessTool,jf as createReadFileTool,C as createSession,xd as createSessionContextStore,Lp as createSessionSearchTool,_m as createSkillListTool,vm as createSkillLoadTool,km as createSubagentSpawnTool,Pm as createSubagentsTool,Km as createUiTool,Nf as createWriteFileTool,j as cronExecutionsPath,Gm as defaultUiToolInputSchema,ie as deleteGoal,pp as deleteMemoryFile,zg as discoverAIMaxPlugins,fl as emitGoalUpdatedProgress,Q_ as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,Fr as filterSkillsForAgent,Ir as filterToolsForAgent,Mr as findAgentDefinition,um as findSkillByName,Tt as flushAccounting,dv as formatApprovalResolution,fv as formatClarifyResolution,pv as formatReviewResolution,rc as generateSessionTitle,Me as getAgentConfig,lp as getMemoryLines,F as goalEventsPath,R as goalObjectiveMdPath,re as goalPath,J_ as hasBootstrapSentinel,ve as hitlHistoryPath,e_ as initializePluginSystem,X_ as inspectBootstrapMountLayout,D as inspectSession,Z_ as isBootstrapMountLayoutReady,Pt as isContinuationEnabled,jt as isGoalContext,bi as isHitlPauseSignal,Si as isUiToolPauseSignal,Ee as listAgents,Oc as listAvailableSlashCommands,Ie as listBindings,ap as listMemoryFiles,w as listSessionSummaries,y as listSessions,nv as listSubagentRunsFromDisk,Ar as loadAgentDefinitionsFromDir,Re as loadAgentsConfig,v as loadArtifactOperations,x_ as loadBootstrapFiles,f as loadCronExecutionRecords,Ce as loadPendingHitl,Ce as readPendingHitl,c_ as loadPendingUiTool,c_ as readPendingUiTool,Wg as loadPluginManifest,Gg as loadPluginManifestRegistry,Zg as loadPlugins,M as loadSessionContextSnapshot,P as loadSessionMetadata,fm as loadSkillView,sm as loadSkills,lm as loadSkillsFromDirs,cm as loadSkillsWithPluginDirs,ev as loadSubagentRegistryFromDisk,m as loadTranscript,Lt as maybeContinueGoalIfIdle,np as memoryDir,ee as metadataPath,ne as mirrorGoalStatusToSession,De as normalizeAgentId,hg as normalizePluginsConfig,u as normalizeSessionStoreName,jr as parseAgentDefinition,_e as pendingHitlPath,o_ as pendingUiToolPath,zt as prependObjectiveUpdatedSteeringIfNeeded,rp as primaryMemoryPath,Pr as publicAgentDefinitions,z as readGoal,xe as readHitlHistory,op as readMemoryFile,sp as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,se as registerEmbeddingProvider,he as registerMemoryProvider,Ne as removeAgent,Be as removeBindings,fp as replaceMemoryFile,ae as resetEmbeddingProviderRegistryForTests,ge as resetMemoryProviderRegistryForTests,kr as resolveAgentDefinitionsContext,Oe as resolveAgentDir,ke as resolveAgentIdByBinding,Le as resolveAgentsConfigPath,Pe as resolveDefaultAgentId,ue as resolveEmbeddingProvider,B as resolveGoalObjective,cv as resolveHitlRequest,cv as resolvePendingHitl,me as resolveMemoryProvider,je as resolveModelFallbacks,Ae as resolveModelString,u_ as resolvePendingUiTool,Ug as resolvePluginManifestPath,t as rewriteTranscript,R_ as runAgent,Te as saveAgentsConfig,N as saveSessionMetadata,tv as saveSubagentRegistryToDisk,Er as scanAgentDefinitions,cp as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,Ft as shouldContinueGoal,tm as skillsDir,S as toolResultsDir,e as transcriptPath,ye as transitionHitlStatus,Ve as updateAgent,He as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,gg as validatePluginsConfig,sv as validateResume,Sh as wrapToolsWithHooks,L as writeGoal,a as writeSessionFile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",