@gencode/agents 0.9.3-preview.3 → 0.9.3-preview.5

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/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { C as AgentsConfig, S as AgentModelConfig, _ as saveAgentsConfig, a as listAgents, b as AgentBinding, c as normalizeAgentId, d as resolveAgentDir, f as resolveAgentIdByBinding, g as resolveModelString, h as resolveModelFallbacks, i as getAgentConfig, l as removeAgent, m as resolveDefaultAgentId, n as addBinding, o as listBindings, p as resolveAgentsConfigPath, s as loadAgentsConfig, t as addAgent, u as removeBindings, v as updateAgent, x as AgentConfig, y as updateAgentIdentity } from "./index-iedOAibO.js";
2
2
  import * as _gencode_shared0 from "@gencode/shared";
3
3
  import { AgentCustomProgressEvent, AgentDiagnosticEvent, AgentProgressEvent, AgentProgressEvent as AgentProgressEvent$1, AgentProgressEvent as AgentProgressEvent$2, AgentProgressEventBase, CallbackEventPayload, CallbackEventPayload as CallbackEventPayload$1, Channel, Channel as Channel$1, CollapseSpan, GoalStatus, HitlCheckpoint, HitlCheckpoint as HitlCheckpoint$1, HitlHistoryEntry, HitlRequest, HitlRequest as HitlRequest$1, HitlResolution, HitlResolution as HitlResolution$1, HitlStatus, HitlToolContext, HitlToolContext as HitlToolContext$1, ModelUsageCheckpoint, PausedRunState, PausedRunState as PausedRunState$1, ReadStateRecord, RunResultPayload, RunResultPayload as RunResultPayload$1, SessionContextSnapshot, SessionMemorySnapshot, SessionMetadata, SessionMetadata as SessionMetadata$1, SessionSummary, SessionSummary as SessionSummary$1, SnipRecord, ThreadGoal, ToolResultReference, UiToolExtra, UiToolOutputSchema, UiToolPausedState, UiToolRequest, UiToolResult, UiToolValidationResult } from "@gencode/shared";
4
+ import path from "node:path";
4
5
  import { Agent, AgentMessage, AgentTool } from "@mariozechner/pi-agent-core";
5
6
  import { AssistantMessage, Message } from "@mariozechner/pi-ai";
6
7
 
@@ -1936,6 +1937,7 @@ declare const execSchema: TObject<{
1936
1937
  yieldMs: TOptional<TNumber>;
1937
1938
  background: TOptional<TBoolean>;
1938
1939
  }>;
