@gencode/agents 0.0.29 → 0.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +38 -38
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -29,52 +29,52 @@ import{C as e,D as t,E as n,S as r,T as i,_ as a,a as o,b as s,c,d as l,f as u,g
29
29
  `);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
30
30
 
31
31
  `)}function Qn(e){return e.role===`tool_result`}function $n(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function er(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function tr(e){return Math.max(256,e-Math.min(e/4,2e4))}async function nr(e,t,n){let r=m(e,t);await P.mkdir(F.dirname(r),{recursive:!0}),await P.appendFile(r,`${JSON.stringify(n)}\n`,`utf-8`)}async function rr(e){let t=await Mn(e);return{async getReusableRead(e,n,r){let i=await t.findReusableRead(e,n,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await t.recordRead(e)},async invalidateReadPath(e){await t.invalidatePath(e)},persistToolResult(e){return t.persistToolResult(e)},manageHistory(e){return Kn({...e,contextStore:t})},getSnapshot:t.getSnapshot}}async function ir(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,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId}):Kn({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId})}var K=class extends Error{isHitlPause=!0;constructor(e,t,n){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.name=`HitlPauseSignal`}};function q(e){return!!(e instanceof K||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const ar=I.Object({command:I.String({description:`Shell command to execute`}),workdir:I.Optional(I.String({description:`Working directory (relative to workspace root)`})),env:I.Optional(I.Record(I.String(),I.String())),timeout:I.Optional(I.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:I.Optional(I.Number({description:`Wait this many milliseconds before returning running state`})),background:I.Optional(I.Boolean({description:`Return immediately with running session`}))});function or(e,t,n){return Math.max(t,Math.min(n,e))}function sr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function cr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:or(Math.floor(e),0,12e4)}function lr(e,t){if(!t?.trim())return e;let n=F.isAbsolute(t)?F.normalize(t):F.normalize(F.join(e,t));if(!n.startsWith(e+F.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function ur(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 dr(e){return pr({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
32
- `)}function fr(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function pr(e){let t=fr(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 mr(e){return/\b(rm|mv|cp|chmod|chown|sudo|git\s+push|kubectl\s+delete|terraform\s+apply|docker\s+rm)\b|[>|]{1,2}\s*[^ ]+/i.test(e)}function hr(e,t,n){return!e||e.request.kind!==`approval`||e.toolContext?.toolName!==`exec`||e.toolContext.toolCallId!==t||JSON.stringify(e.toolContext.toolArgs)!==JSON.stringify(n)?!1:e.resolution.action===`submit`&&(e.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1)}function gr(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands with optional background continuation. Use process tool to poll logs and status.`,parameters:ar,async execute(t,n,r){if(!n.command?.trim())return{content:[{type:`text`,text:`Error: command is required.`}],details:{status:`failed`}};if(e.sessionId&&mr(n.command)&&!hr(e.hitlResume,t,n))throw new K({requestId:R(),sessionId:e.hitlResume?.request.sessionId??e.sessionId,kind:`approval`,title:`Confirm shell command`,prompt:`This command may modify system or workspace state. Approve before execution.`,details:{tool:`exec`,command:n.command,workdir:n.workdir},preview:{mimeType:`text/plain`,content:n.command},input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`},{id:`deny`,label:`Deny`}]},policy:{resumable:!0,defaultOnTimeout:`deny`},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`exec`,toolArgs:n});let i;try{i=lr(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=sr(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,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,cr(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:ur(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?pr({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[dr(l)],p=fr(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(`
33
- `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const _r=I.Object({action:I.String({description:`Process action: list | poll | log | kill`}),sessionId:I.Optional(I.String({description:`Session id for non-list actions`})),offset:I.Optional(I.Number({description:`Log line offset (0-based)`})),limit:I.Optional(I.Number({description:`Maximum lines to return`})),timeout:I.Optional(I.Number({description:`Poll wait time in milliseconds`}))});function vr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function yr(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function br(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:_r,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(`
34
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return yr(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,vr(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`}}:yr(`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}}:yr(`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}}:yr(`No session found for ${i}`)}return yr(`Unsupported action: ${n.action}`)}}}const xr=2e5;function Sr(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Cr(e,t){let n=e+t;return n.length<=xr?{text:n,truncated:!1}:{text:n.slice(-xr),truncated:!0}}function wr(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Cr(e.output,r);e.output=i.text;let a=Cr(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function J(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:Sr(e.output),stdoutTail:Sr(e.stdout),stderrTail:Sr(e.stderr),outputTruncated:e.outputTruncated}}function Y(e,t){return t?e.scopeKey===t:!0}function Tr(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Er(e){return e?e.split(/\r?\n/):[]}function Dr(e){let t=Er(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Tr(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(`
35
- `);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 Or(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function kr(){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),Or(e))};return{start(t){let n=ke(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:R(),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=>wr(o,`stdout`,e)),n.stderr.on(`data`,e=>wr(o,`stderr`,e));let s=Tr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,wr(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`),wr(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`)})}),J(o)},get(e,t){let n=r(e);return!n||!Y(n,t)?null:J(n)},list(n){return[...e.values(),...t.values()].filter(e=>Y(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>J(e))},async wait(e,t,n){let i=r(e);if(!i||!Y(i,t))return null;if(i.status!==`running`)return J(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||!Y(a,t)?null:J(a)},readLog(e){let t=r(e.sessionId);return!t||!Y(t,e.scopeKey)?null:Dr({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Y(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||!Y(n,t))return null;if(n.status!==`running`)return J(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?J(i):null}}}function Ar(e){return gr({workspaceDir:e,registry:kr(),scopeKey:e})}const jr=5*1024*1024,Mr=2e3;function Nr(e,t){return F.isAbsolute(e)?F.normalize(e):F.normalize(F.join(t,e))}const Pr=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),offset:I.Optional(I.Number({description:`Line offset (1-based, default: 1)`})),limit:I.Optional(I.Number({description:`Maximum lines to read (default: 2000)`}))});function Fr(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Pr,async execute(n,r){let i;try{i=Nr(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 P.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}}}if(o.length>jr){let e=o.slice(0,jr).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${jr} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let s=o.toString(`utf-8`).split(`
36
- `),c=Math.max(1,r.offset??1),l=Math.min(Mr,r.limit??Mr),u=s.slice(c-1,c-1+l),d=u.length<s.length-(c-1),f=u.map((e,t)=>`${(c+t).toString().padStart(4)} ${e}`).join(`
32
+ `)}function fr(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function pr(e){let t=fr(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 mr(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands with optional background continuation. Use process tool to poll logs and status.`,parameters:ar,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=lr(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=sr(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,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,cr(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:ur(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?pr({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[dr(l)],p=fr(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(`
33
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const hr=I.Object({action:I.String({description:`Process action: list | poll | log | kill`}),sessionId:I.Optional(I.String({description:`Session id for non-list actions`})),offset:I.Optional(I.Number({description:`Log line offset (0-based)`})),limit:I.Optional(I.Number({description:`Maximum lines to return`})),timeout:I.Optional(I.Number({description:`Poll wait time in milliseconds`}))});function gr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function _r(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function vr(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:hr,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(`
34
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return _r(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,gr(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`}}:_r(`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}}:_r(`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}}:_r(`No session found for ${i}`)}return _r(`Unsupported action: ${n.action}`)}}}const yr=2e5;function br(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function xr(e,t){let n=e+t;return n.length<=yr?{text:n,truncated:!1}:{text:n.slice(-yr),truncated:!0}}function Sr(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=xr(e.output,r);e.output=i.text;let a=xr(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function J(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:br(e.output),stdoutTail:br(e.stdout),stderrTail:br(e.stderr),outputTruncated:e.outputTruncated}}function Y(e,t){return t?e.scopeKey===t:!0}function Cr(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function wr(e){return e?e.split(/\r?\n/):[]}function Tr(e){let t=wr(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Cr(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(`
35
+ `);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 Er(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Dr(){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),Er(e))};return{start(t){let n=ke(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:R(),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=>Sr(o,`stdout`,e)),n.stderr.on(`data`,e=>Sr(o,`stderr`,e));let s=Cr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Sr(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`),Sr(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`)})}),J(o)},get(e,t){let n=r(e);return!n||!Y(n,t)?null:J(n)},list(n){return[...e.values(),...t.values()].filter(e=>Y(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>J(e))},async wait(e,t,n){let i=r(e);if(!i||!Y(i,t))return null;if(i.status!==`running`)return J(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||!Y(a,t)?null:J(a)},readLog(e){let t=r(e.sessionId);return!t||!Y(t,e.scopeKey)?null:Tr({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Y(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||!Y(n,t))return null;if(n.status!==`running`)return J(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?J(i):null}}}function Or(e){return mr({workspaceDir:e,registry:Dr(),scopeKey:e})}const kr=5*1024*1024,Ar=2e3;function jr(e,t){return F.isAbsolute(e)?F.normalize(e):F.normalize(F.join(t,e))}const Mr=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),offset:I.Optional(I.Number({description:`Line offset (1-based, default: 1)`})),limit:I.Optional(I.Number({description:`Maximum lines to read (default: 2000)`}))});function Nr(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Mr,async execute(n,r){let i;try{i=jr(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 P.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}}}if(o.length>kr){let e=o.slice(0,kr).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${kr} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let s=o.toString(`utf-8`).split(`
36
+ `),c=Math.max(1,r.offset??1),l=Math.min(Ar,r.limit??Ar),u=s.slice(c-1,c-1+l),d=u.length<s.length-(c-1),f=u.map((e,t)=>`${(c+t).toString().padStart(4)} ${e}`).join(`
37
37
  `),p=d?`\n[...${s.length-(c-1+u.length)} more lines]`:``;return await t?.rememberRead({path:i,content:u.join(`
38
38
  `),lineCount:u.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:f+p}],details:{content:u.join(`
39
- `),lines:u.length,truncated:d}}}}}const Ir=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),content:I.String({description:`File content to write`})});function Lr(e,t){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Ir,async execute(n,r){let i;try{i=Nr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path}}}try{await P.mkdir(F.dirname(i),{recursive:!0}),await P.writeFile(i,r.content,`utf-8`),await t?.invalidateReadPath(i)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:i}}}return{content:[{type:`text`,text:`File written: ${r.path}`}],details:{path:i}}}}}const Rr=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),old_string:I.String({description:`Exact text to replace`}),new_string:I.String({description:`Replacement text`})});function zr(e,t){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Rr,async execute(n,r){let i;try{i=Nr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path,occurrences:0}}}let a;try{a=await P.readFile(i,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{path:i,occurrences:0}}}if(!a.includes(r.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${r.path}`}],details:{path:i,occurrences:0}};let o=a.replace(r.old_string,r.new_string);return await P.writeFile(i,o,`utf-8`),await t?.invalidateReadPath(i),{content:[{type:`text`,text:`File edited: ${r.path}`}],details:{path:i,occurrences:1}}}}}const Br=I.Object({path:I.Optional(I.String({description:`Directory path (default: workspace root)`}))});function Vr(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Br,async execute(t,n){let r=n.path??`.`,i;try{i=Nr(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await P.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(`
40
- `)||`(empty directory)`}],details:{entries:a}}}}}const Hr=I.Object({input:I.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Ur(e,t){let n=F.isAbsolute(e)?F.normalize(e):F.normalize(F.join(t,e));if(!n.startsWith(t+F.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Wr(e,t){let n=F.relative(t,e);return!n||n===``?F.basename(e):n.startsWith(`..`)||F.isAbsolute(n)?e:n}async function Gr(e){await P.mkdir(F.dirname(e),{recursive:!0})}function Kr(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(`
41
- `)}function qr(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:Hr,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:[]}}};if(t.sessionId&&!(t.hitlResume?.request.kind===`approval`&&t.hitlResume.toolContext?.toolName===`apply_patch`&&t.hitlResume.toolContext.toolCallId===n&&JSON.stringify(t.hitlResume.toolContext.toolArgs)===JSON.stringify(r)&&t.hitlResume.resolution.action===`submit`&&(t.hitlResume.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1)))throw new K({requestId:R(),sessionId:t.hitlResume?.request.sessionId??t.sessionId,kind:`approval`,title:`Confirm patch application`,prompt:`Applying this patch will modify files in the workspace. Approve before continuing.`,preview:{mimeType:`text/plain`,content:i},details:{tool:`apply_patch`},input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`},{id:`deny`,label:`Deny`}]},policy:{resumable:!0,defaultOnTimeout:`deny`},createdAt:new Date().toISOString()},{turnId:n,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:n,toolName:`apply_patch`,toolArgs:r});let a=Yr(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 t of a.hunks){if(t.kind===`add`){let n=Ur(t.path,e);await Gr(n),await P.writeFile(n,t.contents,`utf-8`),Jr(o,s,`added`,Wr(n,e));continue}if(t.kind===`delete`){let n=Ur(t.path,e);await P.rm(n,{force:!0,recursive:!1}),Jr(o,s,`deleted`,Wr(n,e));continue}let n=Ur(t.path,e),r=await $r(n,t.chunks);if(t.movePath){let i=Ur(t.movePath,e);await Gr(i),await P.writeFile(i,r,`utf-8`),await P.rm(n,{force:!0,recursive:!1}),Jr(o,s,`modified`,Wr(i,e))}else await P.writeFile(n,r,`utf-8`),Jr(o,s,`modified`,Wr(n,e))}return{content:[{type:`text`,text:Kr(o)}],details:{summary:o}}}catch(e){if(q(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Jr(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Yr(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Xr(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Zr(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Xr(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 Zr(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}=Qr(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 Qr(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 $r(e,t){let n=(await P.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
42
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=ti(n,ei(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
43
- `)}function ei(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=ni(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=ni(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=ni(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
44
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function ti(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 ni(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(ri(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(ri(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(ri(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(ri(e,t,n,e=>ii(e.trim())))return n;return null}function ri(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 ii(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(``)}const ai=I.Object({question:I.String({description:`The question to ask the user.`}),options:I.Optional(I.Array(I.String(),{description:`Optional list of choices for the user to select from.`})),allow_free_text:I.Optional(I.Boolean({description:`Whether to allow the user to type a free-text response in addition to choices. Defaults to true.`}))});function oi(e){return{name:`clarify`,label:`Clarify`,description:`Ask the user a clarifying question when you need more information to proceed. Provide a clear question and optionally a list of choices. The current task will be paused until the user responds.`,parameters:ai,async execute(t,n){let r=R(),i=n.options&&n.options.length>0,a;throw a=i?{mode:`choice`,choices:n.options.map((e,t)=>({id:`option-${t}`,label:e})),allowFreeText:n.allow_free_text!==!1}:{mode:`text`,multiline:!0,placeholder:`Type your response...`},new K({requestId:r,sessionId:e,kind:`clarify`,title:`Agent needs clarification`,prompt:n.question,input:a,policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`clarify`,toolArgs:n})}}}function si(e){return F.join(e,`.aimax`)}function ci(e){return F.join(si(e),`MEMORY.md`)}async function li(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function ui(e,t){let n=si(e),r=E({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:g({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function di(e){return b(si(e))}async function fi(e){try{return await P.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function pi(e){return fi(ci(e))}async function mi(e,t,n){return await ui(e,n).search(t)}async function hi(e,t,n,r,i){try{return await ui(e,i).getLines(t,n,r)}catch{return null}}async function gi(e,t,n){let r=ui(e,n);await r.append(t),await li(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function _i(e,t,n,r){let i=ui(e,r);await i.updateFile(t,n),await li(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function vi(e,t,n){let r=ui(e,n);await r.deleteFile(t),await li(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const yi=I.Object({query:I.String({description:`Search query (case-insensitive substring match)`})});function bi(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memory files for relevant information`,parameters:yi,async execute(n,r){let i=(await mi(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({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.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
45
- `)}],details:{matches:i}}}}}const xi=I.Object({file:I.String({description:`Memory file path`}),start_line:I.Number({description:`Start line number (1-based)`}),end_line:I.Number({description:`End line number (1-based)`})});function Si(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read specific lines from a memory file`,parameters:xi,async execute(n,r){let i=await hi(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(`
46
- `)||`(empty)`}],details:{lines:i}}}}}const Ci=I.Object({content:I.String({description:`Content to append to MEMORY.md`})});function wi(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append new information to the MEMORY.md file`,parameters:Ci,async execute(n,r){try{return await gi(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 Ti=I.Object({action:I.String({description:`A short description of the action that needs approval.`}),reason:I.String({description:`Why this action needs human approval.`}),details:I.Optional(I.String({description:`Additional details about the action (e.g. the command to execute).`}))});function Ei(e,t){return{name:`request_approval`,label:`Request Approval`,description:"Use this tool only when the user or system instructions explicitly require calling `request_approval`. Do not use it for general confirmation, clarification, or inferred approval checks. Describe the action and why `request_approval` was explicitly required. The task will be paused until the user approves or denies the action.",parameters:Ti,async execute(n,r){if(t?.request.kind===`approval`&&t.toolContext?.toolName===`request_approval`&&t.toolContext.toolCallId===n&&t.resolution.action===`submit`){let e=t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1;return{content:[{type:`text`,text:e?`Approval granted.`:`Approval denied.`}],details:{paused:!1,approved:e}}}let i=R(),a;throw r.details&&(a={mimeType:`text/plain`,content:r.details}),new K({requestId:i,sessionId:e,kind:`approval`,title:r.action,prompt:r.reason,preview:a,input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`,description:`Allow this action to proceed`},{id:`deny`,label:`Deny`,description:`Reject this action`}]},policy:{resumable:!0,defaultOnTimeout:`deny`},createdAt:new Date().toISOString()},{turnId:n,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:n,toolName:`request_approval`,toolArgs:r})}}}const Di=I.Object({title:I.String({description:`A short title for the review (e.g. 'Weekly Report Draft').`}),description:I.String({description:`What the user should review and what kind of feedback you need.`}),content:I.String({description:`The content to review (text, markdown, or JSON).`}),content_type:I.Optional(I.String({description:`MIME type: text/plain, application/json, or text/markdown. Defaults to text/markdown.`}))});function Oi(e){return{name:`request_review`,label:`Request Review`,description:`Present a draft, document, or output for human review before proceeding. Include the content to review and a description of what feedback you need. The task will be paused until the user reviews and responds.`,parameters:Di,async execute(t,n){let r=R(),i={mimeType:n.content_type??`text/markdown`,content:n.content};throw new K({requestId:r,sessionId:e,kind:`review`,title:n.title,prompt:n.description,preview:i,input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`,description:`The content looks good, proceed`},{id:`revise`,label:`Request changes`,description:`Provide feedback for revision`},{id:`reject`,label:`Reject`,description:`Discard this draft`}],allowFreeText:!0},policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`request_review`,toolArgs:n})}}}const ki=I.Object({task:I.String({description:`The task description for the subagent to execute`}),label:I.Optional(I.String({description:`Optional short label to identify this subagent`}))});function Ai(e){let t=e.label?`"${e.label}"`:`task: ${e.task}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${e.result??`(no output)`}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function ji(e,t,n,r,i,a,o,s,c){return{name:`sessions_spawn`,label:`Spawn Subagent`,description:`Use this tool only when the user or system instructions explicitly require using a subagent, delegation, or parallel agent execution. Do not use it for routine decomposition or inferred parallelism. Returns immediately with status=accepted; the subagent result will be delivered back automatically as a follow-up message — do not poll or sleep.`,parameters:ki,async execute(u,d){let f=d.task.trim(),p=d.label?.trim();if(!f){let e={status:`error`,error:`task must not be empty`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=e.checkSpawnAllowed(t,n+1);if(!m.allowed){let e={status:`forbidden`,error:m.reason};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let h=R(),g=new AbortController,_;try{_=await l(r,i)}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}let v={runId:h,childSessionId:_,parentSessionId:t,task:f,label:p,depth:n+1,status:`running`,startedAt:Date.now(),abortController:g},y=c({dataDir:r,sessionId:_,message:f,channel:i,llm:a,...s,loopDetection:o,abortSignal:g.signal,subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(h,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(h,n)});e.register(v,y);let b={status:`accepted`,childSessionId:_,runId:h,note:`The subagent result will be sent back automatically. Do not poll or re-spawn.`};return{content:[{type:`text`,text:JSON.stringify(b)}],details:b}}}}const Mi=I.Object({action:I.Union([`list`,`kill`].map(e=>I.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:I.Optional(I.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Ni(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 Pi(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 Fi(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:Mi,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let e=o.map((e,t)=>({index:t+1,runId:e.runId,label:e.label??e.task.slice(0,40),task:e.task,status:e.status,depth:e.depth,runtimeMs:e.endedAt?e.endedAt-e.startedAt:a-e.startedAt})),t={action:`list`,runs:e,text:(e.length===0?[`(no subagents)`]:e.map(e=>`${e.index}. [${e.status}] ${e.label} (${Ni(e.runtimeMs)})`)).join(`
47
- `)};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}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=Pi(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}}}}const Ii=I.Object({image:I.String({description:`Image path or URL`}),prompt:I.Optional(I.String({description:`Prompt for image analysis`})),model:I.Optional(I.String({description:`Optional model override`})),maxBytesMb:I.Optional(I.Number({description:`Optional size cap in MB`}))});function Li(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Ii,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}}}}function Ri(e,t){let n=F.join(e,`workspace`),r=t?.memoryOptions,i=kr(),a=[gr({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),br({registry:i,scopeKey:n}),Fr(n,t?.contextManager),Lr(n,t?.contextManager),zr(n,t?.contextManager),Vr(n),qr(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),bi(e,r),Si(e,r),wi(e,r),...(t?.sessionId,[])];return t&&a.push(ji(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Fi(t.registry,t.parentSessionId)),a}const zi={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`,memory_search:`Search memory files for relevant information`,memory_get:`Read specific lines from memory files`,memory_append:`Append new long-term memory`,sessions_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Bi=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`memory_search`,`memory_get`,`memory_append`,`sessions_spawn`,`subagents`];function Vi(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:[...Bi.filter(e=>t.has(e)),...n.filter(e=>!Bi.includes(e)).sort()],displayName:t}}function Hi(e){let{ordered:t,displayName:n}=Vi(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)??zi[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
39
+ `),lines:u.length,truncated:d}}}}}const Pr=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),content:I.String({description:`File content to write`})});function Fr(e,t){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Pr,async execute(n,r){let i;try{i=jr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path}}}try{await P.mkdir(F.dirname(i),{recursive:!0}),await P.writeFile(i,r.content,`utf-8`),await t?.invalidateReadPath(i)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:i}}}return{content:[{type:`text`,text:`File written: ${r.path}`}],details:{path:i}}}}}const Ir=I.Object({path:I.String({description:`File path (relative to workspace or absolute)`}),old_string:I.String({description:`Exact text to replace`}),new_string:I.String({description:`Replacement text`})});function Lr(e,t){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Ir,async execute(n,r){let i;try{i=jr(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path,occurrences:0}}}let a;try{a=await P.readFile(i,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{path:i,occurrences:0}}}if(!a.includes(r.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${r.path}`}],details:{path:i,occurrences:0}};let o=a.replace(r.old_string,r.new_string);return await P.writeFile(i,o,`utf-8`),await t?.invalidateReadPath(i),{content:[{type:`text`,text:`File edited: ${r.path}`}],details:{path:i,occurrences:1}}}}}const Rr=I.Object({path:I.Optional(I.String({description:`Directory path (default: workspace root)`}))});function zr(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Rr,async execute(t,n){let r=n.path??`.`,i;try{i=jr(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await P.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(`
40
+ `)||`(empty directory)`}],details:{entries:a}}}}}const Br=I.Object({input:I.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Vr(e,t){let n=F.isAbsolute(e)?F.normalize(e):F.normalize(F.join(t,e));if(!n.startsWith(t+F.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Hr(e,t){let n=F.relative(t,e);return!n||n===``?F.basename(e):n.startsWith(`..`)||F.isAbsolute(n)?e:n}async function Ur(e){await P.mkdir(F.dirname(e),{recursive:!0})}function Wr(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(`
41
+ `)}function Gr(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:Br,async execute(t,n){try{let t=n.input?.trim();if(!t)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let r=qr(t);if(r.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let i={added:[],modified:[],deleted:[]},a={added:new Set,modified:new Set,deleted:new Set};for(let t of r.hunks){if(t.kind===`add`){let n=Vr(t.path,e);await Ur(n),await P.writeFile(n,t.contents,`utf-8`),Kr(i,a,`added`,Hr(n,e));continue}if(t.kind===`delete`){let n=Vr(t.path,e);await P.rm(n,{force:!0,recursive:!1}),Kr(i,a,`deleted`,Hr(n,e));continue}let n=Vr(t.path,e),r=await Zr(n,t.chunks);if(t.movePath){let o=Vr(t.movePath,e);await Ur(o),await P.writeFile(o,r,`utf-8`),await P.rm(n,{force:!0,recursive:!1}),Kr(i,a,`modified`,Hr(o,e))}else await P.writeFile(n,r,`utf-8`),Kr(i,a,`modified`,Hr(n,e))}return{content:[{type:`text`,text:Wr(i)}],details:{summary:i}}}catch(e){if(q(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Kr(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function qr(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Jr(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Yr(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Jr(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 Yr(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}=Xr(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 Xr(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 Zr(e,t){let n=(await P.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
42
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=$r(n,Qr(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
43
+ `)}function Qr(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=ei(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=ei(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=ei(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
44
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function $r(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 ei(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(ti(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(ti(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(ti(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(ti(e,t,n,e=>ni(e.trim())))return n;return null}function ti(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 ni(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(``)}const ri=I.Object({question:I.String({description:`The question to ask the user.`}),options:I.Optional(I.Array(I.String(),{description:`Optional list of choices for the user to select from.`})),allow_free_text:I.Optional(I.Boolean({description:`Whether to allow the user to type a free-text response in addition to choices. Defaults to true.`}))});function ii(e){return{name:`clarify`,label:`Clarify`,description:`Ask the user a clarifying question when you need more information to proceed. Provide a clear question and optionally a list of choices. The current task will be paused until the user responds.`,parameters:ri,async execute(t,n){let r=R(),i=n.options&&n.options.length>0,a;throw a=i?{mode:`choice`,choices:n.options.map((e,t)=>({id:`option-${t}`,label:e})),allowFreeText:n.allow_free_text!==!1}:{mode:`text`,multiline:!0,placeholder:`Type your response...`},new K({requestId:r,sessionId:e,kind:`clarify`,title:`Agent needs clarification`,prompt:n.question,input:a,policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`clarify`,toolArgs:n})}}}function ai(e){return F.join(e,`.aimax`)}function oi(e){return F.join(ai(e),`MEMORY.md`)}async function si(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function ci(e,t){let n=ai(e),r=E({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:g({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function li(e){return b(ai(e))}async function ui(e){try{return await P.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function di(e){return ui(oi(e))}async function fi(e,t,n){return await ci(e,n).search(t)}async function pi(e,t,n,r,i){try{return await ci(e,i).getLines(t,n,r)}catch{return null}}async function mi(e,t,n){let r=ci(e,n);await r.append(t),await si(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function hi(e,t,n,r){let i=ci(e,r);await i.updateFile(t,n),await si(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function gi(e,t,n){let r=ci(e,n);await r.deleteFile(t),await si(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const _i=I.Object({query:I.String({description:`Search query (case-insensitive substring match)`})});function vi(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memory files for relevant information`,parameters:_i,async execute(n,r){let i=(await fi(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({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.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
45
+ `)}],details:{matches:i}}}}}const yi=I.Object({file:I.String({description:`Memory file path`}),start_line:I.Number({description:`Start line number (1-based)`}),end_line:I.Number({description:`End line number (1-based)`})});function bi(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read specific lines from a memory file`,parameters:yi,async execute(n,r){let i=await pi(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(`
46
+ `)||`(empty)`}],details:{lines:i}}}}}const xi=I.Object({content:I.String({description:`Content to append to MEMORY.md`})});function Si(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append new information to the MEMORY.md file`,parameters:xi,async execute(n,r){try{return await mi(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 Ci=I.Object({action:I.String({description:`A short description of the action that needs approval.`}),reason:I.String({description:`Why this action needs human approval.`}),details:I.Optional(I.String({description:`Additional details about the action (e.g. the command to execute).`}))});function wi(e,t){return{name:`request_approval`,label:`Request Approval`,description:"Use this tool only when the user or system instructions explicitly require calling `request_approval`. Do not use it for general confirmation, clarification, or inferred approval checks. Describe the action and why `request_approval` was explicitly required. The task will be paused until the user approves or denies the action.",parameters:Ci,async execute(n,r){if(t?.request.kind===`approval`&&t.toolContext?.toolName===`request_approval`&&t.toolContext.toolCallId===n&&t.resolution.action===`submit`){let e=t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1;return{content:[{type:`text`,text:e?`Approval granted.`:`Approval denied.`}],details:{paused:!1,approved:e}}}let i=R(),a;throw r.details&&(a={mimeType:`text/plain`,content:r.details}),new K({requestId:i,sessionId:e,kind:`approval`,title:r.action,prompt:r.reason,preview:a,input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`,description:`Allow this action to proceed`},{id:`deny`,label:`Deny`,description:`Reject this action`}]},policy:{resumable:!0,defaultOnTimeout:`deny`},createdAt:new Date().toISOString()},{turnId:n,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:n,toolName:`request_approval`,toolArgs:r})}}}const Ti=I.Object({title:I.String({description:`A short title for the review (e.g. 'Weekly Report Draft').`}),description:I.String({description:`What the user should review and what kind of feedback you need.`}),content:I.String({description:`The content to review (text, markdown, or JSON).`}),content_type:I.Optional(I.String({description:`MIME type: text/plain, application/json, or text/markdown. Defaults to text/markdown.`}))});function Ei(e){return{name:`request_review`,label:`Request Review`,description:`Present a draft, document, or output for human review before proceeding. Include the content to review and a description of what feedback you need. The task will be paused until the user reviews and responds.`,parameters:Ti,async execute(t,n){let r=R(),i={mimeType:n.content_type??`text/markdown`,content:n.content};throw new K({requestId:r,sessionId:e,kind:`review`,title:n.title,prompt:n.description,preview:i,input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`,description:`The content looks good, proceed`},{id:`revise`,label:`Request changes`,description:`Provide feedback for revision`},{id:`reject`,label:`Reject`,description:`Discard this draft`}],allowFreeText:!0},policy:{resumable:!0},createdAt:new Date().toISOString()},{turnId:t,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:t,toolName:`request_review`,toolArgs:n})}}}const Di=I.Object({task:I.String({description:`The task description for the subagent to execute`}),label:I.Optional(I.String({description:`Optional short label to identify this subagent`}))});function Oi(e){let t=e.label?`"${e.label}"`:`task: ${e.task}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${e.result??`(no output)`}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function ki(e,t,n,r,i,a,o,s,c){return{name:`sessions_spawn`,label:`Spawn Subagent`,description:`Use this tool only when the user or system instructions explicitly require using a subagent, delegation, or parallel agent execution. Do not use it for routine decomposition or inferred parallelism. Returns immediately with status=accepted; the subagent result will be delivered back automatically as a follow-up message — do not poll or sleep.`,parameters:Di,async execute(u,d){let f=d.task.trim(),p=d.label?.trim();if(!f){let e={status:`error`,error:`task must not be empty`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=e.checkSpawnAllowed(t,n+1);if(!m.allowed){let e={status:`forbidden`,error:m.reason};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let h=R(),g=new AbortController,_;try{_=await l(r,i)}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}let v={runId:h,childSessionId:_,parentSessionId:t,task:f,label:p,depth:n+1,status:`running`,startedAt:Date.now(),abortController:g},y=c({dataDir:r,sessionId:_,message:f,channel:i,llm:a,...s,loopDetection:o,abortSignal:g.signal,subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(h,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(h,n)});e.register(v,y);let b={status:`accepted`,childSessionId:_,runId:h,note:`The subagent result will be sent back automatically. Do not poll or re-spawn.`};return{content:[{type:`text`,text:JSON.stringify(b)}],details:b}}}}const Ai=I.Object({action:I.Union([`list`,`kill`].map(e=>I.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:I.Optional(I.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function ji(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 Mi(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 Ni(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:Ai,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let e=o.map((e,t)=>({index:t+1,runId:e.runId,label:e.label??e.task.slice(0,40),task:e.task,status:e.status,depth:e.depth,runtimeMs:e.endedAt?e.endedAt-e.startedAt:a-e.startedAt})),t={action:`list`,runs:e,text:(e.length===0?[`(no subagents)`]:e.map(e=>`${e.index}. [${e.status}] ${e.label} (${ji(e.runtimeMs)})`)).join(`
47
+ `)};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}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=Mi(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}}}}const Pi=I.Object({image:I.String({description:`Image path or URL`}),prompt:I.Optional(I.String({description:`Prompt for image analysis`})),model:I.Optional(I.String({description:`Optional model override`})),maxBytesMb:I.Optional(I.Number({description:`Optional size cap in MB`}))});function Fi(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Pi,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}}}}function Ii(e,t){let n=F.join(e,`workspace`),r=t?.memoryOptions,i=Dr(),a=[mr({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),vr({registry:i,scopeKey:n}),Nr(n,t?.contextManager),Fr(n,t?.contextManager),Lr(n,t?.contextManager),zr(n),Gr(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),vi(e,r),bi(e,r),Si(e,r),...(t?.sessionId,[])];return t&&a.push(ki(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Ni(t.registry,t.parentSessionId)),a}const Li={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`,memory_search:`Search memory files for relevant information`,memory_get:`Read specific lines from memory files`,memory_append:`Append new long-term memory`,sessions_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Ri=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`memory_search`,`memory_get`,`memory_append`,`sessions_spawn`,`subagents`];function zi(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:[...Ri.filter(e=>t.has(e)),...n.filter(e=>!Ri.includes(e)).sort()],displayName:t}}function Bi(e){let{ordered:t,displayName:n}=zi(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)??Li[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
48
48
  `),``].join(`
49
- `)}function Ui(){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(`
50
- `)}function Wi(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(`
51
- `)}function Gi(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: read its SKILL.md at <location> with `read_file`, then follow it.",`- If multiple could apply: choose the most specific one, then read/follow it.`,`- If none clearly apply: do not read any SKILL.md.`,`Constraints: never read more than one skill up front; only read after selecting.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
49
+ `)}function Vi(){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(`
50
+ `)}function Hi(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(`
51
+ `)}function Ui(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: read its SKILL.md at <location> with `read_file`, then follow it.",`- If multiple could apply: choose the most specific one, then read/follow it.`,`- If none clearly apply: do not read any SKILL.md.`,`Constraints: never read more than one skill up front; only read after selecting.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
52
52
  `)).join(`
53
53
  `)}\n</available_skills>`,``].join(`
54
- `)}function Ki(){return[`## Memory Write`,`When the user asks to remember something or new long-term memory is needed, you must use memory_append. Do not use write_file or edit_file for memory writes.`,``].join(`
55
- `)}function qi(e){return[`## Memory Recall`,`Before answering anything about prior work, decisions, dates, people, preferences, or todos: run memory_search on MEMORY.md + memory/*.md; then use memory_get to pull only the needed lines. If low confidence after search, say you checked.`,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(`
56
- `)}function Ji(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.`;return[`## Workspace`,`Your cloud working directory is: ${r}`,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, HEARTBEAT.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(`
57
- `)}function Yi(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(`
58
- `)}function Xi(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Zi(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
59
- `)}function Zi(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 Qi(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(`
60
- `)}function $i(e){if(e.isMinimal)return``;let t=e.docs,n=[`## Documentation`,t?.localPath?`Cloud docs mount: ${t.localPath}`:``,t?.webUrl?`Docs mirror: ${t.webUrl}`:``,t?.sourceUrl?`Source: ${t.sourceUrl}`:``,`For AiMax behavior, configuration, and architecture questions, consult documentation first.`,``].filter(Boolean);return n.length<=2?``:n.join(`
61
- `)}function ea(e){if(!e)return``;let t=[e.hostname?`host=${e.hostname}`:``,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(`
62
- `)}function ta(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(`
63
- `)}function na(e){return e.isMinimal?``:[`## Heartbeats`,`Heartbeat prompt: ${e.heartbeatPrompt?.trim()||`Read HEARTBEAT.md if it exists (cloud workspace context). Follow it strictly. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.`}`,`If a user message matches the heartbeat prompt and nothing needs attention, reply exactly: HEARTBEAT_OK`,`If something needs attention, do NOT include "HEARTBEAT_OK"; respond with the alert text instead.`,``].join(`
64
- `)}function ra(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(`
65
- `)}function ia(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(`
66
- `):``}function aa(e){let t=e.promptMode??`full`,n=t===`minimal`;if(t===`none`)return`You are a personal assistant running inside AiMax.`;let r=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Bi],i=e.skills??[],a=e.contextFiles??[];return[`You are a personal assistant running inside AiMax.
67
- `,Hi({toolNames:r,toolSummaries:e.toolSummaries}),Wi(n),Ui(),Gi(i),Ki(),qi(e.memoryCitationsMode??`off`),Ji({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),Yi(e.sandboxInfo),Xi({currentDate:e.currentDate,timezone:e.timezone}),Qi({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),$i({isMinimal:n,docs:e.docs}),ta({isMinimal:n}),na({isMinimal:n,heartbeatPrompt:e.heartbeatPrompt}),ea(e.runtimeInfo),ra({contextFiles:a,bootstrapWarnings:e.bootstrapWarnings}),ia(e.priorConversationSummary)].filter(Boolean).join(`
68
- `)}const oa=new Ae;async function sa(e,t){return await oa.run(e,t)}function ca(e){return{async emit(t){let n=oa.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const la=Symbol(`pluginToolOwner`);var ua=class{tools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,la,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}list(){return[...this.tools]}namesForPlugin(e){return this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names)}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)}};function da(e){return e[la]}const fa=new Ae;function pa(){return{}}async function ma(e,t){return await fa.run(e,t)}function ha(e){let t=fa.getStore();!t||t.signal||(t.signal=e)}function ga(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=da(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await sa({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r);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(q(i)){ha(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}}}})}var _a=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await sa({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const X={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function va(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function ya(e){let t=va(e?.warningThreshold,X.warningThreshold),n=va(e?.criticalThreshold,X.criticalThreshold),r=va(e?.globalCircuitBreakerThreshold,X.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??X.enabled,historySize:va(e?.historySize,X.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??X.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??X.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??X.detectors.pingPong}}}function Z(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ba(e,t){return`${e}:${Q(t)}`}function xa(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(xa).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${xa(t[e])}`).join(`,`)}}`}function Sa(e){try{return xa(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 Q(e){let t=Sa(e);return Ee(`sha256`).update(t).digest(`hex`)}function Ca(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Z(t))return!1;let n=t.action;return n===`poll`||n===`log`}function wa(e){return!Z(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Z(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
69
- `).trim()}function Ta(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:xa(e)}function Ea(e,t,n,r){if(r!==void 0)return`error:${Q(Ta(r))}`;if(!Z(n))return n===void 0?void 0:Q(n);let i=Z(n.details)?n.details:{},a=wa(n);if(Ca(e,t)&&e===`process`&&Z(t)){let e=t.action;if(e===`poll`)return Q({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Q({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 Q({details:i,text:a})}function Da(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 Oa(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 ka(e,t){return[e,t].toSorted().join(`|`)}function Aa(e,t,n,r){let i=ya(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=ba(t,n),s=Da(a,t,o),c=s.count,l=Ca(t,n),u=Oa(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:${ka(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 ja(e,t,n,r,i){let a=ya(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:ba(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Ma(e,t){let n=ya(t.config),r=Ea(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=ba(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 Na(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 Pa(e){return e&&e.trim()||`tool`}function Fa(e,t,n){if(!e.execute)return e;let r=Pa(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Aa(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Na(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}ja(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Ma(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Ma(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Ia(e,t,n){return e.map(e=>Fa(e,t,n))}async function La(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,effectivePromptText:u,pluginTools:d},dependencies:{registry:f,spawnFn:p,createModel:m,abortSignal:h}}=e,g=t.channel===`CRON`,_=g?[]:await T(t.dataDir,n),v={model:t.llm.model,api:`openai-completions`},y=await rr({dataDir:t.dataDir,sessionId:n}),b=g?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await ir({entries:_,modelInfo:v,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:h,hooks:r,hookCtx:i,contextManager:y,dataDir:t.dataDir,sessionId:n});await Ra({sessionId:n,historyResult:b,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let x=t.subagentContext?.depth??0,S=[...Ri(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,registry:f,parentSessionId:n,depth:x,channel:t.channel,llm:t.llm,inheritedRunParams:{plugins:t.plugins,memory:t.memory,messaging:t.messaging,docs:t.docs,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},contextManager:y,hitlResume:t.hitlResume,spawnFn:p}),...d],C=S.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),w={};for(let e of S){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||w[t]||(w[t]=n)}let E=t.messaging?.enabled??t.channel!==`CRON`,D=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],O=aa({dataDir:t.dataDir,skills:l,contextFiles:s,toolNames:C,toolSummaries:w,promptMode:x>0?`minimal`:`full`,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:E,channels:D},docs:{localPath:t.docs?.localPath,webUrl:t.docs?.webUrl,sourceUrl:t.docs?.sourceUrl},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Oe.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:b.priorSummary}),ee=await r.dispatch(`before_prompt_build`,{prompt:u},i,{eventDispatcher:o});for(let e of ee)e&&(e.systemPrompt&&(O=e.systemPrompt),e.prependContext&&(O=`${e.prependContext}\n\n${O}`));await r.dispatch(`after_prompt_build`,{prompt:u,systemPrompt:O},i,{eventDispatcher:o});let k=Ia(ga(S,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},$e),A=t.llm.model,j=await r.dispatch(`before_model_resolve`,{prompt:u},i,{eventDispatcher:o});for(let e of j)e&&e.modelOverride&&(A=e.modelOverride);let M=m({...t.llm,model:A},n),N=new De({initialState:{systemPrompt:O,model:M,tools:k,messages:[]},getApiKey:e=>t.llm.apiKey});return b.messages.length>0&&N.replaceMessages(b.messages),{agent:N,resolvedModelId:A,historyMessages:b.messages,historyResult:b,workspaceDir:a.workspaceDir}}async function Ra(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;await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i}),await r.appendTranscriptEntry(n.compactionEntry),(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})}}async function za(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=[],x=new Map,S=pa(),C=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Ka(`partial`in t?t.partial:void 0)??Ka(`message`in t?t.message:void 0)??Ka(`message`in e?e.message:void 0),i=qa(t.delta,n,p);i&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:i}),m+=i),n&&(p=n,m=n)}if(t.type===`done`){let e=t.message;f=Ga(e);let n=qa(``,f,m||p);n&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:n}),m+=n),p=f,m=f,e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ga(e);await c.dispatch(`assistant_message_end`,{sessionId:r,model:i,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:Ua(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r,e.toolCallId,e.toolName)}));b.push({message:t,toolResults:n}),d&&(await d(Va(Ba(t),!!S.signal),n.map(Ha)),S.signal);return}if(e.type===`tool_execution_start`){m=``,x.set(e.toolCallId,e.args),s.onToolExecutionStart({toolName:e.toolName,args:e.args}),await o.dispatchProgress(r,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await s.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result),n=x.get(e.toolCallId);x.delete(e.toolCallId),await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:n,output:t,isError:e.isError})}});try{if(await c.dispatch(`llm_input`,{sessionId:r,model:i,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:a},l),u?.aborted)throw Error(`aborted`);y=Date.now(),await ma(S,async()=>{await t.prompt(n)});let e=S.signal;if(e)throw e;if(!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Ja(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){if(q(e))throw e;_=Ja(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{C()}let w=b.length>0?b[b.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:f?[f]:[],lastAssistant:w,usage:{input:h,output:g,total:h+g}},l);let T=b.length>0?Ga(b[b.length-1].message):``;if(S.signal)throw S.signal;return d&&b.length===0&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:T||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}function Ba(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function Va(e,t){return!e||!t||e.content.trim()!==`HITL_PAUSED`?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Ha(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function Ua(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:Wa(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Wa(e){let t=e.indexOf(`
54
+ `)}function Wi(){return[`## Memory Write`,`When the user asks to remember something or new long-term memory is needed, you must use memory_append. Do not use write_file or edit_file for memory writes.`,``].join(`
55
+ `)}function Gi(e){return[`## Memory Recall`,`Before answering anything about prior work, decisions, dates, people, preferences, or todos: run memory_search on MEMORY.md + memory/*.md; then use memory_get to pull only the needed lines. If low confidence after search, say you checked.`,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(`
56
+ `)}function Ki(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.`;return[`## Workspace`,`Your cloud working directory is: ${r}`,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, HEARTBEAT.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(`
57
+ `)}function qi(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(`
58
+ `)}function Ji(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Yi(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
59
+ `)}function Yi(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 Xi(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(`
60
+ `)}function Zi(e){if(e.isMinimal)return``;let t=e.docs,n=[`## Documentation`,t?.localPath?`Cloud docs mount: ${t.localPath}`:``,t?.webUrl?`Docs mirror: ${t.webUrl}`:``,t?.sourceUrl?`Source: ${t.sourceUrl}`:``,`For AiMax behavior, configuration, and architecture questions, consult documentation first.`,``].filter(Boolean);return n.length<=2?``:n.join(`
61
+ `)}function Qi(e){if(!e)return``;let t=[e.hostname?`host=${e.hostname}`:``,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(`
62
+ `)}function $i(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(`
63
+ `)}function ea(e){return e.isMinimal?``:[`## Heartbeats`,`Heartbeat prompt: ${e.heartbeatPrompt?.trim()||`Read HEARTBEAT.md if it exists (cloud workspace context). Follow it strictly. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.`}`,`If a user message matches the heartbeat prompt and nothing needs attention, reply exactly: HEARTBEAT_OK`,`If something needs attention, do NOT include "HEARTBEAT_OK"; respond with the alert text instead.`,``].join(`
64
+ `)}function ta(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(`
65
+ `)}function na(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(`
66
+ `):``}function ra(e){let t=e.promptMode??`full`,n=t===`minimal`;if(t===`none`)return`You are a personal assistant running inside AiMax.`;let r=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Ri],i=e.skills??[],a=e.contextFiles??[];return[`You are a personal assistant running inside AiMax.
67
+ `,Bi({toolNames:r,toolSummaries:e.toolSummaries}),Hi(n),Vi(),Ui(i),Wi(),Gi(e.memoryCitationsMode??`off`),Ki({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),qi(e.sandboxInfo),Ji({currentDate:e.currentDate,timezone:e.timezone}),Xi({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Zi({isMinimal:n,docs:e.docs}),$i({isMinimal:n}),ea({isMinimal:n,heartbeatPrompt:e.heartbeatPrompt}),Qi(e.runtimeInfo),ta({contextFiles:a,bootstrapWarnings:e.bootstrapWarnings}),na(e.priorConversationSummary)].filter(Boolean).join(`
68
+ `)}const ia=new Ae;async function aa(e,t){return await ia.run(e,t)}function oa(e){return{async emit(t){let n=ia.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const sa=Symbol(`pluginToolOwner`);var ca=class{tools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,sa,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}list(){return[...this.tools]}namesForPlugin(e){return this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names)}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)}};function la(e){return e[sa]}const ua=new Ae;function da(){return{}}async function fa(e,t){return await ua.run(e,t)}function pa(e){let t=ua.getStore();!t||t.signal||(t.signal=e)}function ma(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=la(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await aa({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r);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(q(i)){pa(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}}}})}var ha=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await aa({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const X={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function ga(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function _a(e){let t=ga(e?.warningThreshold,X.warningThreshold),n=ga(e?.criticalThreshold,X.criticalThreshold),r=ga(e?.globalCircuitBreakerThreshold,X.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??X.enabled,historySize:ga(e?.historySize,X.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??X.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??X.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??X.detectors.pingPong}}}function Z(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function va(e,t){return`${e}:${Q(t)}`}function ya(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(ya).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${ya(t[e])}`).join(`,`)}}`}function ba(e){try{return ya(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 Q(e){let t=ba(e);return Ee(`sha256`).update(t).digest(`hex`)}function xa(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Z(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Sa(e){return!Z(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Z(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
69
+ `).trim()}function Ca(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:ya(e)}function wa(e,t,n,r){if(r!==void 0)return`error:${Q(Ca(r))}`;if(!Z(n))return n===void 0?void 0:Q(n);let i=Z(n.details)?n.details:{},a=Sa(n);if(xa(e,t)&&e===`process`&&Z(t)){let e=t.action;if(e===`poll`)return Q({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Q({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 Q({details:i,text:a})}function Ta(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 Ea(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 Da(e,t){return[e,t].toSorted().join(`|`)}function Oa(e,t,n,r){let i=_a(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=va(t,n),s=Ta(a,t,o),c=s.count,l=xa(t,n),u=Ea(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:${Da(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 ka(e,t,n,r,i){let a=_a(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:va(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Aa(e,t){let n=_a(t.config),r=wa(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=va(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 ja(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 Ma(e){return e&&e.trim()||`tool`}function Na(e,t,n){if(!e.execute)return e;let r=Ma(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Oa(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);ja(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}ka(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Aa(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Aa(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Pa(e,t,n){return e.map(e=>Na(e,t,n))}async function Fa(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,effectivePromptText:u,pluginTools:d},dependencies:{registry:f,spawnFn:p,createModel:m,abortSignal:h}}=e,g=t.channel===`CRON`,_=g?[]:await T(t.dataDir,n),v={model:t.llm.model,api:`openai-completions`},y=await rr({dataDir:t.dataDir,sessionId:n}),b=g?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await ir({entries:_,modelInfo:v,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:h,hooks:r,hookCtx:i,contextManager:y,dataDir:t.dataDir,sessionId:n});await Ia({sessionId:n,historyResult:b,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let x=t.subagentContext?.depth??0,S=[...Ii(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,registry:f,parentSessionId:n,depth:x,channel:t.channel,llm:t.llm,inheritedRunParams:{plugins:t.plugins,memory:t.memory,messaging:t.messaging,docs:t.docs,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},contextManager:y,hitlResume:t.hitlResume,spawnFn:p}),...d],C=S.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),w={};for(let e of S){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||w[t]||(w[t]=n)}let E=t.messaging?.enabled??t.channel!==`CRON`,D=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],O=ra({dataDir:t.dataDir,skills:l,contextFiles:s,toolNames:C,toolSummaries:w,promptMode:x>0?`minimal`:`full`,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:E,channels:D},docs:{localPath:t.docs?.localPath,webUrl:t.docs?.webUrl,sourceUrl:t.docs?.sourceUrl},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Oe.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:b.priorSummary}),ee=await r.dispatch(`before_prompt_build`,{prompt:u},i,{eventDispatcher:o});for(let e of ee)e&&(e.systemPrompt&&(O=e.systemPrompt),e.prependContext&&(O=`${e.prependContext}\n\n${O}`));await r.dispatch(`after_prompt_build`,{prompt:u,systemPrompt:O},i,{eventDispatcher:o});let k=Pa(ma(S,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},$e),A=t.llm.model,j=await r.dispatch(`before_model_resolve`,{prompt:u},i,{eventDispatcher:o});for(let e of j)e&&e.modelOverride&&(A=e.modelOverride);let M=m({...t.llm,model:A},n),N=new De({initialState:{systemPrompt:O,model:M,tools:k,messages:[]},getApiKey:e=>t.llm.apiKey});return b.messages.length>0&&N.replaceMessages(b.messages),{agent:N,resolvedModelId:A,historyMessages:b.messages,historyResult:b,workspaceDir:a.workspaceDir}}async function Ia(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;await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i}),await r.appendTranscriptEntry(n.compactionEntry),(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})}}async function La(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=[],x=new Map,S=da(),C=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Wa(`partial`in t?t.partial:void 0)??Wa(`message`in t?t.message:void 0)??Wa(`message`in e?e.message:void 0),i=Ga(t.delta,n,p);i&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:i}),m+=i),n&&(p=n,m=n)}if(t.type===`done`){let e=t.message;f=Ua(e);let n=Ga(``,f,m||p);n&&(await o.dispatchProgress(r,{type:`stream_text_delta`,text:n}),m+=n),p=f,m=f,e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ua(e);await c.dispatch(`assistant_message_end`,{sessionId:r,model:i,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:Va(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),r,e.toolCallId,e.toolName)}));b.push({message:t,toolResults:n}),d&&(await d(za(Ra(t),!!S.signal),n.map(Ba)),S.signal);return}if(e.type===`tool_execution_start`){m=``,x.set(e.toolCallId,e.args),s.onToolExecutionStart({toolName:e.toolName,args:e.args}),await o.dispatchProgress(r,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args});return}if(e.type===`tool_execution_end`){await s.onToolExecutionEnd({toolName:e.toolName,isError:e.isError});let t=typeof e.result==`string`?e.result:JSON.stringify(e.result),n=x.get(e.toolCallId);x.delete(e.toolCallId),await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:n,output:t,isError:e.isError})}});try{if(await c.dispatch(`llm_input`,{sessionId:r,model:i,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:a},l),u?.aborted)throw Error(`aborted`);y=Date.now(),await fa(S,async()=>{await t.prompt(n)});let e=S.signal;if(e)throw e;if(!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Ka(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){if(q(e))throw e;_=Ka(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{C()}let w=b.length>0?b[b.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:f?[f]:[],lastAssistant:w,usage:{input:h,output:g,total:h+g}},l);let T=b.length>0?Ua(b[b.length-1].message):``;if(S.signal)throw S.signal;return d&&b.length===0&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:T||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}function Ra(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function za(e,t){return!e||!t||e.content.trim()!==`HITL_PAUSED`?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Ba(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function Va(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:Ha(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Ha(e){let t=e.indexOf(`
70
70
  Preview:
71
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Ga(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Ka(e){if(!e||typeof e!=`object`)return null;let t=e;return Array.isArray(t.content)?t.content.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):null}function qa(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Ja(e){let t=Ya(e);return t?t.code===`http_error`&&t.statusCode?t.providerMessage?`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}: ${t.providerMessage}`:`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}`:t.code===`timeout`?`LLM request timed out`:t.code===`network_error`?t.message:t.code===`aborted`?`LLM request was aborted`:t.message:e instanceof Error?e.message:String(e)}function Ya(e){if(e instanceof V)return e;if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function Xa(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,skillUsageTracker:o,hookRegistry:s,hookContext:c,abortSignal:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!l?.aborted&&n.needsAnnounce(r)&&d<10;){d++,await n.waitForAll(r);let e=n.consumeCompleted(r);if(e.length===0)break;for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=Za(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await za({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,skillUsageTracker:o,hooks:s,hookCtx:c,abortSignal: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)}return{text:f,inputTokens:p,outputTokens:m,error:h}}function Za(e){if(e.length===1){let t=e[0];return Ai({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Ai({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
71
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Ua(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Wa(e){if(!e||typeof e!=`object`)return null;let t=e;return Array.isArray(t.content)?t.content.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):null}function Ga(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Ka(e){let t=qa(e);return t?t.code===`http_error`&&t.statusCode?t.providerMessage?`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}: ${t.providerMessage}`:`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}`:t.code===`timeout`?`LLM request timed out`:t.code===`network_error`?t.message:t.code===`aborted`?`LLM request was aborted`:t.message:e instanceof Error?e.message:String(e)}function qa(e){if(e instanceof V)return e;if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function Ja(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,skillUsageTracker:o,hookRegistry:s,hookContext:c,abortSignal:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!l?.aborted&&n.needsAnnounce(r)&&d<10;){d++,await n.waitForAll(r);let e=n.consumeCompleted(r);if(e.length===0)break;for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=Ya(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await La({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,skillUsageTracker:o,hooks:s,hookCtx:c,abortSignal: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)}return{text:f,inputTokens:p,outputTokens:m,error:h}}function Ya(e){if(e.length===1){let t=e[0];return Oi({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Oi({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
72
72
 
73
73
  ---
74
74
 
75
- `)}`}function Qa(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 $a(e){let t=Qa(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=F.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 eo(e){let t=e.watchFactory??((e,t,n)=>z.watch(e,t,n)),n=F.join(e.dataDir,`.aimax`),r=[{target:F.join(n,`MEMORY.md`),kind:`memory-file`},{target:F.join(n,`memory.md`),kind:`memory-file-lower`},{target:F.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=$a({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{}}}async function to(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,l=F.join(t.dataDir,`workspace`),u=new Map,d=new Map,f=!1,p=async e=>{let t=Date.now(),o=io(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(u.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)u.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(d.get(c)??0)<1e3)return;d.set(c,t);let l={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:l.reason,files:l.files,source:l.source,providerId:l.providerId,timestamp:l.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,l,{...a,sessionId:l.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=F.join(t.dataDir,`.aimax`),h=E({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i})?.provider??g({dataDir:t.dataDir,memoryDir:m,sessionId:i}),_=eo({dataDir:t.dataDir,sessionId:i,providerId:o??s??h.id,provider:h,onMemoryChanged:p});h.sync&&h.sync(`session-start`).catch(()=>{});let v=async e=>{await c(t.dataDir,i,e,ro({providerId:o,pluginId:s,onMemoryChanged:p}))};return{workspaceDir:l,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:v,persistInitialUserEntry:async e=>f?!1:(await v({role:`user`,content:e,timestamp:new Date().toISOString()}),f=!0,!0),stop:()=>{_()}}}function no(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function ro(e){return e.providerId||e.pluginId?{providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function io(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}function ao(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oo(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function so(){let e=Oe.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function co(e){let t=e.trim(),n=so();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?F.join(n,t.slice(2)):void 0:F.resolve(t)}const lo=new je({allErrors:!0,strict:!1}),uo=new Map;function fo(e,t){let n=uo.get(t);if(n)return n;let r=lo.compile(e);return uo.set(t,r),r}function po(e){let t=e.cacheKey??JSON.stringify(e.schema),n=fo(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function mo(e){let t=oo(e?.allow),n=oo(e?.deny),r=oo(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 ho(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=po({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 go(e){try{return z.realpathSync(e)}catch{return null}}function _o(e){try{return z.statSync(e)}catch{return null}}function vo(e,t){let n=F.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!F.isAbsolute(n)}function yo(e){return`0o${e.toString(8).padStart(3,`0`)}`}const bo=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),xo=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function So(e){let t=F.join(e,`package.json`);if(z.existsSync(t))try{let e=JSON.parse(z.readFileSync(t,`utf-8`));return ao(e)?e:void 0}catch{return}}function Co(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 wo(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function To(e){let t=go(e.source),n=go(e.rootDir);return!t||!n||vo(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Eo(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=F.resolve(r);if(n.has(t))continue;n.add(t);let i=_o(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 Do(e){return To({source:e.source,rootDir:e.rootDir})||Eo({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:wo(e.ownershipUid)})}function Oo(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=${yo(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function ko(e){let t=Do({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Oo(t),source:e.source}),!0):!1}function Ao(e){return F.basename(e,F.extname(e))}function jo(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 Mo(e){for(let t of xo){let n=F.join(e,t);if(z.existsSync(n))return n}return null}function No(e){let t;try{t=z.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=F.join(e.rootDir,n.name);if(n.isFile()){if(!bo.has(F.extname(n.name)))continue;let r=F.dirname(t);if(ko({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(jo({idHint:Ao(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=So(t),i=Co(r);if(i.status===`ok`){for(let n of i.entries){let i=F.resolve(t,n);if(!vo(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!z.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!bo.has(F.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(ko({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Ao(i)}`:Ao(i);e.candidates.push(jo({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=Mo(t);a&&(ko({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(jo({idHint:F.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Po(e){return e?e.map(co).filter(e=>typeof e==`string`&&e.length>0):[]}function Fo(){let e=so();if(e)return F.join(e,`.aimax`,`extensions`)}function Io(e){return F.join(e,`.aimax`,`extensions`)}function Lo(e){return F.join(e,`.aimax`,`extensions`)}function Ro(e={}){let t=[],n=[],r=Po(e.extraPaths);for(let i of r){if(!z.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=_o(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!bo.has(F.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=F.dirname(i);if(ko({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(jo({idHint:Ao(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&No({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?No({rootDir:Io(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&No({rootDir:Lo(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Fo();return i?No({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&&No({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function zo(e){let t=e.rejectHardlinks??!0,n=go(e.rootPath),r=go(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!vo(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=z.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:z.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Bo=`aimax.plugin.json`,Vo=[Bo];function Ho(e){for(let t of Vo){let n=F.join(e,t);if(z.existsSync(n))return n}return F.join(e,Bo)}function Uo(e,t=!0){let n=Ho(e),r=zo({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(z.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{z.closeSync(r.fd)}if(!ao(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=ao(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=oo(i.skills),f;return ao(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 Wo(e){let t=new Map,n=[];for(let r of e){let e=Uo(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 Go=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Ko(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function qo(e,t,n,r){process.stderr.write(`[${Ko()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Jo(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>qo(Go.INFO,e.pluginId,t,n),warn:n=>qo(Go.WARN,e.pluginId,t,n),error:n=>qo(Go.ERROR,e.pluginId,t,n)})}}}function Yo(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 Xo(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 Zo(e){let t=[...e.registry.diagnostics],n=new ua,r=new _a,i=[],a=[],o=e.runtime?.llm?it({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Qo(e.runtime?.llmAllowlist),c=Me(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Yo({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Xo({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 m=f&&typeof f==`object`&&`default`in f?f.default:f,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){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 g=Jo({pluginId:l.id}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!$o(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},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);p({pluginId:l.id,id:e.id,create:e.create,config:_,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`);D({pluginId:l.id,id:e.id,create:e.create,config:_,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=F.isAbsolute(e)?e:F.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>ca(l.id)};try{h(v)}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=F.isAbsolute(e)?e:F.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Qo(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function $o(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function es(e={}){let t=mo(e.config),n=Ro({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Wo(n.candidates),i=ho({config:t,registry:r}),a=Zo({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 ts(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?es({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):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 _a,pluginSkillDirs:o?.registry.skills??[],pluginTools:o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function ns(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=F.join(t.dataDir,`workspace`),a=n,o=!a;a?await u(t.dataDir,a):a=await l(t.dataDir,t.channel);let s={sessionId:a,workspaceDir:i,channel:t.channel},c=ts({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),d=c.hookRegistry,f=await to({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:d});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:d,pluginContext:c,runContext:f,start:e=>zt({sessionId:a,runParams:t,hookRegistry:d,hookContext:s,eventDispatcher:r,...e})}}function rs(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function is(e){if(!(e instanceof Error))return{errorValue:rs(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]=rs(n[e]));return t}async function as(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...is(e.error)}})}function os(e,t){return F.join(r(e,t),`pending-hitl.json`)}function ss(e,t){return F.join(r(e,t),`hitl-history.jsonl`)}async function cs(e,t,n){let i=r(e,t);await P.mkdir(i,{recursive:!0});let a=os(e,t);await P.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function ls(e,t,n){let i=r(e,t);await P.mkdir(i,{recursive:!0});let a=ss(e,t),o=JSON.stringify(n)+`
76
- `;await P.appendFile(a,o,`utf-8`)}async function us(e,t){let n=os(e,t);try{let e=await P.readFile(n,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ds(e,t){let n=ss(e,t);try{let e=await P.readFile(n,`utf-8`),t=[];for(let n of e.split(`
77
- `)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function fs(e,t,n,r,i,a){let o=new Date().toISOString(),s={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:o,updatedAt:o};return await cs(e,t,s),await ls(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:o}),s}async function ps(e,t,n,r,i){let a=await us(e,t);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o=new Date().toISOString(),s={...a,status:r,resolution:i,updatedAt:o};await cs(e,t,s);let c={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await ls(e,t,{requestId:n,sessionId:t,action:c,payload:i??a.request,timestamp:o}),s}async function ms(e,t,n){let r=await us(e,t);return!r||r.request.requestId!==n?null:r.status===`resolved`?r:null}async function hs(e,t){let n=os(e,t);try{await P.unlink(n)}catch(e){if(e.code===`ENOENT`)return;throw e}}function gs(e,t){return{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:{"Client-Code":`AIMax`,"X-Session-Id":t},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}async function _s(e,t){Nt();let n=Date.now(),r=new Pt(e),i=yn(e),a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await ns({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,m=c.pluginContext,h=c.runContext;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}}),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 w(e.dataDir,no({sessionId:l,title:Rt(a),channel:e.channel})),i.resetCommand&&(o=await h.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let g=new AbortController;e.abortSignal?.aborted?g.abort():e.abortSignal?.addEventListener(`abort`,()=>g.abort());let _=await Le(e.dataDir),v=[],y=Be(_,{warn:e=>v.push(e)});await r.dispatchDiagnostic(l,{level:v.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length}});let b=await Ke(e.dataDir,m.pluginSkillDirs),x=new rt({workspaceDir:d,sessionId:l,skills:b,report:e=>r.dispatchProgress(l,e),reportDiagnostic:e=>r.dispatchDiagnostic(l,{level:e.level,scope:`skill`,phase:e.phase,message:e.message,details:e.details})});await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:b.length,pluginSkillDirCount:m.pluginSkillDirs.length}});let S=e=>h.appendTranscriptEntry(e),C=await xn({invocation:i,skills:b,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(C.kind===`completed`)return C.result;let T=C.effectivePrompt;a=C.transcriptMessage;let E=typeof T==`string`?T:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof T==`string`?`string`:`messages`,transcriptLength:a.length}});let D=await La({session:{runParams:e,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:b,effectivePromptText:E,pluginTools:m.pluginTools},dependencies:{registry:t,spawnFn:e=>_s(e,new Ze),createModel:gs,abortSignal:g.signal}}),O=D.agent,ee=D.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:ee,historyMessageCount:D.historyMessages.length,pluginToolCount:m.pluginTools.length}}),g.signal.addEventListener(`abort`,()=>O.abort());let k=0,A=0,j=``,M;try{o=await h.persistInitialUserEntry(a)||o,await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let e=await za({agent:O,message:T,sessionId:l,modelId:ee,historyMessages:D.historyMessages,eventDispatcher:r,skillUsageTracker:x,hooks:p,hookCtx:f,abortSignal:g.signal,onTurnRecordProduced:async(e,t)=>{e&&await S(e);for(let e of t)await S(e)}});j=e.text,k+=e.inputTokens,A+=e.outputTokens,e.error&&(M=e.error),await r.dispatchDiagnostic(l,{level:e.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!e.error,error:e.error,inputTokens:e.inputTokens,outputTokens:e.outputTokens}}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let n=await Xa({agent:O,registry:t,sessionId:l,resolvedModelId:ee,eventDispatcher:r,skillUsageTracker:x,hookRegistry:p,hookContext:f,abortSignal:g.signal,appendEntry:S});n.text&&(j=n.text),k+=n.inputTokens,A+=n.outputTokens,n.error&&!M&&(M=n.error),await r.dispatchDiagnostic(l,{level:n.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}})}catch(t){if(q(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await fs(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}});let c={input:k,output:A,total:k+A};return Ht({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}})}throw await as({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),t}finally{et(l),h.stop()}let N={input:k,output:A,total:k+A};return await r.dispatchDiagnostic(l,{level:M?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:N.input,outputTokens:N.output,totalTokens:N.total,hasError:!!M,error:M}}),Ht({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:N,error:M})}async function vs(e,t){let n=t??new Ze;try{return await _s(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:is(t)}),t}}const ys={"AGENTS.md":`---
75
+ `)}`}function Xa(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 Za(e){let t=Xa(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=F.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 Qa(e){let t=e.watchFactory??((e,t,n)=>z.watch(e,t,n)),n=F.join(e.dataDir,`.aimax`),r=[{target:F.join(n,`MEMORY.md`),kind:`memory-file`},{target:F.join(n,`memory.md`),kind:`memory-file-lower`},{target:F.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=Za({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{}}}async function $a(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,l=F.join(t.dataDir,`workspace`),u=new Map,d=new Map,f=!1,p=async e=>{let t=Date.now(),o=no(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(u.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)u.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(d.get(c)??0)<1e3)return;d.set(c,t);let l={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:l.reason,files:l.files,source:l.source,providerId:l.providerId,timestamp:l.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,l,{...a,sessionId:l.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=F.join(t.dataDir,`.aimax`),h=E({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i})?.provider??g({dataDir:t.dataDir,memoryDir:m,sessionId:i}),_=Qa({dataDir:t.dataDir,sessionId:i,providerId:o??s??h.id,provider:h,onMemoryChanged:p});h.sync&&h.sync(`session-start`).catch(()=>{});let v=async e=>{await c(t.dataDir,i,e,to({providerId:o,pluginId:s,onMemoryChanged:p}))};return{workspaceDir:l,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:v,persistInitialUserEntry:async e=>f?!1:(await v({role:`user`,content:e,timestamp:new Date().toISOString()}),f=!0,!0),stop:()=>{_()}}}function eo(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function to(e){return e.providerId||e.pluginId?{providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function no(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}function ro(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function io(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function ao(){let e=Oe.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function oo(e){let t=e.trim(),n=ao();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?F.join(n,t.slice(2)):void 0:F.resolve(t)}const so=new je({allErrors:!0,strict:!1}),co=new Map;function lo(e,t){let n=co.get(t);if(n)return n;let r=so.compile(e);return co.set(t,r),r}function uo(e){let t=e.cacheKey??JSON.stringify(e.schema),n=lo(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function fo(e){let t=io(e?.allow),n=io(e?.deny),r=io(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 po(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=uo({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 mo(e){try{return z.realpathSync(e)}catch{return null}}function ho(e){try{return z.statSync(e)}catch{return null}}function go(e,t){let n=F.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!F.isAbsolute(n)}function _o(e){return`0o${e.toString(8).padStart(3,`0`)}`}const vo=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),yo=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function bo(e){let t=F.join(e,`package.json`);if(z.existsSync(t))try{let e=JSON.parse(z.readFileSync(t,`utf-8`));return ro(e)?e:void 0}catch{return}}function xo(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 So(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Co(e){let t=mo(e.source),n=mo(e.rootDir);return!t||!n||go(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function wo(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=F.resolve(r);if(n.has(t))continue;n.add(t);let i=ho(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 To(e){return Co({source:e.source,rootDir:e.rootDir})||wo({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:So(e.ownershipUid)})}function Eo(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=${_o(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Do(e){let t=To({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Eo(t),source:e.source}),!0):!1}function Oo(e){return F.basename(e,F.extname(e))}function ko(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 Ao(e){for(let t of yo){let n=F.join(e,t);if(z.existsSync(n))return n}return null}function jo(e){let t;try{t=z.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=F.join(e.rootDir,n.name);if(n.isFile()){if(!vo.has(F.extname(n.name)))continue;let r=F.dirname(t);if(Do({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(ko({idHint:Oo(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=bo(t),i=xo(r);if(i.status===`ok`){for(let n of i.entries){let i=F.resolve(t,n);if(!go(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!z.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!vo.has(F.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Do({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Oo(i)}`:Oo(i);e.candidates.push(ko({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=Ao(t);a&&(Do({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(ko({idHint:F.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Mo(e){return e?e.map(oo).filter(e=>typeof e==`string`&&e.length>0):[]}function No(){let e=ao();if(e)return F.join(e,`.aimax`,`extensions`)}function Po(e){return F.join(e,`.aimax`,`extensions`)}function Fo(e){return F.join(e,`.aimax`,`extensions`)}function Io(e={}){let t=[],n=[],r=Mo(e.extraPaths);for(let i of r){if(!z.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=ho(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!vo.has(F.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=F.dirname(i);if(Do({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(ko({idHint:Oo(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&jo({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?jo({rootDir:Po(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&jo({rootDir:Fo(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=No();return i?jo({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&&jo({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Lo(e){let t=e.rejectHardlinks??!0,n=mo(e.rootPath),r=mo(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!go(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=z.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:z.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ro=`aimax.plugin.json`,zo=[Ro];function Bo(e){for(let t of zo){let n=F.join(e,t);if(z.existsSync(n))return n}return F.join(e,Ro)}function Vo(e,t=!0){let n=Bo(e),r=Lo({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(z.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{z.closeSync(r.fd)}if(!ro(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=ro(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=io(i.skills),f;return ro(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 Ho(e){let t=new Map,n=[];for(let r of e){let e=Vo(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 Uo=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Wo(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function Go(e,t,n,r){process.stderr.write(`[${Wo()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Ko(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Go(Uo.INFO,e.pluginId,t,n),warn:n=>Go(Uo.WARN,e.pluginId,t,n),error:n=>Go(Uo.ERROR,e.pluginId,t,n)})}}}function qo(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 Jo(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 Yo(e){let t=[...e.registry.diagnostics],n=new ca,r=new ha,i=[],a=[],o=e.runtime?.llm?it({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Xo(e.runtime?.llmAllowlist),c=Me(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=qo({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Jo({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 m=f&&typeof f==`object`&&`default`in f?f.default:f,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){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 g=Ko({pluginId:l.id}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Zo(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},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);p({pluginId:l.id,id:e.id,create:e.create,config:_,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`);D({pluginId:l.id,id:e.id,create:e.create,config:_,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=F.isAbsolute(e)?e:F.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>oa(l.id)};try{h(v)}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=F.isAbsolute(e)?e:F.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Xo(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Zo(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Qo(e={}){let t=fo(e.config),n=Io({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Ho(n.candidates),i=po({config:t,registry:r}),a=Yo({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 $o(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Qo({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):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 ha,pluginSkillDirs:o?.registry.skills??[],pluginTools:o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function es(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=F.join(t.dataDir,`workspace`),a=n,o=!a;a?await u(t.dataDir,a):a=await l(t.dataDir,t.channel);let s={sessionId:a,workspaceDir:i,channel:t.channel},c=$o({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),d=c.hookRegistry,f=await $a({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:d});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:d,pluginContext:c,runContext:f,start:e=>zt({sessionId:a,runParams:t,hookRegistry:d,hookContext:s,eventDispatcher:r,...e})}}function ts(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ns(e){if(!(e instanceof Error))return{errorValue:ts(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]=ts(n[e]));return t}async function rs(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ns(e.error)}})}function is(e,t){return F.join(r(e,t),`pending-hitl.json`)}function as(e,t){return F.join(r(e,t),`hitl-history.jsonl`)}async function os(e,t,n){let i=r(e,t);await P.mkdir(i,{recursive:!0});let a=is(e,t);await P.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function ss(e,t,n){let i=r(e,t);await P.mkdir(i,{recursive:!0});let a=as(e,t),o=JSON.stringify(n)+`
76
+ `;await P.appendFile(a,o,`utf-8`)}async function cs(e,t){let n=is(e,t);try{let e=await P.readFile(n,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ls(e,t){let n=as(e,t);try{let e=await P.readFile(n,`utf-8`),t=[];for(let n of e.split(`
77
+ `)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function us(e,t,n,r,i,a){let o=new Date().toISOString(),s={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:o,updatedAt:o};return await os(e,t,s),await ss(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:o}),s}async function ds(e,t,n,r,i){let a=await cs(e,t);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o=new Date().toISOString(),s={...a,status:r,resolution:i,updatedAt:o};await os(e,t,s);let c={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await ss(e,t,{requestId:n,sessionId:t,action:c,payload:i??a.request,timestamp:o}),s}async function fs(e,t,n){let r=await cs(e,t);return!r||r.request.requestId!==n?null:r.status===`resolved`?r:null}async function ps(e,t){let n=is(e,t);try{await P.unlink(n)}catch(e){if(e.code===`ENOENT`)return;throw e}}function ms(e,t){return{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:{"Client-Code":`AIMax`,"X-Session-Id":t},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}async function hs(e,t){Nt();let n=Date.now(),r=new Pt(e),i=yn(e),a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await es({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,m=c.pluginContext,h=c.runContext;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}}),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 w(e.dataDir,eo({sessionId:l,title:Rt(a),channel:e.channel})),i.resetCommand&&(o=await h.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let g=new AbortController;e.abortSignal?.aborted?g.abort():e.abortSignal?.addEventListener(`abort`,()=>g.abort());let _=await Le(e.dataDir),v=[],y=Be(_,{warn:e=>v.push(e)});await r.dispatchDiagnostic(l,{level:v.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length}});let b=await Ke(e.dataDir,m.pluginSkillDirs),x=new rt({workspaceDir:d,sessionId:l,skills:b,report:e=>r.dispatchProgress(l,e),reportDiagnostic:e=>r.dispatchDiagnostic(l,{level:e.level,scope:`skill`,phase:e.phase,message:e.message,details:e.details})});await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:b.length,pluginSkillDirCount:m.pluginSkillDirs.length}});let S=e=>h.appendTranscriptEntry(e),C=await xn({invocation:i,skills:b,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(C.kind===`completed`)return C.result;let T=C.effectivePrompt;a=C.transcriptMessage;let E=typeof T==`string`?T:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof T==`string`?`string`:`messages`,transcriptLength:a.length}});let D=await Fa({session:{runParams:e,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:b,effectivePromptText:E,pluginTools:m.pluginTools},dependencies:{registry:t,spawnFn:e=>hs(e,new Ze),createModel:ms,abortSignal:g.signal}}),O=D.agent,ee=D.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:ee,historyMessageCount:D.historyMessages.length,pluginToolCount:m.pluginTools.length}}),g.signal.addEventListener(`abort`,()=>O.abort());let k=0,A=0,j=``,M;try{o=await h.persistInitialUserEntry(a)||o,await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let e=await La({agent:O,message:T,sessionId:l,modelId:ee,historyMessages:D.historyMessages,eventDispatcher:r,skillUsageTracker:x,hooks:p,hookCtx:f,abortSignal:g.signal,onTurnRecordProduced:async(e,t)=>{e&&await S(e);for(let e of t)await S(e)}});j=e.text,k+=e.inputTokens,A+=e.outputTokens,e.error&&(M=e.error),await r.dispatchDiagnostic(l,{level:e.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!e.error,error:e.error,inputTokens:e.inputTokens,outputTokens:e.outputTokens}}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let n=await Ja({agent:O,registry:t,sessionId:l,resolvedModelId:ee,eventDispatcher:r,skillUsageTracker:x,hookRegistry:p,hookContext:f,abortSignal:g.signal,appendEntry:S});n.text&&(j=n.text),k+=n.inputTokens,A+=n.outputTokens,n.error&&!M&&(M=n.error),await r.dispatchDiagnostic(l,{level:n.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}})}catch(t){if(q(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await us(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}});let c={input:k,output:A,total:k+A};return Ht({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}})}throw await rs({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),t}finally{et(l),h.stop()}let N={input:k,output:A,total:k+A};return await r.dispatchDiagnostic(l,{level:M?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:N.input,outputTokens:N.output,totalTokens:N.total,hasError:!!M,error:M}}),Ht({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:N,error:M})}async function gs(e,t){let n=t??new Ze;try{return await hs(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:ns(t)}),t}}const _s={"AGENTS.md":`---
78
78
  title: "AGENTS.md Template"
79
79
  summary: ".aimax template for AGENTS.md"
80
80
  read_when:
@@ -381,4 +381,4 @@ read_when:
381
381
  # Add tasks below when you want the agent to check something periodically.
382
382
 
383
383
  # This file lives at .aimax/HEARTBEAT.md, not in workspace/.
384
- `},bs=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`,`HEARTBEAT.md`];async function $(e,t){try{if(!(await P.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 P.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function xs(e,t,n){try{if(!(await P.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 P.mkdir(F.dirname(e),{recursive:!0});try{await P.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 Ss(e){let t=B(e);return[e,t,F.join(t,`skills`),F.join(t,`sessions`),F.join(t,`memory`),F.join(e,`workspace`)]}function Cs(e){let t=B(e);return[...bs.filter(e=>e!==`BOOTSTRAP.md`).map(e=>F.join(t,e)),F.join(t,`MEMORY.md`)]}function ws(e){return F.join(B(e),`.bootstrapped`)}async function Ts(e){try{return(await P.stat(ws(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Es(e){let t=ws(e);await P.mkdir(F.dirname(t),{recursive:!0}),await P.writeFile(t,``,{encoding:`utf-8`})}async function Ds(e){let t=[],n=[];for(let n of Ss(e))try{(await P.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Cs(e))try{(await P.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 Os(e){return(await Ds(e)).ready}async function ks(e){if(await Ts(e))return{ready:!0,performedBootstrap:!1};if((await Ds(e)).ready)return await Es(e),{ready:!0,performedBootstrap:!1};let t=await As(e);return await Es(e),{ready:!0,performedBootstrap:!0,result:t}}async function As(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=B(e),r=F.join(e,`workspace`),i=F.join(n,`skills`),a=F.join(n,`sessions`),o=F.join(n,`memory`);await $(e,t),await $(n,t),await $(i,t),await $(a,t),await $(o,t),await $(r,t);for(let e of bs){let r=ys[e]??``;await xs(F.join(n,e),r,t)}return await xs(F.join(n,`MEMORY.md`),``,t),t}async function js(e){let t=F.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await P.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 Ms(e,t){let n=F.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 P.mkdir(F.dirname(n),{recursive:!0}),await P.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Ns(e,t){let n=await js(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 Ps(e,t=7){let n=await js(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 Ms(e,n),i}async function Fs(e,t,n){let r=await us(e,t);return r?r.request.requestId===n?r.sessionId===t?r.status===`pending`?Ne(r.request)?(await ps(e,t,n,`expired`),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:r}:{valid:!1,reason:`HITL request is already "${r.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${r.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${r.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function Is(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i}=e,a=await ms(t,n,r);if(a){let e=a.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:a,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${a.status}", cannot resume`)}let o=await Fs(t,n,r);if(!o.valid)throw Error(`HITL resume validation failed: ${o.reason}`);let s=await ps(t,n,r,`resolved`,i);if(!s)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:s,idempotentReplay:!1}}export{Ie as BOOTSTRAP_FILE_NAMES,Pe as BOOTSTRAP_MAX_CHARS,Fe as BOOTSTRAP_TOTAL_MAX_CHARS,K as HitlPauseSignal,Xe as MAX_CHILDREN_PER_SESSION,Ye as MAX_SUBAGENT_DEPTH,y as MemoryIndexManager,Bo as PLUGIN_MANIFEST_FILENAME,Vo as PLUGIN_MANIFEST_FILENAMES,_a as PluginHookRegistry,ua as PluginToolRegistry,Ze as SubagentRegistry,le as addAgent,ae as addBinding,B as aimaxDir,gi as appendToMemory,c as appendTranscriptEntry,As as bootstrapMountLayout,Be as buildBootstrapContextFiles,Je as buildSkillsPrompt,Ai as buildSubagentAnnounceMessage,aa as buildSystemPrompt,Ps as cleanupOldSubagentRecords,hs as clearPendingHitl,m as collapseLogPath,x as contextSnapshotPath,Ri as createAgentTools,qr as createApplyPatchTool,Ar as createBashTool,g as createBuiltinMemoryProvider,oi as createClarifyTool,rr as createContextManager,zr as createEditFileTool,gr as createExecTool,Li as createImageTool,Vr as createListDirTool,wi as createMemoryAppendTool,Si as createMemoryGetTool,bi as createMemorySearchTool,fs as createPendingHitl,ca as createPluginProgressEmitter,Jo as createPluginRuntime,br as createProcessTool,Fr as createReadFileTool,Ei as createRequestApprovalTool,Oi as createRequestReviewTool,l as createSession,Mn as createSessionContextStore,ji as createSessionsSpawnTool,Fi as createSubagentsTool,Lr as createWriteFileTool,vi as deleteMemoryFile,Ro as discoverAIMaxPlugins,ks as ensureBootstrapMountLayout,u as ensureSession,v as exportSession,It as generateSessionTitle,ne as getAgentConfig,hi as getMemoryLines,Ts as hasBootstrapSentinel,ss as hitlHistoryPath,es as initializePluginSystem,Ds as inspectBootstrapMountLayout,h as inspectSession,Os as isBootstrapMountLayoutReady,q as isHitlPauseSignal,k as listAgents,qt as listAvailableSlashCommands,oe as listBindings,di as listMemoryFiles,f as listSessionSummaries,d as listSessions,Ns as listSubagentRunsFromDisk,ce as loadAgentsConfig,Le as loadBootstrapFiles,us as loadPendingHitl,us as readPendingHitl,Uo as loadPluginManifest,Wo as loadPluginManifestRegistry,Zo as loadPlugins,a as loadSessionContextSnapshot,S as loadSessionMetadata,Ge as loadSkills,qe as loadSkillsFromDirs,Ke as loadSkillsWithPluginDirs,js as loadSubagentRegistryFromDisk,T as loadTranscript,si as memoryDir,s as metadataPath,A as normalizeAgentId,mo as normalizePluginsConfig,os as pendingHitlPath,ci as primaryMemoryPath,ds as readHitlHistory,fi as readMemoryFile,pi as readPrimaryMemory,p as registerEmbeddingProvider,D as registerMemoryProvider,re as removeAgent,ue as removeBindings,_i as replaceMemoryFile,o as resetEmbeddingProviderRegistryForTests,O as resetMemoryProviderRegistryForTests,j as resolveAgentDir,M as resolveAgentIdByBinding,se as resolveAgentsConfigPath,ie as resolveDefaultAgentId,_ as resolveEmbeddingProvider,Is as resolveHitlRequest,Is as resolvePendingHitl,E as resolveMemoryProvider,te as resolveModelFallbacks,N as resolveModelString,Ho as resolvePluginManifestPath,vs as runAgent,ee as saveAgentsConfig,w as saveSessionMetadata,Ms as saveSubagentRegistryToDisk,mi as searchMemory,r as sessionDir,e as sessionMemoryPath,C as sessionsDir,Ve as skillsDir,i as toolResultsDir,n as transcriptPath,ps as transitionHitlStatus,de as updateAgentIdentity,t as updateSessionMetadata,ho as validatePluginsConfig,Fs as validateResume,ga as wrapToolsWithHooks};
384
+ `},vs=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`,`HEARTBEAT.md`];async function $(e,t){try{if(!(await P.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 P.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function ys(e,t,n){try{if(!(await P.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 P.mkdir(F.dirname(e),{recursive:!0});try{await P.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 bs(e){let t=B(e);return[e,t,F.join(t,`skills`),F.join(t,`sessions`),F.join(t,`memory`),F.join(e,`workspace`)]}function xs(e){let t=B(e);return[...vs.filter(e=>e!==`BOOTSTRAP.md`).map(e=>F.join(t,e)),F.join(t,`MEMORY.md`)]}function Ss(e){return F.join(B(e),`.bootstrapped`)}async function Cs(e){try{return(await P.stat(Ss(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function ws(e){let t=Ss(e);await P.mkdir(F.dirname(t),{recursive:!0}),await P.writeFile(t,``,{encoding:`utf-8`})}async function Ts(e){let t=[],n=[];for(let n of bs(e))try{(await P.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of xs(e))try{(await P.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 Es(e){return(await Ts(e)).ready}async function Ds(e){if(await Cs(e))return{ready:!0,performedBootstrap:!1};if((await Ts(e)).ready)return await ws(e),{ready:!0,performedBootstrap:!1};let t=await Os(e);return await ws(e),{ready:!0,performedBootstrap:!0,result:t}}async function Os(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=B(e),r=F.join(e,`workspace`),i=F.join(n,`skills`),a=F.join(n,`sessions`),o=F.join(n,`memory`);await $(e,t),await $(n,t),await $(i,t),await $(a,t),await $(o,t),await $(r,t);for(let e of vs){let r=_s[e]??``;await ys(F.join(n,e),r,t)}return await ys(F.join(n,`MEMORY.md`),``,t),t}async function ks(e){let t=F.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await P.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 As(e,t){let n=F.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 P.mkdir(F.dirname(n),{recursive:!0}),await P.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function js(e,t){let n=await ks(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 Ms(e,t=7){let n=await ks(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 As(e,n),i}async function Ns(e,t,n){let r=await cs(e,t);return r?r.request.requestId===n?r.sessionId===t?r.status===`pending`?Ne(r.request)?(await ds(e,t,n,`expired`),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:r}:{valid:!1,reason:`HITL request is already "${r.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${r.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${r.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function Ps(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i}=e,a=await fs(t,n,r);if(a){let e=a.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:a,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${a.status}", cannot resume`)}let o=await Ns(t,n,r);if(!o.valid)throw Error(`HITL resume validation failed: ${o.reason}`);let s=await ds(t,n,r,`resolved`,i);if(!s)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:s,idempotentReplay:!1}}export{Ie as BOOTSTRAP_FILE_NAMES,Pe as BOOTSTRAP_MAX_CHARS,Fe as BOOTSTRAP_TOTAL_MAX_CHARS,K as HitlPauseSignal,Xe as MAX_CHILDREN_PER_SESSION,Ye as MAX_SUBAGENT_DEPTH,y as MemoryIndexManager,Ro as PLUGIN_MANIFEST_FILENAME,zo as PLUGIN_MANIFEST_FILENAMES,ha as PluginHookRegistry,ca as PluginToolRegistry,Ze as SubagentRegistry,le as addAgent,ae as addBinding,B as aimaxDir,mi as appendToMemory,c as appendTranscriptEntry,Os as bootstrapMountLayout,Be as buildBootstrapContextFiles,Je as buildSkillsPrompt,Oi as buildSubagentAnnounceMessage,ra as buildSystemPrompt,Ms as cleanupOldSubagentRecords,ps as clearPendingHitl,m as collapseLogPath,x as contextSnapshotPath,Ii as createAgentTools,Gr as createApplyPatchTool,Or as createBashTool,g as createBuiltinMemoryProvider,ii as createClarifyTool,rr as createContextManager,Lr as createEditFileTool,mr as createExecTool,Fi as createImageTool,zr as createListDirTool,Si as createMemoryAppendTool,bi as createMemoryGetTool,vi as createMemorySearchTool,us as createPendingHitl,oa as createPluginProgressEmitter,Ko as createPluginRuntime,vr as createProcessTool,Nr as createReadFileTool,wi as createRequestApprovalTool,Ei as createRequestReviewTool,l as createSession,Mn as createSessionContextStore,ki as createSessionsSpawnTool,Ni as createSubagentsTool,Fr as createWriteFileTool,gi as deleteMemoryFile,Io as discoverAIMaxPlugins,Ds as ensureBootstrapMountLayout,u as ensureSession,v as exportSession,It as generateSessionTitle,ne as getAgentConfig,pi as getMemoryLines,Cs as hasBootstrapSentinel,as as hitlHistoryPath,Qo as initializePluginSystem,Ts as inspectBootstrapMountLayout,h as inspectSession,Es as isBootstrapMountLayoutReady,q as isHitlPauseSignal,k as listAgents,qt as listAvailableSlashCommands,oe as listBindings,li as listMemoryFiles,f as listSessionSummaries,d as listSessions,js as listSubagentRunsFromDisk,ce as loadAgentsConfig,Le as loadBootstrapFiles,cs as loadPendingHitl,cs as readPendingHitl,Vo as loadPluginManifest,Ho as loadPluginManifestRegistry,Yo as loadPlugins,a as loadSessionContextSnapshot,S as loadSessionMetadata,Ge as loadSkills,qe as loadSkillsFromDirs,Ke as loadSkillsWithPluginDirs,ks as loadSubagentRegistryFromDisk,T as loadTranscript,ai as memoryDir,s as metadataPath,A as normalizeAgentId,fo as normalizePluginsConfig,is as pendingHitlPath,oi as primaryMemoryPath,ls as readHitlHistory,ui as readMemoryFile,di as readPrimaryMemory,p as registerEmbeddingProvider,D as registerMemoryProvider,re as removeAgent,ue as removeBindings,hi as replaceMemoryFile,o as resetEmbeddingProviderRegistryForTests,O as resetMemoryProviderRegistryForTests,j as resolveAgentDir,M as resolveAgentIdByBinding,se as resolveAgentsConfigPath,ie as resolveDefaultAgentId,_ as resolveEmbeddingProvider,Ps as resolveHitlRequest,Ps as resolvePendingHitl,E as resolveMemoryProvider,te as resolveModelFallbacks,N as resolveModelString,Bo as resolvePluginManifestPath,gs as runAgent,ee as saveAgentsConfig,w as saveSessionMetadata,As as saveSubagentRegistryToDisk,fi as searchMemory,r as sessionDir,e as sessionMemoryPath,C as sessionsDir,Ve as skillsDir,i as toolResultsDir,n as transcriptPath,ds as transitionHitlStatus,de as updateAgentIdentity,t as updateSessionMetadata,po as validatePluginsConfig,Ns as validateResume,ma as wrapToolsWithHooks};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.0.29",
3
+ "version": "0.0.30",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",