1940
+ /** @internal exported for unit tests */
1939
1941
  type ExecToolOptions = {
1940
1942
  sessionId?: string;
1941
1943
  workspaceDir: string;
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 to execute the command in. Must resolve to a path inside the workspace root; absolute paths outside the workspace root are rejected.`})),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{cwd:e,adjusted:!1};let n=H.isAbsolute(t)?H.normalize(t):H.normalize(H.join(e,t));return!n.startsWith(e+H.sep)&&n!==e?{cwd:e,adjusted:!0}:{cwd:n,adjusted:!1}}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 of({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
61
- `)}function rf(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function af(e){return`'${e.replace(/'/g,`'\\''`)}'`}function of(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 sf(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`}};console.log(`workspaceDir: ${e.workspaceDir}`),console.log(`workdir: ${n.workdir}`);let{cwd:i,adjusted:a}=ef(e.workspaceDir,n.workdir),o=a?`cd ${af(e.workspaceDir)} && ${n.command}`:n.command,s=Qd(n.timeout),c=e.registry.start({command:o,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:s,scopeKey:e.scopeKey}),l=n.background===!0,u=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),d=c,f;try{if(!l&&r&&(f=()=>{e.registry.terminate(c.sessionId,e.scopeKey)},r.aborted?f():r.addEventListener(`abort`,f,{once:!0})),!l&&!u){let t=await e.registry.wait(c.sessionId,e.scopeKey,void 0);t&&(d=t)}else if(!l){let t=await e.registry.wait(c.sessionId,e.scopeKey,$d(n.yieldMs));t&&(d=t)}}finally{r&&f&&r.removeEventListener(`abort`,f)}if(d.status===`running`)return{content:[{type:`text`,text:tf(d)}],details:{status:`running`,sessionId:d.sessionId,command:d.command,cwd:d.cwd,pid:d.pid}};let p=e.registry.readOutput(d.sessionId,e.scopeKey),m=p?of({stdout:p.stdout,stderr:p.stderr,exitCode:d.exitCode,backgroundInfo:``}):[nf(d)],h=rf(p?.stdout??d.stdoutTail),g=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:h.length>0?h:`(no output)`});return{content:[{type:`text`,text:[g?.content??(h.length>0?h:`(no output)`),...m.slice(1)].join(`
62
- `)}],details:{status:d.status,sessionId:d.sessionId,command:d.command,cwd:d.cwd,exitCode:d.exitCode,exitSignal:d.exitSignal,toolResultRef:g?.reference}}}}}const cf=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 lf(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function uf(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function df(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:cf,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 uf(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,lf(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`}}:uf(`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}}:uf(`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}}:uf(`No session found for ${i}`)}return uf(`Unsupported action: ${n.action}`)}}}const ff=2e5;function pf(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function mf(e,t){let n=e+t;return n.length<=ff?{text:n,truncated:!1}:{text:n.slice(-ff),truncated:!0}}function hf(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=mf(e.output,r);e.output=i.text;let a=mf(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function gf(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:pf(e.output),stdoutTail:pf(e.stdout),stderrTail:pf(e.stderr),outputTruncated:e.outputTruncated}}function _f(e,t){return t?e.scopeKey===t:!0}function vf(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function yf(e){return e?e.split(/\r?\n/):[]}function bf(e){let t=yf(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=vf(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 xf(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Sf(){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),xf(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=>hf(o,`stdout`,e)),n.stderr.on(`data`,e=>hf(o,`stderr`,e));let s=vf(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,hf(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`),hf(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`)})}),gf(o)},get(e,t){let n=r(e);return!n||!_f(n,t)?null:gf(n)},list(n){return[...e.values(),...t.values()].filter(e=>_f(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>gf(e))},async wait(e,t,n){let i=r(e);if(!i||!_f(i,t))return null;if(i.status!==`running`)return gf(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||!_f(a,t)?null:gf(a)},readLog(e){let t=r(e.sessionId);return!t||!_f(t,e.scopeKey)?null:bf({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!_f(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||!_f(n,t))return null;if(n.status!==`running`)return gf(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?gf(i):null}}}function Cf(e){return sf({workspaceDir:e,registry:Sf(),scopeKey:e})}const wf=5*1024*1024,Tf=2e3;async function Ef(e,t){e&&await e(t).catch(()=>{})}function Df(e,t){return H.isAbsolute(e)?H.normalize(e):H.normalize(H.join(t,e))}const Of=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 kf(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Of,async execute(n,r){let i;try{i=Df(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>wf){let e=o.slice(0,wf).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${wf} 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(Tf,r.limit??Tf),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(`
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. On Windows the command runs under cmd.exe; on macOS/Linux under bash -lc. When the command references a path that contains spaces (e.g. `C:/Program Files/Foo/bar.exe`), wrap that path in double quotes inside the command string itself, e.g. `"C:/Program Files/Foo/bar.exe" --flag`. Forward slashes work on Windows too — prefer them over backslashes to avoid escape issues in JSON.'}),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). Pass the raw path string — do NOT wrap it in quotes and do NOT escape spaces. Forward slashes are accepted on every OS (e.g. `C:/Program Files/Foo`). If the desired directory cannot be located inside the workspace, do NOT set workdir — instead adjust the command itself (e.g. prefix with `cd "C:/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=process.platform){let n=e.trim();if(n.length>=2){let e=n[0],t=n[n.length-1];(e===`"`&&t===`"`||e===`'`&&t===`'`)&&(n=n.slice(1,-1).trim())}if(n=n.replace(/\\ /g,` `),t===`win32`){let e=/^(\\\\|\/\/)([^\\/]+)([\\/].*)?$/.exec(n);if(e){let t=(e[3]??``).replace(/\\/g,`/`);n=`//${e[2]}${t}`}else n=n.replace(/\\/g,`/`)}return n}function tf(e,t,n={}){let r=n.platform??process.platform,i=n.pathImpl??H;if(!t?.trim())return e;let a=ef(t,r),o=i.isAbsolute(a)?i.normalize(a):i.normalize(i.join(e,a)),s=i.normalize(e),c=s.endsWith(i.sep)?s:s+i.sep,l=r===`win32`;if(!((e,t)=>l?e.toLowerCase().startsWith(t.toLowerCase()):e.startsWith(t))(o,c)&&!((e,t)=>l?e.toLowerCase()===t.toLowerCase():e===t)(o,s))throw Error(`workdir escapes workspace: ${t}`);return o}function nf(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 rf(e){return of({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
61
+ `)}function af(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function of(e){let t=af(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 sf(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=tf(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:nf(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?of({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[rf(l)],p=af(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
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const cf=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 lf(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function uf(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function df(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:cf,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 uf(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,lf(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`}}:uf(`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}}:uf(`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}}:uf(`No session found for ${i}`)}return uf(`Unsupported action: ${n.action}`)}}}const ff=process.platform===`win32`;function pf(e){return ff?{file:process.env.ComSpec||process.env.COMSPEC||`cmd.exe`,args:[`/d`,`/s`,`/c`,`chcp 65001>nul & ${e}`]}:{file:`bash`,args:[`-lc`,e]}}function mf(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(ff&&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 hf=2e5;function gf(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function _f(e,t){let n=e+t;return n.length<=hf?{text:n,truncated:!1}:{text:n.slice(-hf),truncated:!0}}function vf(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=_f(e.output,r);e.output=i.text;let a=_f(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function yf(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:gf(e.output),stdoutTail:gf(e.stdout),stderrTail:gf(e.stderr),outputTruncated:e.outputTruncated}}function bf(e,t){return t?e.scopeKey===t:!0}function xf(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Sf(e){return e?e.split(/\r?\n/):[]}function Cf(e){let t=Sf(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=xf(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 wf(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Tf(){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),wf(e))};return{start(t){let{file:n,args:r}=pf(t.command),a=bt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0}),o=()=>{},s=new Promise(e=>{o=e}),c={sessionId:Ze(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:a,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:s,resolveDone:o};e.set(c.sessionId,c),a.stdout.on(`data`,e=>vf(c,`stdout`,e)),a.stderr.on(`data`,e=>vf(c,`stderr`,e));let l=xf(t.timeoutSec,1800);return c.timeoutTimer=setTimeout(()=>{c.status===`running`&&(c.status=`timeout`,vf(c,`stderr`,Buffer.from(`\n[Timed out after ${l}s]\n`)),mf(c.child,`SIGTERM`),c.killTimer=setTimeout(()=>{(c.status===`running`||c.status===`timeout`)&&mf(c.child,`SIGKILL`)},1e3))},l*1e3),a.on(`error`,e=>{i(c,()=>{c.status===`running`&&(c.status=`failed`),vf(c,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),a.on(`close`,(e,t)=>{i(c,()=>{c.exitCode=e,c.exitSignal=t,c.status===`running`?c.status=e===0?`completed`:`failed`:c.status===`killed`&&e===0&&(c.status=`completed`)})}),yf(c)},get(e,t){let n=r(e);return!n||!bf(n,t)?null:yf(n)},list(n){return[...e.values(),...t.values()].filter(e=>bf(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>yf(e))},async wait(e,t,n){let i=r(e);if(!i||!bf(i,t))return null;if(i.status!==`running`)return yf(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||!bf(a,t)?null:yf(a)},readLog(e){let t=r(e.sessionId);return!t||!bf(t,e.scopeKey)?null:Cf({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!bf(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||!bf(n,t))return null;if(n.status!==`running`)return yf(n);n.status=`killed`,mf(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&mf(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?yf(i):null}}}function Ef(e){return sf({workspaceDir:e,registry:Tf(),scopeKey:e})}const Df=5*1024*1024,Of=2e3;async function kf(e,t){e&&await e(t).catch(()=>{})}function Af(e,t){return H.isAbsolute(e)?H.normalize(e):H.normalize(H.join(t,e))}const jf=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 Mf(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:jf,async execute(n,r){let i;try{i=Af(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>Df){let e=o.slice(0,Df).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Df} 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(Of,r.limit??Of),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 Af=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),content:W.String({description:`File content to write`})});function jf(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Af,async execute(r,i){let a;try{a=Df(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 Ef(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 Mf=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 Nf(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:Mf,async execute(r,i){let a;try{a=Df(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 Ef(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 Pf=W.Object({path:W.Optional(W.String({description:`Directory path (default: workspace root)`}))});function Ff(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Pf,async execute(t,n){let r=n.path??`.`,i;try{i=Df(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 If=W.Object({input:W.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Lf(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 Rf(e,t){let n=H.relative(t,e);return!n||n===``?H.basename(e):n.startsWith(`..`)||H.isAbsolute(n)?e:n}async function zf(e){await V.mkdir(H.dirname(e),{recursive:!0})}async function Bf(e,t){e&&await e(t).catch(()=>{})}function Vf(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 Hf(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:If,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=Wf(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=Lf(r.path,e);await zf(i),await V.writeFile(i,r.contents,`utf-8`),await Bf(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Uf(o,s,`added`,Rf(i,e));continue}if(r.kind===`delete`){let i=Lf(r.path,e);await V.rm(i,{force:!0,recursive:!1}),await Bf(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Uf(o,s,`deleted`,Rf(i,e));continue}let i=Lf(r.path,e),a=await Jf(i,r.chunks);if(r.movePath){let c=Lf(r.movePath,e);await zf(c),await V.writeFile(c,a,`utf-8`),await V.rm(i,{force:!0,recursive:!1}),await Bf(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Uf(o,s,`modified`,Rf(c,e))}else await V.writeFile(i,a,`utf-8`),await Bf(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Uf(o,s,`modified`,Rf(i,e))}return{content:[{type:`text`,text:Vf(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 Uf(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Wf(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Gf(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Kf(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Gf(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 Kf(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}=qf(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 qf(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 Jf(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=Xf(n,Yf(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
72
- `)}function Yf(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Zf(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=Zf(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=Zf(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 Xf(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 Zf(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(Qf(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Qf(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Qf(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Qf(e,t,n,e=>$f(e.trim())))return n;return null}function Qf(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 $f(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 ep(e){return H.join(e,`.aimax`)}function tp(e){return H.join(ep(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 np(e,t){let n=ep(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 rp(e){return pe(ep(e))}async function ip(e){try{return await V.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ap(e){return ip(tp(e))}async function op(e,t,n){let{provider:r}=np(e,n);return await r.search(t)}async function sp(e,t,n,r,i){try{let{provider:a}=np(e,i);return await a.getLines(t,n,r)}catch{return null}}async function cp(e,t,n){let{provider:r,resolvedProviderId:i}=np(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 lp(e,t,n,r){let{provider:i,resolvedProviderId:a}=np(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 up(e,t,n,r){let{provider:i,resolvedProviderId:a}=np(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 dp(e,t,n){let{provider:r,resolvedProviderId:i}=np(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 fp=W.Object({query:W.String({description:`Search query (case-insensitive substring match)`})});function pp(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:fp,async execute(n,r){let i=(await op(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 mp=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 hp(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:mp,async execute(n,r){let i=await sp(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 gp=W.Object({content:W.String({description:`Content to write to memory`})});function _p(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:gp,async execute(n,r){try{return await cp(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 vp=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 yp(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:vp,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await cp(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 up(e,`MEMORY.md`,bp(await ap(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await cp(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 bp(e,t,n){let r=e.split(`
68
+ `),lines:d.length,truncated:f}}}}}const Nf=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),content:W.String({description:`File content to write`})});function Pf(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Nf,async execute(r,i){let a;try{a=Af(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 kf(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 Ff=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 If(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:Ff,async execute(r,i){let a;try{a=Af(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 kf(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 Lf=W.Object({path:W.Optional(W.String({description:`Directory path (default: workspace root)`}))});function Rf(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Lf,async execute(t,n){let r=n.path??`.`,i;try{i=Af(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 zf=W.Object({input:W.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Bf(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 Vf(e,t){let n=H.relative(t,e);return!n||n===``?H.basename(e):n.startsWith(`..`)||H.isAbsolute(n)?e:n}async function Hf(e){await V.mkdir(H.dirname(e),{recursive:!0})}async function Uf(e,t){e&&await e(t).catch(()=>{})}function Wf(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 Gf(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:zf,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=qf(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=Bf(r.path,e);await Hf(i),await V.writeFile(i,r.contents,`utf-8`),await Uf(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Kf(o,s,`added`,Vf(i,e));continue}if(r.kind===`delete`){let i=Bf(r.path,e);await V.rm(i,{force:!0,recursive:!1}),await Uf(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Kf(o,s,`deleted`,Vf(i,e));continue}let i=Bf(r.path,e),a=await Zf(i,r.chunks);if(r.movePath){let c=Bf(r.movePath,e);await Hf(c),await V.writeFile(c,a,`utf-8`),await V.rm(i,{force:!0,recursive:!1}),await Uf(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Kf(o,s,`modified`,Vf(c,e))}else await V.writeFile(i,a,`utf-8`),await Uf(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Kf(o,s,`modified`,Vf(i,e))}return{content:[{type:`text`,text:Wf(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 Kf(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function qf(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Jf(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Yf(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Jf(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 Yf(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}=Xf(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 Xf(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 Zf(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=$f(n,Qf(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
72
+ `)}function Qf(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=ep(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=ep(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=ep(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 $f(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 ep(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(tp(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(tp(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(tp(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(tp(e,t,n,e=>np(e.trim())))return n;return null}function tp(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 np(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 rp(e){return H.join(e,`.aimax`)}function ip(e){return H.join(rp(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 ap(e,t){let n=rp(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 op(e){return pe(rp(e))}async function sp(e){try{return await V.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function cp(e){return sp(ip(e))}async function lp(e,t,n){let{provider:r}=ap(e,n);return await r.search(t)}async function up(e,t,n,r,i){try{let{provider:a}=ap(e,i);return await a.getLines(t,n,r)}catch{return null}}async function dp(e,t,n){let{provider:r,resolvedProviderId:i}=ap(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 fp(e,t,n,r){let{provider:i,resolvedProviderId:a}=ap(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 pp(e,t,n,r){let{provider:i,resolvedProviderId:a}=ap(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 mp(e,t,n){let{provider:r,resolvedProviderId:i}=ap(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 hp=W.Object({query:W.String({description:`Search query (case-insensitive substring match)`})});function gp(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:hp,async execute(n,r){let i=(await lp(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 _p=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 vp(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:_p,async execute(n,r){let i=await up(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 yp=W.Object({content:W.String({description:`Content to write to memory`})});function bp(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:yp,async execute(n,r){try{return await dp(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 xp=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 Sp(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:xp,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await dp(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 pp(e,`MEMORY.md`,Cp(await cp(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await dp(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 Cp(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 xp(e,t){let n=e.split(`
79
+ `)}\n`}function wp(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 Sp(e,t){let n=e.split(`
83
+ `)}\n`:``}function Tp(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 Cp(e,t,n){let r=e.split(`
85
+ `)}\n`:``)}function Ep(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 wp(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 Tp(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 Ep=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 Dp(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:Ep,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await lp(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 Op=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 kp(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:Op,async execute(n,r){try{let n=r.scope??`all`,i=await rp(e),a=[];for(let n of i.slice(0,30)){let r=await sp(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
89
- `),t=Tp(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 Dp(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 Op(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 kp=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 Ap(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:kp,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await fp(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 jp=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 Mp(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:jp,async execute(n,r){try{let n=r.scope??`all`,i=await op(e),a=[];for(let n of i.slice(0,30)){let r=await up(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
89
+ `),t=Op(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 Ap=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 jp(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:Ap,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=wp(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=xp(await ap(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 up(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 sp(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(`
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 up(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 sp(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=Sp(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 up(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 dp(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 op(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await dp(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 Mp=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 Np(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:Mp,async execute(n,r){try{let n=wp(r.id);if(n.section){let i=bp(await ap(e)??``,n.section,r.content);return await up(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 sp(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=Cp(i.join(`
95
- `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await up(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 up(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 Pp=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 Fp(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:Pp,async execute(n,r){let i=Ip(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Lp(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 Rp({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=Zp(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:Jp(qp(await m(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Xp({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 Ip(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Lp(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 Rp(e){let t=e.messageLimit??50,n=(await y(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Hp(e.query),i=(await Qp(n,6,async t=>zp({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Kp).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 zp(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||!Bp(n,t.terms))continue;let i;try{i=JSON.parse(n)}catch{continue}if(!Vp(i.role)||t.roleFilter&&i.role!==t.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Wp(i.content,t.terms,i.role);if(a<=0)continue;let o=Gp(i.content);r.push({sessionId:t.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),r.length>20&&(r.sort(Kp),r.length=20)}return r.sort(Kp),r}function Bp(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Vp(e){return e===`user`||e===`assistant`||e===`tool_result`}function Hp(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=>Up(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 Up(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 Wp(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 Gp(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Kp(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function qp(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function Jp(e,t,n){if(e.length===0)return e;let r=Hp(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 Yp(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 Yp(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 Xp(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 Zp(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 Qp(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 $p(e){return H.join(e,`.aimax`,`skills`)}function em(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function tm(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${em(n)}\n`)}function nm(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 rm(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 im(e){return(await V.stat(e)).mtime.toISOString()}async function am(e){return sm([$p(e)])}async function om(e,t,n=[]){return sm([...n,...t,$p(e)])}async function sm(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=nm(i),o=rm(i),s=await im(r)}catch(t){tm(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 cm(e,t){let n=t.trim();if(!n)return;let r=(await sm(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:H.dirname(r.location)}}async function lm(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=nm(o),c=rm(o),l=await im(a)}catch(e){tm(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:H.dirname(a)}}async function um(e,t,n){let r=n?.trim()?await lm(t,n):await cm(e,t);if(!r)return;let i=await V.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function dm(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 Np=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 Pp(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:Np,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Dp(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=wp(await cp(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 pp(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 up(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(`
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 pp(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 up(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=Tp(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 pp(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 mp(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 lp(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await mp(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 Fp=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 Ip(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:Fp,async execute(n,r){try{let n=Dp(r.id);if(n.section){let i=Cp(await cp(e)??``,n.section,r.content);return await pp(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 up(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=Ep(i.join(`
95
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await pp(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 pp(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 Lp=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 Rp(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:Lp,async execute(n,r){let i=zp(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Bp(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 Vp({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=em(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:Zp(Xp(await m(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:$p({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 zp(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Bp(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 Vp(e){let t=e.messageLimit??50,n=(await y(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Gp(e.query),i=(await tm(n,6,async t=>Hp({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Yp).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 Hp(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||!Up(n,t.terms))continue;let i;try{i=JSON.parse(n)}catch{continue}if(!Wp(i.role)||t.roleFilter&&i.role!==t.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=qp(i.content,t.terms,i.role);if(a<=0)continue;let o=Jp(i.content);r.push({sessionId:t.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),r.length>20&&(r.sort(Yp),r.length=20)}return r.sort(Yp),r}function Up(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Wp(e){return e===`user`||e===`assistant`||e===`tool_result`}function Gp(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=>Kp(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 Kp(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 qp(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 Jp(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Yp(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Xp(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function Zp(e,t,n){if(e.length===0)return e;let r=Gp(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 Qp(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 Qp(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 $p(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 em(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 tm(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 nm(e){return H.join(e,`.aimax`,`skills`)}function rm(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function im(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${rm(n)}\n`)}function am(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 om(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 sm(e){return(await V.stat(e)).mtime.toISOString()}async function cm(e){return um([nm(e)])}async function lm(e,t,n=[]){return um([...n,...t,nm(e)])}async function um(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=am(i),o=om(i),s=await sm(r)}catch(t){im(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 dm(e,t){let n=t.trim();if(!n)return;let r=(await um(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:H.dirname(r.location)}}async function fm(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=am(o),c=om(o),l=await sm(a)}catch(e){im(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:H.dirname(a)}}async function pm(e,t,n){let r=n?.trim()?await fm(t,n):await dm(e,t);if(!r)return;let i=await V.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function mm(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 fm=W.Object({category:W.Optional(W.String({description:`Reserved category filter field. Not used yet.`}))}),pm=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 mm(e,t,n=[]){return[...n,...t,$p(e)]}function hm(e,t,n=[]){let r=mm(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:fm,async execute(e,t){let n=await sm(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 gm(e){let t=mm(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:pm,async execute(r,i){let a=await um(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 _m=W.Object({});function vm(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:_m,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 ym=W.Object({status:W.String({description:`Status to set. Only 'complete' is allowed.`})});function bm(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:ym,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 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({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.`}))}),Cm=W.Object({tasks:W.Array(xm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function wm(e){let t=e.label?`"${e.label}"`:`task: ${We(e.task)}`;return e.status===`done`?`${t}\n\n${Tm(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Tm(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 Em(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=wm({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 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:`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:Sm,async execute(e,t){return Em(u,e,t)}}}function Om(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:Cm,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 Em(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${Tm(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
101
+ `)}\n</available_skills>`}const hm=W.Object({category:W.Optional(W.String({description:`Reserved category filter field. Not used yet.`}))}),gm=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 _m(e,t,n=[]){return[...n,...t,nm(e)]}function vm(e,t,n=[]){let r=_m(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:hm,async execute(e,t){let n=await um(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 ym(e){let t=_m(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:gm,async execute(r,i){let a=await pm(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 bm=W.Object({});function xm(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:bm,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 Sm=W.Object({status:W.String({description:`Status to set. Only 'complete' is allowed.`})});function Cm(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:Sm,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 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({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.`}))}),Em=W.Object({tasks:W.Array(wm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Dm(e){let t=e.label?`"${e.label}"`:`task: ${We(e.task)}`;return e.status===`done`?`${t}\n\n${Om(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Om(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 km(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=Dm({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 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:`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:Tm,async execute(e,t){return km(u,e,t)}}}function jm(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:Em,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 km(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${Om(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 km=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 Am(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 jm(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 Mm(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:km,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} (${Am(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=jm(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 Nm(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 Pm(e){let t=Nm(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 Fm(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=Pm({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 Im(e){return e.projectDir?.trim()||H.join(e.dataDir,`workspace`)}async function Lm(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Im(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Bm(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=Fm({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,zm({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 Rm(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function zm(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 Bm(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 Vm=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 Hm(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Vm,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 Um=W.Object({reason:W.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Wm(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??Um,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 Gm(e,t){let n=Im({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=Sf(),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=[sf({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),df({registry:i,scopeKey:n}),kf(n,t?.contextManager),jf(n,t?.contextManager,s),Nf(n,t?.contextManager,s),Ff(n),Hf(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[vm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),bm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId)]:[],pp(e,r),Fp(e,r),hp(e,r),yp(e,r),Dp(e,r),kp(e,r),jp(e,r),Np(e,r),hm(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),gm({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(Dm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Om(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Mm(t.registry,t.parentSessionId)),c}function Km(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 Mm=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 Nm(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 Pm(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 Fm(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:Mm,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} (${Nm(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=Pm(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 Im(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 Lm(e){let t=Im(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 Rm(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=Lm({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 zm(e){return e.projectDir?.trim()||H.join(e.dataDir,`workspace`)}async function Bm(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=zm(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Um(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=Rm({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,Hm({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 Vm(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Hm(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 Um(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 Wm=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 Gm(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Wm,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 Km=W.Object({reason:W.String({description:`A brief explanation of why user input is needed through this UI form.`})});function qm(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??Km,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 Jm(e,t){let n=zm({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=Tf(),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=[sf({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),df({registry:i,scopeKey:n}),Mf(n,t?.contextManager),Pf(n,t?.contextManager,s),If(n,t?.contextManager,s),Rf(n),Gf(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[xm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),Cm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId)]:[],gp(e,r),Rp(e,r),vp(e,r),Sp(e,r),Ap(e,r),Mp(e,r),Pp(e,r),Ip(e,r),vm(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),ym({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(Am(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),jm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Fm(t.registry,t.parentSessionId)),c}function Ym(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 qm={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`},Jm=[`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 Ym(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:[...Jm.filter(e=>t.has(e)),...n.filter(e=>!Jm.includes(e)).sort()],displayName:t}}function Xm(e){let{ordered:t,displayName:n}=Ym(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)??qm[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
106
+ `)}const Xm={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`},Zm=[`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 Qm(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:[...Zm.filter(e=>t.has(e)),...n.filter(e=>!Zm.includes(e)).sort()],displayName:t}}function $m(e){let{ordered:t,displayName:n}=Qm(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)??Xm[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
107
107
  `),``].join(`
108
- `)}function Zm(){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 Qm(){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 $m(){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 eh(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 th(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 eh(){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 th(){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 nh(){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 rh(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 ih(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 nh(e=[]){let t=Km(e).trim();return t?`${t}\n`:``}function rh(){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 ih(){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 ah(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 oh(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 sh(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 ch(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=lh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
121
- `)}function lh(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 uh(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 dh(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 fh(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 ph(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 mh(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 hh(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 gh(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:[...Jm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,mh(e.subagentDepth??0),Xm({toolNames:i,toolSummaries:e.toolSummaries}),eh(n),Zm(),Qm(),Lr(e.availableAgents??[]),th(a),nh(e.autoSkillCategories),rh(),ih(),ah(e.memoryCitationsMode??`off`),oh({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),sh(e.sandboxInfo),ch({currentDate:e.currentDate,timezone:e.timezone}),$m(),uh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),fh({isMinimal:n}),dh(e.runtimeInfo),ph({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),hh(e.priorConversationSummary)].filter(Boolean).join(`
128
- `)}const _h=Symbol(`pluginToolOwner`);var vh=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,_h,{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=Wm({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,_h,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function yh(e){return e[_h]}function bh(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=yh(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 xh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Sh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Ch(e){let t=Sh(e?.warningThreshold,xh.warningThreshold),n=Sh(e?.criticalThreshold,xh.criticalThreshold),r=Sh(e?.globalCircuitBreakerThreshold,xh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??xh.enabled,historySize:Sh(e?.historySize,xh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??xh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??xh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??xh.detectors.pingPong}}}function wh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Th(e,t){return`${e}:${Oh(t)}`}function Eh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Eh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Eh(t[e])}`).join(`,`)}}`}function Dh(e){try{return Eh(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 Oh(e){let t=Dh(e);return Xe(`sha256`).update(t).digest(`hex`)}function kh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!wh(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Ah(e){return!wh(e)||!Array.isArray(e.content)?``:e.content.filter(e=>wh(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
129
- `).trim()}function jh(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Eh(e)}function Mh(e,t,n,r){if(r!==void 0)return`error:${Oh(jh(r))}`;if(!wh(n))return n===void 0?void 0:Oh(n);let i=wh(n.details)?n.details:{},a=Ah(n);if(kh(e,t)&&e===`process`&&wh(t)){let e=t.action;if(e===`poll`)return Oh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Oh({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 Oh({details:i,text:a})}function Nh(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 Ph(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 Fh(e,t){return[e,t].toSorted().join(`|`)}function Ih(e,t,n,r){let i=Ch(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Th(t,n),s=Nh(a,t,o),c=s.count,l=kh(t,n),u=Ph(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:${Fh(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 Lh(e,t,n,r,i){let a=Ch(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Th(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Rh(e,t){let n=Ch(t.config),r=Mh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Th(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 zh(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 Bh(e){return e&&e.trim()||`tool`}function Vh(e,t,n){if(!e.execute)return e;let r=Bh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Ih(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);zh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Lh(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Rh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Rh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Hh(e,t,n){return e.map(e=>Vh(e,t,n))}function Uh(e){let t=e.streamFn??lt;return(e,n,r)=>(e.api===`anthropic-messages`&&Wh(e),t(e,n,{...r,...Zh(e,r)}))}function Wh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>qh(Xh(e),n)?(globalThis.fetch=t,Gh(await t(e,Jh(e,r)))):t(e,r))}function Gh(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(Kh))),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 Kh=`event: message_start
115
+ `)}function ah(e=[]){let t=Ym(e).trim();return t?`${t}\n`:``}function oh(){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 sh(){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 ch(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 lh(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 uh(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 dh(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=fh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
121
+ `)}function fh(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 ph(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 mh(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 hh(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 gh(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 _h(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 vh(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 yh(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:[...Zm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,_h(e.subagentDepth??0),$m({toolNames:i,toolSummaries:e.toolSummaries}),rh(n),eh(),th(),Lr(e.availableAgents??[]),ih(a),ah(e.autoSkillCategories),oh(),sh(),ch(e.memoryCitationsMode??`off`),lh({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),uh(e.sandboxInfo),dh({currentDate:e.currentDate,timezone:e.timezone}),nh(),ph({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),hh({isMinimal:n}),mh(e.runtimeInfo),gh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),vh(e.priorConversationSummary)].filter(Boolean).join(`
128
+ `)}const bh=Symbol(`pluginToolOwner`);var xh=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,bh,{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=qm({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,bh,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Sh(e){return e[bh]}function Ch(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=Sh(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 wh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Th(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Eh(e){let t=Th(e?.warningThreshold,wh.warningThreshold),n=Th(e?.criticalThreshold,wh.criticalThreshold),r=Th(e?.globalCircuitBreakerThreshold,wh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??wh.enabled,historySize:Th(e?.historySize,wh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??wh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??wh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??wh.detectors.pingPong}}}function Dh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Oh(e,t){return`${e}:${jh(t)}`}function kh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(kh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${kh(t[e])}`).join(`,`)}}`}function Ah(e){try{return kh(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 jh(e){let t=Ah(e);return Xe(`sha256`).update(t).digest(`hex`)}function Mh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Dh(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Nh(e){return!Dh(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Dh(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
129
+ `).trim()}function Ph(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:kh(e)}function Fh(e,t,n,r){if(r!==void 0)return`error:${jh(Ph(r))}`;if(!Dh(n))return n===void 0?void 0:jh(n);let i=Dh(n.details)?n.details:{},a=Nh(n);if(Mh(e,t)&&e===`process`&&Dh(t)){let e=t.action;if(e===`poll`)return jh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return jh({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 jh({details:i,text:a})}function Ih(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 Lh(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 Rh(e,t){return[e,t].toSorted().join(`|`)}function zh(e,t,n,r){let i=Eh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Oh(t,n),s=Ih(a,t,o),c=s.count,l=Mh(t,n),u=Lh(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:${Rh(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 Bh(e,t,n,r,i){let a=Eh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Oh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Vh(e,t){let n=Eh(t.config),r=Fh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Oh(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 Hh(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 Uh(e){return e&&e.trim()||`tool`}function Wh(e,t,n){if(!e.execute)return e;let r=Uh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=zh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Hh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Bh(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Vh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Vh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Gh(e,t,n){return e.map(e=>Wh(e,t,n))}function Kh(e){let t=e.streamFn??lt;return(e,n,r)=>(e.api===`anthropic-messages`&&qh(e),t(e,n,{...r,...eg(e,r)}))}function qh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Xh($h(e),n)?(globalThis.fetch=t,Jh(await t(e,Zh(e,r)))):t(e,r))}function Jh(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(Yh))),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 Yh=`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 qh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Jh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Yh(e)&&n.delete(e);return{...t,headers:n}}function Yh(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 Xh(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function Zh(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function Qh(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 tg({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([...Gm(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=gh({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 $h({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=Hh(bh(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:Uh({})});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 $h(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 eg(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 tg({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 tg({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 tg(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=ng(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 ng(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 Xh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Zh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Qh(e)&&n.delete(e);return{...t,headers:n}}function Qh(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 $h(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function eg(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function tg(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 ig({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([...Jm(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=yh({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 ng({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=Gh(Ch(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:Kh({})});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 ng(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 rg(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 ig({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 ig({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 ig(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=ag(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 ag(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 rg(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=ig(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Ea({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 ig(e){if(e.length===1){let t=e[0];return wm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>wm({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 og(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=sg(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Ea({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 sg(e){if(e.length===1){let t=e[0];return Dm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Dm({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 ag(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function og(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function sg(){let e=vt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function cg(e){let t=e.trim(),n=sg();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?H.join(n,t.slice(2)):void 0:H.resolve(t)}const lg=new St({allErrors:!0,strict:!1}),ug=new Map;function dg(e,t){let n=ug.get(t);if(n)return n;let r=lg.compile(e);return ug.set(t,r),r}function fg(e){let t=e.cacheKey??JSON.stringify(e.schema),n=dg(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function pg(e){let t=og(e?.allow),n=og(e?.deny),r=og(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 mg(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=fg({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 hg(e){try{return U.realpathSync(e)}catch{return null}}function gg(e){try{return U.statSync(e)}catch{return null}}function _g(e,t){let n=H.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!H.isAbsolute(n)}function vg(e){return`0o${e.toString(8).padStart(3,`0`)}`}const yg=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),bg=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function xg(e){let t=H.join(e,`package.json`);if(U.existsSync(t))try{let e=JSON.parse(U.readFileSync(t,`utf-8`));return ag(e)?e:void 0}catch{return}}function Sg(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 Cg(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function wg(e){let t=hg(e.source),n=hg(e.rootDir);return!t||!n||_g(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Tg(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=gg(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 Eg(e){return wg({source:e.source,rootDir:e.rootDir})||Tg({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Cg(e.ownershipUid)})}function Dg(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=${vg(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Og(e){let t=Eg({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Dg(t),source:e.source}),!0):!1}function kg(e){return H.basename(e,H.extname(e))}function Ag(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 jg(e){for(let t of bg){let n=H.join(e,t);if(U.existsSync(n))return n}return null}function Mg(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(!yg.has(H.extname(n.name)))continue;let r=H.dirname(t);if(Og({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Ag({idHint:kg(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=xg(t),i=Sg(r);if(i.status===`ok`){for(let n of i.entries){let i=H.resolve(t,n);if(!_g(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(!yg.has(H.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Og({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${kg(i)}`:kg(i);e.candidates.push(Ag({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=jg(t);a&&(Og({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Ag({idHint:H.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Ng(e){return e?e.map(cg).filter(e=>typeof e==`string`&&e.length>0):[]}function Pg(){let e=sg();if(e)return H.join(e,`.aimax`,`extensions`)}function Fg(e){return H.join(e,`.aimax`,`extensions`)}function Ig(e){return H.join(e,`.aimax`,`extensions`)}function Lg(e={}){let t=[],n=[],r=Ng(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=gg(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!yg.has(H.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=H.dirname(i);if(Og({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Ag({idHint:kg(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Mg({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Mg({rootDir:Fg(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Mg({rootDir:Ig(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Pg();return i?Mg({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&&Mg({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Rg(e){let t=e.rejectHardlinks??!0,n=hg(e.rootPath),r=hg(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!_g(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 zg=`aimax.plugin.json`,Bg=[zg];function Vg(e){for(let t of Bg){let n=H.join(e,t);if(U.existsSync(n))return n}return H.join(e,zg)}function Hg(e,t=!0){let n=Vg(e),r=Rg({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(!ag(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=ag(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=og(i.skills),f;return ag(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 Ug(e){let t=new Map,n=[];for(let r of e){let e=Hg(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 Wg=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Gg(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Wg.ERROR){q.error(i);return}if(e===Wg.WARN){q.warn(i);return}q.info(i)}function Kg(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Gg(Wg.INFO,e.pluginId,t,n),warn:n=>Gg(Wg.WARN,e.pluginId,t,n),error:n=>Gg(Wg.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}function qg(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 Jg(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 Yg(e){let t=[...e.registry.diagnostics],n=new vh,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=Xg(e.runtime?.llmAllowlist),c=Ct(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=qg({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Jg({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=Kg({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(!Zg(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 Xg(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Zg(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Qg(e={}){let t=pg(e.config),n=Lg({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Ug(n.candidates),i=mg({config:t,registry:r}),a=Yg({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 $g(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Qg({...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 e_(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Im(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=$g({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await Lm({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 t_(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function n_(e){if(!(e instanceof Error))return{errorValue:t_(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]=t_(n[e]));return t}async function r_(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...n_(e.error)}})}function i_(e,t,n){return H.join(d(e,t,n),`pending-ui-tool.json`)}async function a_(e,t,n,r){let i=d(e,t,r);await V.mkdir(i,{recursive:!0}),await a(i_(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function o_(e,t,n){let r=await l(i_(e,t,n));return r===null?null:JSON.parse(r)}async function s_(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await a_(e,t,a,r),a}async function c_(e,t,n,r,i){let a=await o_(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 a_(e,t,o,i),o}async function l_(e,t,n){try{await V.unlink(i_(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function u_(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 d_(e,t,n,r,i,a){let o=await z(e,t,{storeName:a?.storeName});await u_(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 f_(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ke(t))}async function p_(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=m_(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 m_(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 h_=2e4,g_=15e4,__=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function v_(e){return H.join(e,`.aimax`)}async function y_(e){let t=v_(e),n=[];for(let e of __){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 b_(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 cg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lg(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function ug(){let e=vt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function dg(e){let t=e.trim(),n=ug();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?H.join(n,t.slice(2)):void 0:H.resolve(t)}const fg=new St({allErrors:!0,strict:!1}),pg=new Map;function mg(e,t){let n=pg.get(t);if(n)return n;let r=fg.compile(e);return pg.set(t,r),r}function hg(e){let t=e.cacheKey??JSON.stringify(e.schema),n=mg(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function gg(e){let t=lg(e?.allow),n=lg(e?.deny),r=lg(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 _g(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=hg({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 vg(e){try{return U.realpathSync(e)}catch{return null}}function yg(e){try{return U.statSync(e)}catch{return null}}function bg(e,t){let n=H.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!H.isAbsolute(n)}function xg(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Sg=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Cg=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function wg(e){let t=H.join(e,`package.json`);if(U.existsSync(t))try{let e=JSON.parse(U.readFileSync(t,`utf-8`));return cg(e)?e:void 0}catch{return}}function Tg(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 Eg(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Dg(e){let t=vg(e.source),n=vg(e.rootDir);return!t||!n||bg(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Og(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=yg(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 kg(e){return Dg({source:e.source,rootDir:e.rootDir})||Og({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Eg(e.ownershipUid)})}function Ag(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=${xg(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function jg(e){let t=kg({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Ag(t),source:e.source}),!0):!1}function Mg(e){return H.basename(e,H.extname(e))}function Ng(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 Pg(e){for(let t of Cg){let n=H.join(e,t);if(U.existsSync(n))return n}return null}function Fg(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(!Sg.has(H.extname(n.name)))continue;let r=H.dirname(t);if(jg({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Ng({idHint:Mg(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=wg(t),i=Tg(r);if(i.status===`ok`){for(let n of i.entries){let i=H.resolve(t,n);if(!bg(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(!Sg.has(H.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(jg({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Mg(i)}`:Mg(i);e.candidates.push(Ng({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=Pg(t);a&&(jg({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Ng({idHint:H.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Ig(e){return e?e.map(dg).filter(e=>typeof e==`string`&&e.length>0):[]}function Lg(){let e=ug();if(e)return H.join(e,`.aimax`,`extensions`)}function Rg(e){return H.join(e,`.aimax`,`extensions`)}function zg(e){return H.join(e,`.aimax`,`extensions`)}function Bg(e={}){let t=[],n=[],r=Ig(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=yg(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Sg.has(H.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=H.dirname(i);if(jg({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Ng({idHint:Mg(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Fg({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Fg({rootDir:Rg(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Fg({rootDir:zg(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Lg();return i?Fg({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&&Fg({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Vg(e){let t=e.rejectHardlinks??!0,n=vg(e.rootPath),r=vg(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!bg(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 Hg=`aimax.plugin.json`,Ug=[Hg];function Wg(e){for(let t of Ug){let n=H.join(e,t);if(U.existsSync(n))return n}return H.join(e,Hg)}function Gg(e,t=!0){let n=Wg(e),r=Vg({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(!cg(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=cg(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=lg(i.skills),f;return cg(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 Kg(e){let t=new Map,n=[];for(let r of e){let e=Gg(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 qg=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Jg(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===qg.ERROR){q.error(i);return}if(e===qg.WARN){q.warn(i);return}q.info(i)}function Yg(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Jg(qg.INFO,e.pluginId,t,n),warn:n=>Jg(qg.WARN,e.pluginId,t,n),error:n=>Jg(qg.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}function Xg(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 Zg(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 Qg(e){let t=[...e.registry.diagnostics],n=new xh,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=$g(e.runtime?.llmAllowlist),c=Ct(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Xg({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Zg({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=Yg({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(!e_(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 $g(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function e_(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function t_(e={}){let t=gg(e.config),n=Bg({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Kg(n.candidates),i=_g({config:t,registry:r}),a=Qg({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 n_(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?t_({...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 r_(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=zm(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=n_({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await Bm({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 i_(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function a_(e){if(!(e instanceof Error))return{errorValue:i_(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]=i_(n[e]));return t}async function o_(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...a_(e.error)}})}function s_(e,t,n){return H.join(d(e,t,n),`pending-ui-tool.json`)}async function c_(e,t,n,r){let i=d(e,t,r);await V.mkdir(i,{recursive:!0}),await a(s_(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function l_(e,t,n){let r=await l(s_(e,t,n));return r===null?null:JSON.parse(r)}async function u_(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await c_(e,t,a,r),a}async function d_(e,t,n,r,i){let a=await l_(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 c_(e,t,o,i),o}async function f_(e,t,n){try{await V.unlink(s_(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function p_(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 m_(e,t,n,r,i,a){let o=await z(e,t,{storeName:a?.storeName});await p_(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 h_(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ke(t))}async function g_(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=__(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 __(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 v_=2e4,y_=15e4,b_=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function x_(e){return H.join(e,`.aimax`)}async function S_(e){let t=x_(e),n=[];for(let e of b_){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 C_(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 x_(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function S_(e,t){let n=t?.maxChars??h_,r=Math.max(1,t?.totalMaxChars??Math.max(n,g_)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=x_(`[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}=b_(a.content??``,a.name,e),l=x_(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 C_=`You are a personal assistant running inside AiMax.`;async function w_(e){try{return{presetSystemPrompt:$e(await V.readFile(e,`utf-8`)).content.trim()||C_}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:C_};throw e}}async function T_(){return w_(`/aimax_pvc/system_prompt.md`)}async function E_(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await y_(t.dataDir),o=[],s=S_(a,{warn:e=>o.push(e)}),c=await T_();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 om(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 D_({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function D_(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 O_=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 k_=`crons`;function A_(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:si(e.message)}}async function j_(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 e_({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,Rm({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 E_({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 Qh({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=>j_(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=L_(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 O_,j=``,M,ee=!1,P=new wt;await u_(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=>j_(e,new Xs),createModel:Sr,abortSignal:v.signal},I=(e,t,n)=>({turnKind:e,budget:F,reloadHistory:()=>eg({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(f_(e)){let t=await p_({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 Ea({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 d_(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 rg({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 d_(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 Ea({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 d_(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 rg({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 M_({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 s_(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 M_({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&&R_(t))M=`Run timed out after ${D}ms`;else throw await r_({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 d_(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 M_({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 M_(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 N_(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,...A_(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,Rm({sessionId:c,title:cc(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:k_});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:k_,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await j_(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:k_}),toolResultsDir:S(e.dataDir,u,{storeName:k_})}},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 _=wm({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=>P_(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 P_(e,t){if(t<=0)return e.filter(e=>!F_(e));let n=e.reduce((e,t,n)=>(F_(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!F_(e)||r.has(t))}function F_(e){return`source`in e&&e.source===`cron`}async function I_(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,...A_(e)}),e.channel===`CRON`&&!e.subagentContext)return N_(e);let n=t??new Xs;try{return await j_(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:n_(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 L_(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:6e5}function R_(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 z_={"AGENTS.md":`---
144
+ `),truncated:!0,originalLength:r.length}}function w_(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function T_(e,t){let n=t?.maxChars??v_,r=Math.max(1,t?.totalMaxChars??Math.max(n,y_)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=w_(`[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}=C_(a.content??``,a.name,e),l=w_(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 E_=`You are a personal assistant running inside AiMax.`;async function D_(e){try{return{presetSystemPrompt:$e(await V.readFile(e,`utf-8`)).content.trim()||E_}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:E_};throw e}}async function O_(){return D_(`/aimax_pvc/system_prompt.md`)}async function k_(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await S_(t.dataDir),o=[],s=T_(a,{warn:e=>o.push(e)}),c=await O_();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 lm(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 A_({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function A_(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 j_=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 M_=`crons`;function N_(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:si(e.message)}}async function P_(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 r_({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,Vm({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 k_({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 tg({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=>P_(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=B_(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 j_,j=``,M,ee=!1,P=new wt;await p_(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=>P_(e,new Xs),createModel:Sr,abortSignal:v.signal},I=(e,t,n)=>({turnKind:e,budget:F,reloadHistory:()=>rg({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(h_(e)){let t=await g_({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 Ea({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 m_(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 og({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 m_(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 Ea({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 m_(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 og({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 F_({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 u_(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 F_({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&&V_(t))M=`Run timed out after ${D}ms`;else throw await o_({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 m_(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 F_({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 F_(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 I_(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,...N_(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,Vm({sessionId:c,title:cc(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:M_});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:M_,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await P_(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:M_}),toolResultsDir:S(e.dataDir,u,{storeName:M_})}},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 _=Dm({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=>L_(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 L_(e,t){if(t<=0)return e.filter(e=>!R_(e));let n=e.reduce((e,t,n)=>(R_(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!R_(e)||r.has(t))}function R_(e){return`source`in e&&e.source===`cron`}async function z_(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,...N_(e)}),e.channel===`CRON`&&!e.subagentContext)return I_(e);let n=t??new Xs;try{return await P_(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:a_(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 B_(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:6e5}function V_(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 H_={"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
- `},B_=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function V_(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 H_(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 U_(e){let t=v_(e);return[e,t,H.join(t,`skills`),H.join(t,`sessions`),H.join(t,`memory`),H.join(e,`workspace`)]}function W_(e){let t=v_(e);return[...B_.filter(e=>e!==`BOOTSTRAP.md`).map(e=>H.join(t,e)),H.join(t,`MEMORY.md`)]}function G_(e){return H.join(v_(e),`.bootstrapped`)}async function K_(e){try{return(await V.stat(G_(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function q_(e){let t=G_(e);await V.mkdir(H.dirname(t),{recursive:!0}),await V.writeFile(t,``,{encoding:`utf-8`})}async function J_(e){let t=[],n=[];for(let n of U_(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 W_(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 Y_(e){return(await J_(e)).ready}async function X_(e){if(await K_(e))return{ready:!0,performedBootstrap:!1};if((await J_(e)).ready)return await q_(e),{ready:!0,performedBootstrap:!1};let t=await Z_(e);return await q_(e),{ready:!0,performedBootstrap:!0,result:t}}async function Z_(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=v_(e),r=H.join(e,`workspace`),i=H.join(n,`skills`),a=H.join(n,`sessions`),o=H.join(n,`memory`);await V_(e,t),await V_(n,t),await V_(i,t),await V_(a,t),await V_(o,t),await V_(r,t);for(let e of B_){let r=z_[e]??``;await H_(H.join(n,e),r,t)}return await H_(H.join(n,`MEMORY.md`),``,t),t}async function Q_(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 $_(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 ev(e,t){let n=await Q_(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 tv(e,t=7){let n=await Q_(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 $_(e,n),i}var nv=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function rv(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function iv(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 nv(`A different goal already exists for this session. Use --force to replace it.`,rv(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 nv(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,rv(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 av(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 ov(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 av(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 sv={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 cv(e){return e.action===`timeout`?sv.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?sv.approval.summary.approved:sv.approval.summary.denied}function lv(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:cv(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function uv(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 dv(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 fv(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
437
+ `},U_=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function W_(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 G_(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 K_(e){let t=x_(e);return[e,t,H.join(t,`skills`),H.join(t,`sessions`),H.join(t,`memory`),H.join(e,`workspace`)]}function q_(e){let t=x_(e);return[...U_.filter(e=>e!==`BOOTSTRAP.md`).map(e=>H.join(t,e)),H.join(t,`MEMORY.md`)]}function J_(e){return H.join(x_(e),`.bootstrapped`)}async function Y_(e){try{return(await V.stat(J_(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function X_(e){let t=J_(e);await V.mkdir(H.dirname(t),{recursive:!0}),await V.writeFile(t,``,{encoding:`utf-8`})}async function Z_(e){let t=[],n=[];for(let n of K_(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 q_(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 Q_(e){return(await Z_(e)).ready}async function $_(e){if(await Y_(e))return{ready:!0,performedBootstrap:!1};if((await Z_(e)).ready)return await X_(e),{ready:!0,performedBootstrap:!1};let t=await ev(e);return await X_(e),{ready:!0,performedBootstrap:!0,result:t}}async function ev(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=x_(e),r=H.join(e,`workspace`),i=H.join(n,`skills`),a=H.join(n,`sessions`),o=H.join(n,`memory`);await W_(e,t),await W_(n,t),await W_(i,t),await W_(a,t),await W_(o,t),await W_(r,t);for(let e of U_){let r=H_[e]??``;await G_(H.join(n,e),r,t)}return await G_(H.join(n,`MEMORY.md`),``,t),t}async function tv(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 nv(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 rv(e,t){let n=await tv(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 iv(e,t=7){let n=await tv(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 nv(e,n),i}var av=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function ov(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function sv(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 av(`A different goal already exists for this session. Use --force to replace it.`,ov(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 av(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,ov(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 cv(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 lv(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 cv(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 uv={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 dv(e){return e.action===`timeout`?uv.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?uv.approval.summary.approved:uv.approval.summary.denied}function fv(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:dv(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function pv(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 mv(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 hv(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,__ as BOOTSTRAP_FILE_NAMES,h_ as BOOTSTRAP_MAX_CHARS,g_ 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,nv as GoalConflictError,sv 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,zg as PLUGIN_MANIFEST_FILENAME,Bg as PLUGIN_MANIFEST_FILENAMES,qr as PluginHookRegistry,vh 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,v_ as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,te as appendGoalEvent,lp as appendRecentToMemory,o as appendSessionFile,cp as appendToMemory,p as appendTranscriptEntry,iv as applyCliGoalBeforeRun,cv as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,wn as autoSkillsDir,Z_ as bootstrapMountLayout,Lr as buildAgentDelegationPrompt,Rr as buildAgentTaskPrompt,_c as buildAimaxGoalCliHelpExtra,S_ as buildBootstrapContextFiles,Ot as buildBudgetLimitPrompt,Dt as buildContinuationPrompt,At as buildGoalContextItem,gc as buildGoalSlashHelpText,kt as buildObjectiveUpdatedPrompt,fv as buildResumeNarration,dm as buildSkillsPrompt,wm as buildSubagentAnnounceMessage,gh as buildSystemPrompt,tv as cleanupOldSubagentRecords,we as clearPendingHitl,l_ as clearPendingUiTool,k as collapseLogPath,Bt as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,It as continuationTurnHadMeaningfulOutput,Dr as createAgentDefinitionsContext,Gm as createAgentTools,Hf as createApplyPatchTool,Eo as createAutoSkillCategoriesTool,Do as createAutoSkillListTool,Oo as createAutoSkillSearchTool,ko as createAutoSkillViewTool,Vn as createAutoSkillsLoader,Cf as createBashTool,Om as createBatchSubagentSpawnTool,le as createBuiltinMemoryProvider,Jd as createContextManager,Nf as createEditFileTool,sf as createExecTool,Hm as createImageTool,Ff as createListDirTool,_p as createMemoryAppendTool,jp as createMemoryForgetTool,hp as createMemoryGetTool,kp as createMemoryListTool,Dp as createMemoryLogTool,pp as createMemorySearchTool,Np as createMemoryUpdateTool,yp as createMemoryWriteTool,be as createPendingHitl,s_ as createPendingUiTool,Kr as createPluginProgressEmitter,Kg as createPluginRuntime,df as createProcessTool,kf as createReadFileTool,C as createSession,xd as createSessionContextStore,Fp as createSessionSearchTool,hm as createSkillListTool,gm as createSkillLoadTool,Dm as createSubagentSpawnTool,Mm as createSubagentsTool,Wm as createUiTool,jf as createWriteFileTool,j as cronExecutionsPath,Um as defaultUiToolInputSchema,ie as deleteGoal,dp as deleteMemoryFile,Lg as discoverAIMaxPlugins,fl as emitGoalUpdatedProgress,X_ as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,Fr as filterSkillsForAgent,Ir as filterToolsForAgent,Mr as findAgentDefinition,cm as findSkillByName,Tt as flushAccounting,lv as formatApprovalResolution,uv as formatClarifyResolution,dv as formatReviewResolution,rc as generateSessionTitle,Me as getAgentConfig,sp as getMemoryLines,F as goalEventsPath,R as goalObjectiveMdPath,re as goalPath,K_ as hasBootstrapSentinel,ve as hitlHistoryPath,Qg as initializePluginSystem,J_ as inspectBootstrapMountLayout,D as inspectSession,Y_ as isBootstrapMountLayoutReady,Pt as isContinuationEnabled,jt as isGoalContext,bi as isHitlPauseSignal,Si as isUiToolPauseSignal,Ee as listAgents,Oc as listAvailableSlashCommands,Ie as listBindings,rp as listMemoryFiles,w as listSessionSummaries,y as listSessions,ev as listSubagentRunsFromDisk,Ar as loadAgentDefinitionsFromDir,Re as loadAgentsConfig,v as loadArtifactOperations,y_ as loadBootstrapFiles,f as loadCronExecutionRecords,Ce as loadPendingHitl,Ce as readPendingHitl,o_ as loadPendingUiTool,o_ as readPendingUiTool,Hg as loadPluginManifest,Ug as loadPluginManifestRegistry,Yg as loadPlugins,M as loadSessionContextSnapshot,P as loadSessionMetadata,um as loadSkillView,am as loadSkills,sm as loadSkillsFromDirs,om as loadSkillsWithPluginDirs,Q_ as loadSubagentRegistryFromDisk,m as loadTranscript,Lt as maybeContinueGoalIfIdle,ep as memoryDir,ee as metadataPath,ne as mirrorGoalStatusToSession,De as normalizeAgentId,pg as normalizePluginsConfig,u as normalizeSessionStoreName,jr as parseAgentDefinition,_e as pendingHitlPath,i_ as pendingUiToolPath,zt as prependObjectiveUpdatedSteeringIfNeeded,tp as primaryMemoryPath,Pr as publicAgentDefinitions,z as readGoal,xe as readHitlHistory,ip as readMemoryFile,ap as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,se as registerEmbeddingProvider,he as registerMemoryProvider,Ne as removeAgent,Be as removeBindings,up 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,ov as resolveHitlRequest,ov as resolvePendingHitl,me as resolveMemoryProvider,je as resolveModelFallbacks,Ae as resolveModelString,c_ as resolvePendingUiTool,Vg as resolvePluginManifestPath,t as rewriteTranscript,I_ as runAgent,Te as saveAgentsConfig,N as saveSessionMetadata,$_ as saveSubagentRegistryToDisk,Er as scanAgentDefinitions,op as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,Ft as shouldContinueGoal,$p as skillsDir,S as toolResultsDir,e as transcriptPath,ye as transitionHitlStatus,Ve as updateAgent,He as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,mg as validatePluginsConfig,av as validateResume,bh as wrapToolsWithHooks,L as writeGoal,a as writeSessionFile};
440
+ `))}export{K as AutoSkillsLoader,b_ as BOOTSTRAP_FILE_NAMES,v_ as BOOTSTRAP_MAX_CHARS,y_ 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,av as GoalConflictError,uv 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,Hg as PLUGIN_MANIFEST_FILENAME,Ug as PLUGIN_MANIFEST_FILENAMES,qr as PluginHookRegistry,xh 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,x_ as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,te as appendGoalEvent,fp as appendRecentToMemory,o as appendSessionFile,dp as appendToMemory,p as appendTranscriptEntry,sv as applyCliGoalBeforeRun,dv as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,wn as autoSkillsDir,ev as bootstrapMountLayout,Lr as buildAgentDelegationPrompt,Rr as buildAgentTaskPrompt,_c as buildAimaxGoalCliHelpExtra,T_ as buildBootstrapContextFiles,Ot as buildBudgetLimitPrompt,Dt as buildContinuationPrompt,At as buildGoalContextItem,gc as buildGoalSlashHelpText,kt as buildObjectiveUpdatedPrompt,hv as buildResumeNarration,mm as buildSkillsPrompt,Dm as buildSubagentAnnounceMessage,yh as buildSystemPrompt,iv as cleanupOldSubagentRecords,we as clearPendingHitl,f_ as clearPendingUiTool,k as collapseLogPath,Bt as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,It as continuationTurnHadMeaningfulOutput,Dr as createAgentDefinitionsContext,Jm as createAgentTools,Gf as createApplyPatchTool,Eo as createAutoSkillCategoriesTool,Do as createAutoSkillListTool,Oo as createAutoSkillSearchTool,ko as createAutoSkillViewTool,Vn as createAutoSkillsLoader,Ef as createBashTool,jm as createBatchSubagentSpawnTool,le as createBuiltinMemoryProvider,Jd as createContextManager,If as createEditFileTool,sf as createExecTool,Gm as createImageTool,Rf as createListDirTool,bp as createMemoryAppendTool,Pp as createMemoryForgetTool,vp as createMemoryGetTool,Mp as createMemoryListTool,Ap as createMemoryLogTool,gp as createMemorySearchTool,Ip as createMemoryUpdateTool,Sp as createMemoryWriteTool,be as createPendingHitl,u_ as createPendingUiTool,Kr as createPluginProgressEmitter,Yg as createPluginRuntime,df as createProcessTool,Mf as createReadFileTool,C as createSession,xd as createSessionContextStore,Rp as createSessionSearchTool,vm as createSkillListTool,ym as createSkillLoadTool,Am as createSubagentSpawnTool,Fm as createSubagentsTool,qm as createUiTool,Pf as createWriteFileTool,j as cronExecutionsPath,Km as defaultUiToolInputSchema,ie as deleteGoal,mp as deleteMemoryFile,Bg as discoverAIMaxPlugins,fl as emitGoalUpdatedProgress,$_ as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,Fr as filterSkillsForAgent,Ir as filterToolsForAgent,Mr as findAgentDefinition,dm as findSkillByName,Tt as flushAccounting,fv as formatApprovalResolution,pv as formatClarifyResolution,mv as formatReviewResolution,rc as generateSessionTitle,Me as getAgentConfig,up as getMemoryLines,F as goalEventsPath,R as goalObjectiveMdPath,re as goalPath,Y_ as hasBootstrapSentinel,ve as hitlHistoryPath,t_ as initializePluginSystem,Z_ as inspectBootstrapMountLayout,D as inspectSession,Q_ as isBootstrapMountLayoutReady,Pt as isContinuationEnabled,jt as isGoalContext,bi as isHitlPauseSignal,Si as isUiToolPauseSignal,Ee as listAgents,Oc as listAvailableSlashCommands,Ie as listBindings,op as listMemoryFiles,w as listSessionSummaries,y as listSessions,rv as listSubagentRunsFromDisk,Ar as loadAgentDefinitionsFromDir,Re as loadAgentsConfig,v as loadArtifactOperations,S_ as loadBootstrapFiles,f as loadCronExecutionRecords,Ce as loadPendingHitl,Ce as readPendingHitl,l_ as loadPendingUiTool,l_ as readPendingUiTool,Gg as loadPluginManifest,Kg as loadPluginManifestRegistry,Qg as loadPlugins,M as loadSessionContextSnapshot,P as loadSessionMetadata,pm as loadSkillView,cm as loadSkills,um as loadSkillsFromDirs,lm as loadSkillsWithPluginDirs,tv as loadSubagentRegistryFromDisk,m as loadTranscript,Lt as maybeContinueGoalIfIdle,rp as memoryDir,ee as metadataPath,ne as mirrorGoalStatusToSession,De as normalizeAgentId,gg as normalizePluginsConfig,u as normalizeSessionStoreName,jr as parseAgentDefinition,_e as pendingHitlPath,s_ as pendingUiToolPath,zt as prependObjectiveUpdatedSteeringIfNeeded,ip as primaryMemoryPath,Pr as publicAgentDefinitions,z as readGoal,xe as readHitlHistory,sp as readMemoryFile,cp as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,se as registerEmbeddingProvider,he as registerMemoryProvider,Ne as removeAgent,Be as removeBindings,pp 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,lv as resolveHitlRequest,lv as resolvePendingHitl,me as resolveMemoryProvider,je as resolveModelFallbacks,Ae as resolveModelString,d_ as resolvePendingUiTool,Wg as resolvePluginManifestPath,t as rewriteTranscript,z_ as runAgent,Te as saveAgentsConfig,N as saveSessionMetadata,nv as saveSubagentRegistryToDisk,Er as scanAgentDefinitions,lp as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,Ft as shouldContinueGoal,nm as skillsDir,S as toolResultsDir,e as transcriptPath,ye as transitionHitlStatus,Ve as updateAgent,He as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,_g as validatePluginsConfig,cv as validateResume,Ch 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.9.3-preview.3",
3
+ "version": "0.9.3-preview.5",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",