@gencode/agents 0.0.10 → 0.0.11

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 +34 -34
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,u as h,v as g,y as _}from"./builtin-provider-C0d7-NZt.js";import{i as v,n as y,r as b}from"./provider-registry-rVbsCDN2.js";import{_ as x,a as S,c as C,d as w,f as T,g as E,h as D,i as ee,l as te,m as O,n as k,o as A,p as j,s as ne,t as re,u as ie,v as ae}from"./config-DG3Q1aJ6.js";import M from"node:fs/promises";import N from"node:path";import{Type as P,calculateCost as oe,getEnvApiKey as se,parseStreamingJson as ce,registerApiProvider as le,registerBuiltInApiProviders as ue,supportsXhigh as de}from"@mariozechner/pi-ai";import fe from"openai";import{AssistantMessageEventStream as pe}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as F}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as me,hasCopilotVisionInput as he}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as ge,clampReasoning as _e}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as ve}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import{createHash as ye,randomUUID as be}from"node:crypto";import I from"node:fs";import{Agent as xe}from"@mariozechner/pi-agent-core";import Se from"node:os";import{spawn as Ce}from"node:child_process";import we from"ajv";import{createJiti as Te}from"jiti";const Ee=2e4,De=15e4,Oe=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`HEARTBEAT.md`,`MEMORY.md`,`BOOTSTRAP.md`];function L(e){return N.join(e,`.aimax`)}async function ke(e){let t=L(e),n=[];for(let e of Oe){let r=N.join(t,e);try{let t=await M.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await M.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function Ae(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
1
+ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,p as f,r as p,s as m,u as h,v as g,y as _}from"./builtin-provider-C0d7-NZt.js";import{i as v,n as y,r as b}from"./provider-registry-rVbsCDN2.js";import{_ as x,a as S,c as C,d as w,f as T,g as E,h as D,i as O,l as k,m as A,n as j,o as ee,p as te,s as ne,t as re,u as ie,v as ae}from"./config-DG3Q1aJ6.js";import M from"node:fs/promises";import N from"node:path";import{Type as P,calculateCost as oe,getEnvApiKey as se,parseStreamingJson as ce,registerApiProvider as le,registerBuiltInApiProviders as ue,supportsXhigh as de}from"@mariozechner/pi-ai";import fe from"openai";import{AssistantMessageEventStream as pe}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as F}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as me,hasCopilotVisionInput as he}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as ge,clampReasoning as _e}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as ve}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import{createHash as ye,randomUUID as be}from"node:crypto";import I from"node:fs";import{Agent as xe}from"@mariozechner/pi-agent-core";import Se from"node:os";import{spawn as Ce}from"node:child_process";import we from"ajv";import{createJiti as Te}from"jiti";const Ee=2e4,De=15e4,Oe=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`HEARTBEAT.md`,`MEMORY.md`,`BOOTSTRAP.md`];function L(e){return N.join(e,`.aimax`)}async function ke(e){let t=L(e),n=[];for(let e of Oe){let r=N.join(t,e);try{let t=await M.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await M.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function Ae(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
2
2
  `),s].join(`
3
3
  `),truncated:!0,originalLength:r.length}}function je(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Me(e,t){let n=t?.maxChars??Ee,r=Math.max(1,t?.totalMaxChars??Math.max(n,De)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=je(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=Ae(a.content??``,a.name,e),l=je(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}function Ne(e){return N.join(e,`.aimax`,`skills`)}function Pe(e){let t=e.split(`
4
4
  `).map(e=>e.trim());for(let e of t)if(e.toLowerCase().startsWith(`description:`)){let t=e.slice(12).trim();if(t)return t.slice(0,500)}for(let e of t)if(e&&!e.startsWith(`#`)&&!e.startsWith(`---`))return e.slice(0,500);return``}async function Fe(e){return Le([Ne(e)])}async function Ie(e,t){return Le([Ne(e),...t])}async function Le(e){let t=[],n=new Set;for(let r of e){let e;try{e=await M.readdir(r,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let i=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of i.sort()){if(t.length>=50)break;if(n.has(e))continue;let i=N.join(r,e,`SKILL.md`),a;try{a=await M.readFile(i,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let o=Pe(a);t.push({name:e,description:o,location:i}),n.add(e)}}return t}function Re(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
@@ -16,45 +16,45 @@ import{_ as e,a as t,c as n,d as r,f as i,g as a,h as o,i as s,l as c,m as l,n a
16
16
  `);async function tn(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=rn(t,r,i),l,u=Je({baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:n.model,hooks:o,hookCtx:s});for(let e=1;e<=3;e++)try{let e=(await u.chat({system:en,user:c,temperature:0,maxTokens:2048,signal:a})).text.trim();if(!e)throw Error(`LLM summarisation returned empty content`);return e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;l=t,e<3&&await nn(500*e)}throw l}function nn(e){return new Promise(t=>setTimeout(t,e))}function rn(e,t,n){let r=[];n?.trim()&&r.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(r.push(`[Prior summary]\n${t.trim()}\n`),r.push(`[Conversation to incorporate]`)):r.push(`[Conversation to summarise]`);for(let t of e)if(t.role===`user`)r.push(`User: ${t.content}`);else if(t.role===`assistant`){let e=t.toolCalls&&t.toolCalls.length>0?` [called tools: ${t.toolCalls.map(e=>e.name).join(`, `)}]`:``;r.push(`Assistant:${e} ${t.content}`.trimEnd())}else if(t.role===`tool_result`){let e=t.isError?`error`:`ok`,n=t.content.length>2e3?`${t.content.slice(0,2e3)}… [truncated]`:t.content;r.push(`Tool(${t.toolName})[${e}]: ${n}`)}return r.join(`
17
17
  `)}function an(e){let{entries:t,contextWindowTokens:n,thresholdRatio:r=.6}=e;if(t.length===0)return!1;let i=Math.floor(n*r);return H(t)>i}function on(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=$t(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function sn(e){let t=new Set;for(let n of e)if(n.role===`assistant`)for(let e of n.toolCalls??[])t.add(e.id);let n=e.filter(e=>e.role!==`tool_result`||t.has(e.toolCallId));return n.length===e.length?e:n}async function cn(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=ln(t),l=c>=0?t[c].content:void 0,u=sn(c>=0?t.slice(c+1):t);if(u.length===0)return{status:`skipped`,reason:`No history to compact.`,estimatedTokens:0};let{toKeep:d,toSummarise:f}=on(u,n);return f.length===0&&u.length>1&&(f=u.slice(0,u.length-1),d=u.slice(u.length-1)),f.length===0?{status:`skipped`,reason:`Not enough history to compact.`,estimatedTokens:H(u)}:{status:`compacted`,entry:{role:`compaction`,content:await tn({entries:f,llm:r,previousSummary:l,instructions:i,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:H(d)}}function ln(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const un=[`✨ 新会话已开启,我们可以重新开始啦~`,``,` 我是爱码Max,你的AI研发助手。你可以这样和我聊:`,` 💻 “用React写一个登录组件”`,` ✏️ “帮我写一个用户中心的PRD”`,` 🧪 “为这个接口设计测试用例”`,` 💬 “解释下什么是微服务”`,``,` 直接说出你的需求就行~`].join(`
18
18
  `);function dn(){return{kind:`reply`,text:un}}function fn(){return{kind:`reply`,text:`✅ Session reset.`}}function pn(e){let t=gn(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?_n(r):null,a=n??i?.text,o=a?Wt(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?vn(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:yn(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function mn(e,t){if(e.resetShortCircuit)return{kind:`reset_reply`,action:e.resetCommand?.action??`new`,transcriptMessage:e.transcriptMessage,initialUserEntryPersisted:!0};if(!e.slashCommandSource)return{kind:`run`,effectivePrompt:e.promptInput,transcriptMessage:e.transcriptMessage};let n=Qt({message:e.messageForRun??``,skills:t});if(n.kind===`reply`)return{kind:`reply`,replyText:n.text,transcriptMessage:e.transcriptMessage};if(n.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:n.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(n.kind===`rewrite`){let t=e.inputMode===`text`?n.message:vn(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:yn(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function hn(e){let t=mn(e.invocation,e.skills);if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await Ft({replyText:(t.action===`reset`?fn():dn()).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await Ft({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};let n=await cn({entries:e.runParams.channel===`CRON`?[]:await l(e.runParams.dataDir,e.sessionId),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await Ft({replyText:n.status===`compacted`?`⚙️ Compacted (kept ${n.keptCount}, dropped ${n.droppedCount}).`:`⚙️ Compaction skipped: ${n.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function gn(e){return typeof e.message==`string`}function _n(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n.role!==`user`)continue;if(typeof n.content==`string`)return{index:t,text:n.content};if(!Array.isArray(n.content)||n.content.length===0)return null;let r=n.content[0];return r?.type===`text`&&typeof r.text==`string`?{index:t,text:r.text}:null}return null}function vn(e,t){let n=_n(e);return n?e.map((e,r)=>{if(r!==n.index)return e;let i=e;return typeof i.content==`string`?{...e,content:t}:Array.isArray(i.content)&&i.content.length>0?{...e,content:i.content.map((e,n)=>{if(n!==0)return e;let r=e;return r?.type===`text`&&typeof r.text==`string`?{...r,text:t}:e})}:e}):e}function yn(e){return typeof e==`string`?e:JSON.stringify(e)}function bn(e,t){if(!t||t<=0||e.length===0)return e;let n=0,r=e.length;for(let i=e.length-1;i>=0;i--)if(e[i].role===`user`){if(n++,n>t)return e.slice(r);r=i}return e}const xn={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};async function Sn(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,thresholdRatio:s,signal:c}=e,l,u,d=Cn(t);d>=0?(l=t[d].content,u=t.slice(d+1)):u=t;let f=t.length,p=sn(bn(u,a));if(o&&an({entries:p,contextWindowTokens:r,thresholdRatio:s})){let{toKeep:t,toSummarise:a}=on(p,r);if(a.length>0){let r=await tn({entries:a,llm:i,previousSummary:l,signal:c,hooks:e.hooks,hookCtx:e.hookCtx}),o=sn(t),s={role:`compaction`,content:r,keptCount:o.length,droppedCount:a.length,timestamp:new Date().toISOString()};return{messages:wn(o,n),priorSummary:r,compactionEntry:s,stats:{originalCount:f,keptCount:o.length,estimatedTokens:H(o),compacted:!0}}}}return{messages:wn(p,n),priorSummary:l,compactionEntry:void 0,stats:{originalCount:f,keptCount:p.length,estimatedTokens:H(p),compacted:!1}}}function Cn(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}function wn(e,t){return e.map(e=>Tn(e,t))}function Tn(e,t){let n=new Date(e.timestamp).getTime();if(En(e))return{role:`user`,content:e.content,timestamp:n};if(Dn(e)){let r=[];e.content&&r.push({type:`text`,text:e.content});for(let t of e.toolCalls??[])r.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});return{role:`assistant`,content:r,api:t.api,provider:`openai`,model:t.model,usage:xn,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:r.content}],isError:r.isError,timestamp:n}}function En(e){return e.role===`user`}function Dn(e){return e.role===`assistant`}const On=P.Object({command:P.String({description:`Shell command to execute`}),workdir:P.Optional(P.String({description:`Working directory (relative to workspace root)`})),env:P.Optional(P.Record(P.String(),P.String())),timeout:P.Optional(P.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:P.Optional(P.Number({description:`Wait this many milliseconds before returning running state`})),background:P.Optional(P.Boolean({description:`Return immediately with running session`}))});function kn(e,t,n){return Math.max(t,Math.min(n,e))}function An(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function jn(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:kn(Math.floor(e),0,12e4)}function Mn(e,t){if(!t?.trim())return e;let n=N.isAbsolute(t)?N.normalize(t):N.normalize(N.join(e,t));if(!n.startsWith(e+N.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Nn(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 Pn(e){let t=e.outputTail.trim();return`${t.length>0?t:`(no output)`}${e.exitCode===void 0?``:`\nExit code: ${e.exitCode===null?`null`:e.exitCode}`}`}function Fn(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands with optional background continuation. Use process tool to poll logs and status.`,parameters:On,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=Mn(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=An(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,jn(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}return l.status===`running`?{content:[{type:`text`,text:Nn(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}}:{content:[{type:`text`,text:Pn(l)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal}}}}}const In=P.Object({action:P.String({description:`Process action: list | poll | log | kill`}),sessionId:P.Optional(P.String({description:`Session id for non-list actions`})),offset:P.Optional(P.Number({description:`Log line offset (0-based)`})),limit:P.Optional(P.Number({description:`Maximum lines to return`})),timeout:P.Optional(P.Number({description:`Poll wait time in milliseconds`}))});function Ln(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function U(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Rn(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:In,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(`
19
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return U(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Ln(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`}}:U(`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}}:U(`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}}:U(`No session found for ${i}`)}return U(`Unsupported action: ${n.action}`)}}}const zn=2e5;function Bn(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Vn(e,t){t.length!==0&&(e.output+=t.toString(`utf-8`),e.output.length>zn&&(e.output=e.output.slice(-zn),e.outputTruncated=!0))}function W(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:Bn(e.output),outputTruncated:e.outputTruncated}}function G(e,t){return t?e.scopeKey===t:!0}function Hn(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Un(e){return e?e.split(/\r?\n/):[]}function Wn(e){let t=Un(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Hn(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(`
20
- `);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 Gn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Kn(){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),Gn(e))};return{start(t){let n=Ce(`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:be(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>Vn(o,e)),n.stderr.on(`data`,e=>Vn(o,e));let s=Hn(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Vn(o,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`),Vn(o,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`)})}),W(o)},get(e,t){let n=r(e);return!n||!G(n,t)?null:W(n)},list(n){return[...e.values(),...t.values()].filter(e=>G(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>W(e))},async wait(e,t,n){let i=r(e);if(!i||!G(i,t))return null;if(i.status!==`running`)return W(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||!G(a,t)?null:W(a)},readLog(e){let t=r(e.sessionId);return!t||!G(t,e.scopeKey)?null:Wn({record:t,offset:e.offset,limit:e.limit})},async terminate(e,t){let n=r(e);if(!n||!G(n,t))return null;if(n.status!==`running`)return W(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?W(i):null}}}function qn(e){return Fn({workspaceDir:e,registry:Kn(),scopeKey:e})}const Jn=5*1024*1024,Yn=2e3;function Xn(e,t){return N.isAbsolute(e)?N.normalize(e):N.normalize(N.join(t,e))}const Zn=P.Object({path:P.String({description:`File path (relative to workspace or absolute)`}),offset:P.Optional(P.Number({description:`Line offset (1-based, default: 1)`})),limit:P.Optional(P.Number({description:`Maximum lines to read (default: 2000)`}))});function Qn(e){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Zn,async execute(t,n){let r;try{r=Xn(n.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let i;try{i=await M.readFile(r)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${n.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}if(i.length>Jn){let e=i.slice(0,Jn).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Jn} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let a=i.toString(`utf-8`).split(`
21
- `),o=Math.max(1,n.offset??1),s=Math.min(Yn,n.limit??Yn),c=a.slice(o-1,o-1+s),l=c.length<a.length-(o-1);return{content:[{type:`text`,text:c.map((e,t)=>`${(o+t).toString().padStart(4)} ${e}`).join(`
19
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return U(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Ln(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`}}:U(`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}}:U(`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}}:U(`No session found for ${i}`)}return U(`Unsupported action: ${n.action}`)}}}const zn=2e5;function Bn(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function W(e,t){t.length!==0&&(e.output+=t.toString(`utf-8`),e.output.length>zn&&(e.output=e.output.slice(-zn),e.outputTruncated=!0))}function G(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:Bn(e.output),outputTruncated:e.outputTruncated}}function K(e,t){return t?e.scopeKey===t:!0}function Vn(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Hn(e){return e?e.split(/\r?\n/):[]}function Un(e){let t=Hn(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Vn(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(`
20
+ `);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 Wn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Gn(){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),Wn(e))};return{start(t){let n=Ce(`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:be(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>W(o,e)),n.stderr.on(`data`,e=>W(o,e));let s=Vn(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,W(o,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`),W(o,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`)})}),G(o)},get(e,t){let n=r(e);return!n||!K(n,t)?null:G(n)},list(n){return[...e.values(),...t.values()].filter(e=>K(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>G(e))},async wait(e,t,n){let i=r(e);if(!i||!K(i,t))return null;if(i.status!==`running`)return G(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||!K(a,t)?null:G(a)},readLog(e){let t=r(e.sessionId);return!t||!K(t,e.scopeKey)?null:Un({record:t,offset:e.offset,limit:e.limit})},async terminate(e,t){let n=r(e);if(!n||!K(n,t))return null;if(n.status!==`running`)return G(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?G(i):null}}}function Kn(e){return Fn({workspaceDir:e,registry:Gn(),scopeKey:e})}const qn=5*1024*1024,Jn=2e3;function q(e,t){return N.isAbsolute(e)?N.normalize(e):N.normalize(N.join(t,e))}const Yn=P.Object({path:P.String({description:`File path (relative to workspace or absolute)`}),offset:P.Optional(P.Number({description:`Line offset (1-based, default: 1)`})),limit:P.Optional(P.Number({description:`Maximum lines to read (default: 2000)`}))});function Xn(e){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Yn,async execute(t,n){let r;try{r=q(n.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let i;try{i=await M.readFile(r)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${n.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}if(i.length>qn){let e=i.slice(0,qn).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${qn} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let a=i.toString(`utf-8`).split(`
21
+ `),o=Math.max(1,n.offset??1),s=Math.min(Jn,n.limit??Jn),c=a.slice(o-1,o-1+s),l=c.length<a.length-(o-1);return{content:[{type:`text`,text:c.map((e,t)=>`${(o+t).toString().padStart(4)} ${e}`).join(`
22
22
  `)+(l?`\n[...${a.length-(o-1+c.length)} more lines]`:``)}],details:{content:c.join(`
23
- `),lines:c.length,truncated:l}}}}}const $n=P.Object({path:P.String({description:`File path (relative to workspace or absolute)`}),content:P.String({description:`File content to write`})});function er(e){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:$n,async execute(t,n){let r;try{r=Xn(n.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:n.path}}}try{await M.mkdir(N.dirname(r),{recursive:!0}),await M.writeFile(r,n.content,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:r}}}return{content:[{type:`text`,text:`File written: ${n.path}`}],details:{path:r}}}}}const tr=P.Object({path:P.String({description:`File path (relative to workspace or absolute)`}),old_string:P.String({description:`Exact text to replace`}),new_string:P.String({description:`Replacement text`})});function nr(e){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:tr,async execute(t,n){let r;try{r=Xn(n.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:n.path,occurrences:0}}}let i;try{i=await M.readFile(r,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${n.path}`:String(e)}`}],details:{path:r,occurrences:0}}}if(!i.includes(n.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${n.path}`}],details:{path:r,occurrences:0}};let a=i.replace(n.old_string,n.new_string);return await M.writeFile(r,a,`utf-8`),{content:[{type:`text`,text:`File edited: ${n.path}`}],details:{path:r,occurrences:1}}}}}const rr=P.Object({path:P.Optional(P.String({description:`Directory path (default: workspace root)`}))});function ir(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=Xn(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await M.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(`
24
- `)||`(empty directory)`}],details:{entries:a}}}}}const ar=P.Object({input:P.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function or(e,t){let n=N.isAbsolute(e)?N.normalize(e):N.normalize(N.join(t,e));if(!n.startsWith(t+N.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function sr(e,t){let n=N.relative(t,e);return!n||n===``?N.basename(e):n.startsWith(`..`)||N.isAbsolute(n)?e:n}async function cr(e){await M.mkdir(N.dirname(e),{recursive:!0})}function lr(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(`
25
- `)}function ur(e){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:ar,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=fr(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=or(t.path,e);await cr(n),await M.writeFile(n,t.contents,`utf-8`),dr(i,a,`added`,sr(n,e));continue}if(t.kind===`delete`){let n=or(t.path,e);await M.rm(n,{force:!0,recursive:!1}),dr(i,a,`deleted`,sr(n,e));continue}let n=or(t.path,e),r=await gr(n,t.chunks);if(t.movePath){let o=or(t.movePath,e);await cr(o),await M.writeFile(o,r,`utf-8`),await M.rm(n,{force:!0,recursive:!1}),dr(i,a,`modified`,sr(o,e))}else await M.writeFile(n,r,`utf-8`),dr(i,a,`modified`,sr(n,e))}return{content:[{type:`text`,text:lr(i)}],details:{summary:i}}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function dr(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function fr(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);pr(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=mr(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function pr(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 mr(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}=hr(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 hr(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 gr(e,t){let n=(await M.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
26
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=vr(n,_r(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
27
- `)}function _r(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=yr(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=yr(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=yr(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
28
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function vr(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 yr(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(br(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(br(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(br(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(br(e,t,n,e=>xr(e.trim())))return n;return null}function br(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 xr(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}function Sr(e){return N.join(e,`.aimax`)}function Cr(e){return N.join(Sr(e),`MEMORY.md`)}async function wr(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function K(e,t){let n=Sr(e),r=v({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:u({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function Tr(e){return s(Sr(e))}async function Er(e){try{return await M.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Dr(e){return Er(Cr(e))}async function Or(e,t,n){return await K(e,n).search(t)}async function kr(e,t,n,r,i){try{return await K(e,i).getLines(t,n,r)}catch{return null}}async function Ar(e,t,n){let r=K(e,n);await r.append(t),await wr(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function jr(e,t,n,r){let i=K(e,r);await i.updateFile(t,n),await wr(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function Mr(e,t,n){let r=K(e,n);await r.deleteFile(t),await wr(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const Nr=P.Object({query:P.String({description:`Search query (case-insensitive substring match)`})});function Pr(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memory files for relevant information`,parameters:Nr,async execute(n,r){let i=(await Or(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(`
29
- `)}],details:{matches:i}}}}}const Fr=P.Object({file:P.String({description:`Memory file path`}),start_line:P.Number({description:`Start line number (1-based)`}),end_line:P.Number({description:`End line number (1-based)`})});function Ir(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read specific lines from a memory file`,parameters:Fr,async execute(n,r){let i=await kr(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(`
30
- `)||`(empty)`}],details:{lines:i}}}}}const Lr=P.Object({content:P.String({description:`Content to append to MEMORY.md`})});function Rr(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append new information to the MEMORY.md file`,parameters:Lr,async execute(n,r){try{return await Ar(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 zr=P.Object({task:P.String({description:`The task description for the subagent to execute`}),label:P.Optional(P.String({description:`Optional short label to identify this subagent`}))});function Br(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 Vr(e,t,n,r,i,a,o,s,l){return{name:`sessions_spawn`,label:`Spawn Subagent`,description:`Delegate a task to a subagent that runs independently. Returns immediately with status=accepted; the subagent result will be delivered back automatically as a follow-up message — do not poll or sleep.`,parameters:zr,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=be(),g=new AbortController,_;try{_=await c(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=l({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 Hr=P.Object({action:P.Union([`list`,`kill`].map(e=>P.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:P.Optional(P.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Ur(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 Wr(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 Gr(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:Hr,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} (${Ur(e.runtimeMs)})`)).join(`
31
- `)};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=Wr(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 Kr=P.Object({image:P.String({description:`Image path or URL`}),prompt:P.Optional(P.String({description:`Prompt for image analysis`})),model:P.Optional(P.String({description:`Optional model override`})),maxBytesMb:P.Optional(P.Number({description:`Optional size cap in MB`}))});function qr(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Kr,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 Jr(e,t){let n=N.join(e,`workspace`),r=t?.memoryOptions,i=Kn(),a=[Fn({workspaceDir:n,registry:i,scopeKey:n}),Rn({registry:i,scopeKey:n}),Qn(n),er(n),nr(n),ir(n),ur(n),Pr(e,r),Ir(e,r),Rr(e,r)];return t&&a.push(Vr(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Gr(t.registry,t.parentSessionId)),a}const Yr={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`},Xr=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`memory_search`,`memory_get`,`memory_append`,`sessions_spawn`,`subagents`];function Zr(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:[...Xr.filter(e=>t.has(e)),...n.filter(e=>!Xr.includes(e)).sort()],displayName:t}}function Qr(e){let{ordered:t,displayName:n}=Zr(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)??Yr[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
23
+ `),lines:c.length,truncated:l}}}}}const Zn=P.Object({path:P.String({description:`File path (relative to workspace or absolute)`}),content:P.String({description:`File content to write`})});function Qn(e){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Zn,async execute(t,n){let r;try{r=q(n.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:n.path}}}try{await M.mkdir(N.dirname(r),{recursive:!0}),await M.writeFile(r,n.content,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:r}}}return{content:[{type:`text`,text:`File written: ${n.path}`}],details:{path:r}}}}}const $n=P.Object({path:P.String({description:`File path (relative to workspace or absolute)`}),old_string:P.String({description:`Exact text to replace`}),new_string:P.String({description:`Replacement text`})});function er(e){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:$n,async execute(t,n){let r;try{r=q(n.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:n.path,occurrences:0}}}let i;try{i=await M.readFile(r,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${n.path}`:String(e)}`}],details:{path:r,occurrences:0}}}if(!i.includes(n.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${n.path}`}],details:{path:r,occurrences:0}};let a=i.replace(n.old_string,n.new_string);return await M.writeFile(r,a,`utf-8`),{content:[{type:`text`,text:`File edited: ${n.path}`}],details:{path:r,occurrences:1}}}}}const tr=P.Object({path:P.Optional(P.String({description:`Directory path (default: workspace root)`}))});function nr(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:tr,async execute(t,n){let r=n.path??`.`,i;try{i=q(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await M.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(`
24
+ `)||`(empty directory)`}],details:{entries:a}}}}}const rr=P.Object({input:P.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function ir(e,t){let n=N.isAbsolute(e)?N.normalize(e):N.normalize(N.join(t,e));if(!n.startsWith(t+N.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function ar(e,t){let n=N.relative(t,e);return!n||n===``?N.basename(e):n.startsWith(`..`)||N.isAbsolute(n)?e:n}async function or(e){await M.mkdir(N.dirname(e),{recursive:!0})}function sr(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(`
25
+ `)}function cr(e){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:rr,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=ur(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=ir(t.path,e);await or(n),await M.writeFile(n,t.contents,`utf-8`),lr(i,a,`added`,ar(n,e));continue}if(t.kind===`delete`){let n=ir(t.path,e);await M.rm(n,{force:!0,recursive:!1}),lr(i,a,`deleted`,ar(n,e));continue}let n=ir(t.path,e),r=await mr(n,t.chunks);if(t.movePath){let o=ir(t.movePath,e);await or(o),await M.writeFile(o,r,`utf-8`),await M.rm(n,{force:!0,recursive:!1}),lr(i,a,`modified`,ar(o,e))}else await M.writeFile(n,r,`utf-8`),lr(i,a,`modified`,ar(n,e))}return{content:[{type:`text`,text:sr(i)}],details:{summary:i}}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function lr(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function ur(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);dr(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=fr(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function dr(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 fr(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}=pr(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 pr(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 mr(e,t){let n=(await M.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
26
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=gr(n,hr(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
27
+ `)}function hr(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=_r(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=_r(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=_r(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
28
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function gr(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 _r(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(vr(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(vr(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(vr(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(vr(e,t,n,e=>yr(e.trim())))return n;return null}function vr(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 yr(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}function br(e){return N.join(e,`.aimax`)}function xr(e){return N.join(br(e),`MEMORY.md`)}async function Sr(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function J(e,t){let n=br(e),r=v({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:u({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function Cr(e){return s(br(e))}async function wr(e){try{return await M.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Tr(e){return wr(xr(e))}async function Er(e,t,n){return await J(e,n).search(t)}async function Dr(e,t,n,r,i){try{return await J(e,i).getLines(t,n,r)}catch{return null}}async function Or(e,t,n){let r=J(e,n);await r.append(t),await Sr(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function kr(e,t,n,r){let i=J(e,r);await i.updateFile(t,n),await Sr(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function Ar(e,t,n){let r=J(e,n);await r.deleteFile(t),await Sr(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const jr=P.Object({query:P.String({description:`Search query (case-insensitive substring match)`})});function Mr(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search memory files for relevant information`,parameters:jr,async execute(n,r){let i=(await Er(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(`
29
+ `)}],details:{matches:i}}}}}const Nr=P.Object({file:P.String({description:`Memory file path`}),start_line:P.Number({description:`Start line number (1-based)`}),end_line:P.Number({description:`End line number (1-based)`})});function Pr(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read specific lines from a memory file`,parameters:Nr,async execute(n,r){let i=await Dr(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(`
30
+ `)||`(empty)`}],details:{lines:i}}}}}const Fr=P.Object({content:P.String({description:`Content to append to MEMORY.md`})});function Ir(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append new information to the MEMORY.md file`,parameters:Fr,async execute(n,r){try{return await Or(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 Lr=P.Object({task:P.String({description:`The task description for the subagent to execute`}),label:P.Optional(P.String({description:`Optional short label to identify this subagent`}))});function Rr(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 zr(e,t,n,r,i,a,o,s,l){return{name:`sessions_spawn`,label:`Spawn Subagent`,description:`Delegate a task to a subagent that runs independently. Returns immediately with status=accepted; the subagent result will be delivered back automatically as a follow-up message — do not poll or sleep.`,parameters:Lr,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=be(),g=new AbortController,_;try{_=await c(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=l({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 Br=P.Object({action:P.Union([`list`,`kill`].map(e=>P.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:P.Optional(P.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Vr(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 Hr(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 Ur(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:Br,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} (${Vr(e.runtimeMs)})`)).join(`
31
+ `)};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=Hr(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 Wr=P.Object({image:P.String({description:`Image path or URL`}),prompt:P.Optional(P.String({description:`Prompt for image analysis`})),model:P.Optional(P.String({description:`Optional model override`})),maxBytesMb:P.Optional(P.Number({description:`Optional size cap in MB`}))});function Gr(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Wr,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 Kr(e,t){let n=N.join(e,`workspace`),r=t?.memoryOptions,i=Gn(),a=[Fn({workspaceDir:n,registry:i,scopeKey:n}),Rn({registry:i,scopeKey:n}),Xn(n),Qn(n),er(n),nr(n),cr(n),Mr(e,r),Pr(e,r),Ir(e,r)];return t&&a.push(zr(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Ur(t.registry,t.parentSessionId)),a}const qr={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`},Jr=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`memory_search`,`memory_get`,`memory_append`,`sessions_spawn`,`subagents`];function Yr(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:[...Jr.filter(e=>t.has(e)),...n.filter(e=>!Jr.includes(e)).sort()],displayName:t}}function Xr(e){let{ordered:t,displayName:n}=Yr(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)??qr[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
32
32
  `),``].join(`
33
- `)}function $r(){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(`
34
- `)}function ei(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(`
35
- `)}function ti(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(`
33
+ `)}function Zr(){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(`
34
+ `)}function Qr(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(`
35
+ `)}function $r(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(`
36
36
  `)).join(`
37
37
  `)}\n</available_skills>`,``].join(`
38
- `)}function ni(){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(`
39
- `)}function ri(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(`
40
- `)}function ii(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(`
41
- `)}function ai(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(`
42
- `)}function oi(e){let t=[];return e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate&&t.push(`Current date: ${e.currentDate}`),t.length===0?``:[`## Current Date & Time`,...t,``].join(`
43
- `)}function si(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 for delegated long-running tasks and report concise progress back in this session.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
44
- `)}function ci(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(`
45
- `)}function li(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(`
46
- `)}function ui(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(`
47
- `)}function di(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(`
48
- `)}function fi(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(`
49
- `)}function pi(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(`
50
- `):``}function mi(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:[...Xr],i=e.skills??[],a=e.contextFiles??[];return[`You are a personal assistant running inside AiMax.
51
- `,Qr({toolNames:r,toolSummaries:e.toolSummaries}),ei(n),$r(),ti(i),ni(),ri(e.memoryCitationsMode??`off`),ii({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),ai(e.sandboxInfo),oi({currentDate:e.currentDate,timezone:e.timezone}),si({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),ci({isMinimal:n,docs:e.docs}),ui({isMinimal:n}),di({isMinimal:n,heartbeatPrompt:e.heartbeatPrompt}),li(e.runtimeInfo),fi({contextFiles:a,bootstrapWarnings:e.bootstrapWarnings}),pi(e.priorConversationSummary)].filter(Boolean).join(`
52
- `)}function hi(e,t,n){return e.map(e=>{let r=e,i=e.name??`unknown`;return{...r,async execute(e,a,o,s){let c=Date.now(),l=a??{},u=!1,d,f=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:i,params:l},n);for(let e of f)e&&(e.params&&(l=e.params),e.block&&(u=!0,d=e.blockReason));if(u)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,error:d??`blocked by plugin`,durationMs:Date.now()-c},n),{content:[{type:`text`,text:d??`Tool blocked by plugin`}],isError:!0,details:{}};try{let a=await r.execute(e,l,o,s);return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,result:a,durationMs:Date.now()-c},n),a}catch(r){throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,error:String(r),durationMs:Date.now()-c},n),r}}}})}var gi=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){let r=this.hooks.get(e)??[],i=[];for(let e of r){let r=await e.handler(t,n);i.push(r)}return i}};const q={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function _i(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function vi(e){let t=_i(e?.warningThreshold,q.warningThreshold),n=_i(e?.criticalThreshold,q.criticalThreshold),r=_i(e?.globalCircuitBreakerThreshold,q.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??q.enabled,historySize:_i(e?.historySize,q.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??q.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??q.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??q.detectors.pingPong}}}function J(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function yi(e,t){return`${e}:${Y(t)}`}function bi(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(bi).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${bi(t[e])}`).join(`,`)}}`}function xi(e){try{return bi(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 Y(e){let t=xi(e);return ye(`sha256`).update(t).digest(`hex`)}function Si(e,t){if(e===`command_status`)return!0;if(e!==`process`||!J(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Ci(e){return!J(e)||!Array.isArray(e.content)?``:e.content.filter(e=>J(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
53
- `).trim()}function wi(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:bi(e)}function Ti(e,t,n,r){if(r!==void 0)return`error:${Y(wi(r))}`;if(!J(n))return n===void 0?void 0:Y(n);let i=J(n.details)?n.details:{},a=Ci(n);if(Si(e,t)&&e===`process`&&J(t)){let e=t.action;if(e===`poll`)return Y({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Y({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 Y({details:i,text:a})}function Ei(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 Di(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 Oi(e,t){return[e,t].toSorted().join(`|`)}function ki(e,t,n,r){let i=vi(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=yi(t,n),s=Ei(a,t,o),c=s.count,l=Si(t,n),u=Di(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:${Oi(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 Ai(e,t,n,r,i){let a=vi(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:yi(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function ji(e,t){let n=vi(t.config),r=Ti(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=yi(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 Mi(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 Ni(e){return e&&e.trim()||`tool`}function Pi(e,t,n){if(!e.execute)return e;let r=Ni(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=ki(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Mi(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Ai(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return ji(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw ji(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Fi(e,t,n){return e.map(e=>Pi(e,t,n))}async function Ii(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:u,effectivePromptText:d,pluginTools:f},dependencies:{registry:p,spawnFn:m,createModel:h,abortSignal:g}}=e,_=t.channel===`CRON`,v=_?[]:await l(t.dataDir,n);await r.dispatch(`before_compaction`,{messageCount:v.length},i);let y={model:t.llm.model,api:`openai-completions`},b=_?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1}}:await Sn({entries:v,modelInfo:y,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:g,hooks:r,hookCtx:i});await Li({sessionId:n,historyResult:b,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let x=t.subagentContext?.depth??0,S=[...Jr(t.dataDir,{registry:p,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},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},spawnFn:m}),...f],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 T=t.messaging?.enabled??t.channel!==`CRON`,E=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],D=mi({dataDir:t.dataDir,skills:u,contextFiles:s,toolNames:C,toolSummaries:w,promptMode:x>0?`minimal`:`full`,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:T,channels:E},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:Se.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:b.priorSummary}),ee=await r.dispatch(`before_prompt_build`,{prompt:d},i);for(let e of ee)e&&(e.systemPrompt&&(D=e.systemPrompt),e.prependContext&&(D=`${e.prependContext}\n\n${D}`));await r.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:D},i);let te=Fi(hi(S,r,i),{sessionId:n,config:t.loopDetection},Ue),O=t.llm.model,k=await r.dispatch(`before_model_resolve`,{prompt:d},i);for(let e of k)e&&e.modelOverride&&(O=e.modelOverride);let A=h({...t.llm,model:O},n),j=new xe({initialState:{systemPrompt:D,model:A,tools:te,messages:[]},getApiKey:e=>t.llm.apiKey});return b.messages.length>0&&j.replaceMessages(b.messages),{agent:j,resolvedModelId:O,historyMessages:b.messages,historyResult:b,workspaceDir:a.workspaceDir}}async function Li(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;if(!n.compactionEntry)return;let s=n.stats.originalCount-n.stats.keptCount;await r.appendTranscriptEntry(n.compactionEntry),await i.dispatchProgress(t,{type:`compaction`,reason:`Summarised ${s} older entries`}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:s},o)}async function Ri(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u}=e,d=``,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=[],x=async()=>{d&&=(f=d,await o.dispatchProgress(r,{type:`text`,text:d}),``)},S=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Ui(`partial`in t?t.partial:void 0)??Ui(`message`in t?t.message:void 0)??Ui(`message`in e?e.message:void 0),r=Wi(t.delta,n,m);d+=r,m=n??m+r}if(t.type===`done`){let e=t.message;if(p=Hi(e),!d){let e=Wi(``,p,m);e&&(d+=e,m=p)}e.usage&&(h=e.usage.input,g=e.usage.output),await x()}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=Hi(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??[];b.push({message:t,toolResults:n.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError}))});return}if(e.type===`tool_execution_start`){await x(),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);await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,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`);if(y=Date.now(),await t.prompt(n),!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Gi(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){_=Gi(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{S()}let C=b.length>0?b[b.length-1]?.message:void 0;return await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:p?[p]:f?[f]:[],lastAssistant:C,usage:{input:h,output:g,total:h+g}},l),{text:(b.length>0?Hi(b[b.length-1].message):``)||p||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}async function zi(e,t){if(t.turnRecords.length>0){for(let n of t.turnRecords){let t=Bi(n.message);t&&await e(t);for(let t of n.toolResults)await e(Vi(t))}return}t.text&&await e({role:`assistant`,content:t.text,timestamp:new Date().toISOString()})}function Bi(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 Vi(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,timestamp:new Date().toISOString()}}function Hi(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Ui(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 Wi(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Gi(e){let t=Ki(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 Ki(e){if(e instanceof R)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 qi(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=Ji(e);await u({role:`user`,content:g,timestamp:new Date().toISOString()});let _=await Ri({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,skillUsageTracker:o,hooks:s,hookCtx:c,abortSignal:l});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),await zi(u,_)}return{text:f,inputTokens:p,outputTokens:m,error:h}}function Ji(e){if(e.length===1){let t=e[0];return Br({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Br({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
38
+ `)}function ei(){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(`
39
+ `)}function ti(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(`
40
+ `)}function ni(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(`
41
+ `)}function ri(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(`
42
+ `)}function ii(e){let t=[];return e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate&&t.push(`Current date: ${e.currentDate}`),t.length===0?``:[`## Current Date & Time`,...t,``].join(`
43
+ `)}function ai(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 for delegated long-running tasks and report concise progress back in this session.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
44
+ `)}function oi(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(`
45
+ `)}function si(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(`
46
+ `)}function ci(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(`
47
+ `)}function li(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(`
48
+ `)}function ui(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(`
49
+ `)}function di(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(`
50
+ `):``}function fi(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:[...Jr],i=e.skills??[],a=e.contextFiles??[];return[`You are a personal assistant running inside AiMax.
51
+ `,Xr({toolNames:r,toolSummaries:e.toolSummaries}),Qr(n),Zr(),$r(i),ei(),ti(e.memoryCitationsMode??`off`),ni({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),ri(e.sandboxInfo),ii({currentDate:e.currentDate,timezone:e.timezone}),ai({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),oi({isMinimal:n,docs:e.docs}),ci({isMinimal:n}),li({isMinimal:n,heartbeatPrompt:e.heartbeatPrompt}),si(e.runtimeInfo),ui({contextFiles:a,bootstrapWarnings:e.bootstrapWarnings}),di(e.priorConversationSummary)].filter(Boolean).join(`
52
+ `)}function pi(e,t,n){return e.map(e=>{let r=e,i=e.name??`unknown`;return{...r,async execute(e,a,o,s){let c=Date.now(),l=a??{},u=!1,d,f=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:i,params:l},n);for(let e of f)e&&(e.params&&(l=e.params),e.block&&(u=!0,d=e.blockReason));if(u)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,error:d??`blocked by plugin`,durationMs:Date.now()-c},n),{content:[{type:`text`,text:d??`Tool blocked by plugin`}],isError:!0,details:{}};try{let a=await r.execute(e,l,o,s);return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,result:a,durationMs:Date.now()-c},n),a}catch(r){throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:i,params:l,error:String(r),durationMs:Date.now()-c},n),r}}}})}var mi=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){let r=this.hooks.get(e)??[],i=[];for(let e of r){let r=await e.handler(t,n);i.push(r)}return i}};const Y={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function hi(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function gi(e){let t=hi(e?.warningThreshold,Y.warningThreshold),n=hi(e?.criticalThreshold,Y.criticalThreshold),r=hi(e?.globalCircuitBreakerThreshold,Y.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Y.enabled,historySize:hi(e?.historySize,Y.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Y.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Y.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Y.detectors.pingPong}}}function X(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function _i(e,t){return`${e}:${Z(t)}`}function vi(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(vi).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${vi(t[e])}`).join(`,`)}}`}function yi(e){try{return vi(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 Z(e){let t=yi(e);return ye(`sha256`).update(t).digest(`hex`)}function bi(e,t){if(e===`command_status`)return!0;if(e!==`process`||!X(t))return!1;let n=t.action;return n===`poll`||n===`log`}function xi(e){return!X(e)||!Array.isArray(e.content)?``:e.content.filter(e=>X(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
53
+ `).trim()}function Si(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:vi(e)}function Ci(e,t,n,r){if(r!==void 0)return`error:${Z(Si(r))}`;if(!X(n))return n===void 0?void 0:Z(n);let i=X(n.details)?n.details:{},a=xi(n);if(bi(e,t)&&e===`process`&&X(t)){let e=t.action;if(e===`poll`)return Z({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Z({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 Z({details:i,text:a})}function wi(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 Ti(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 Ei(e,t){return[e,t].toSorted().join(`|`)}function Di(e,t,n,r){let i=gi(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=_i(t,n),s=wi(a,t,o),c=s.count,l=bi(t,n),u=Ti(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:${Ei(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 Oi(e,t,n,r,i){let a=gi(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:_i(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function ki(e,t){let n=gi(t.config),r=Ci(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=_i(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 Ai(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 ji(e){return e&&e.trim()||`tool`}function Mi(e,t,n){if(!e.execute)return e;let r=ji(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Di(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ai(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Oi(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return ki(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw ki(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Ni(e,t,n){return e.map(e=>Mi(e,t,n))}async function Pi(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:u,effectivePromptText:d,pluginTools:f},dependencies:{registry:p,spawnFn:m,createModel:h,abortSignal:g}}=e,_=t.channel===`CRON`,v=_?[]:await l(t.dataDir,n);await r.dispatch(`before_compaction`,{messageCount:v.length},i);let y={model:t.llm.model,api:`openai-completions`},b=_?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1}}:await Sn({entries:v,modelInfo:y,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,signal:g,hooks:r,hookCtx:i});await Fi({sessionId:n,historyResult:b,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let x=t.subagentContext?.depth??0,S=[...Kr(t.dataDir,{registry:p,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},loopDetection:t.loopDetection,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,onMemoryChanged:async()=>{}},spawnFn:m}),...f],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 T=t.messaging?.enabled??t.channel!==`CRON`,E=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],D=fi({dataDir:t.dataDir,skills:u,contextFiles:s,toolNames:C,toolSummaries:w,promptMode:x>0?`minimal`:`full`,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:T,channels:E},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:Se.hostname()},currentDate:new Date().toISOString().split(`T`)[0],priorConversationSummary:b.priorSummary}),O=await r.dispatch(`before_prompt_build`,{prompt:d},i);for(let e of O)e&&(e.systemPrompt&&(D=e.systemPrompt),e.prependContext&&(D=`${e.prependContext}\n\n${D}`));await r.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:D},i);let k=Ni(pi(S,r,i),{sessionId:n,config:t.loopDetection},Ue),A=t.llm.model,j=await r.dispatch(`before_model_resolve`,{prompt:d},i);for(let e of j)e&&e.modelOverride&&(A=e.modelOverride);let ee=h({...t.llm,model:A},n),te=new xe({initialState:{systemPrompt:D,model:ee,tools:k,messages:[]},getApiKey:e=>t.llm.apiKey});return b.messages.length>0&&te.replaceMessages(b.messages),{agent:te,resolvedModelId:A,historyMessages:b.messages,historyResult:b,workspaceDir:a.workspaceDir}}async function Fi(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;if(!n.compactionEntry)return;let s=n.stats.originalCount-n.stats.keptCount;await r.appendTranscriptEntry(n.compactionEntry),await i.dispatchProgress(t,{type:`compaction`,reason:`Summarised ${s} older entries`}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:s},o)}async function Ii(e){let{agent:t,message:n,sessionId:r,modelId:i,historyMessages:a,eventDispatcher:o,skillUsageTracker:s,hooks:c,hookCtx:l,abortSignal:u}=e,d=``,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=[],x=async()=>{d&&=(f=d,await o.dispatchProgress(r,{type:`text`,text:d}),``)},S=t.subscribe(async e=>{if(e.type===`message_update`){let t=e.assistantMessageEvent;if(t.type===`text_delta`&&typeof t.delta==`string`){let n=Vi(`partial`in t?t.partial:void 0)??Vi(`message`in t?t.message:void 0)??Vi(`message`in e?e.message:void 0),r=Hi(t.delta,n,m);d+=r,m=n??m+r}if(t.type===`done`){let e=t.message;if(p=Bi(e),!d){let e=Hi(``,p,m);e&&(d+=e,m=p)}e.usage&&(h=e.usage.input,g=e.usage.output),await x()}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=Bi(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??[];b.push({message:t,toolResults:n.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError}))});return}if(e.type===`tool_execution_start`){await x(),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);await o.dispatchProgress(r,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,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`);if(y=Date.now(),await t.prompt(n),!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=Ui(n),await o.dispatchProgress(r,{type:`error`,message:_}))}}catch(e){_=Ui(e),await o.dispatchProgress(r,{type:`error`,message:_})}finally{S()}let C=b.length>0?b[b.length-1]?.message:void 0;return await c.dispatch(`llm_output`,{sessionId:r,model:i,assistantTexts:p?[p]:f?[f]:[],lastAssistant:C,usage:{input:h,output:g,total:h+g}},l),{text:(b.length>0?Bi(b[b.length-1].message):``)||p||f,inputTokens:h,outputTokens:g,error:_,turnRecords:b}}async function Li(e,t){if(t.turnRecords.length>0){for(let n of t.turnRecords){let t=Ri(n.message);t&&await e(t);for(let t of n.toolResults)await e(zi(t))}return}t.text&&await e({role:`assistant`,content:t.text,timestamp:new Date().toISOString()})}function Ri(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 zi(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,timestamp:new Date().toISOString()}}function Bi(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Vi(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 Hi(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Ui(e){let t=Wi(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 Wi(e){if(e instanceof R)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 Gi(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=Ki(e);await u({role:`user`,content:g,timestamp:new Date().toISOString()});let _=await Ii({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,skillUsageTracker:o,hooks:s,hookCtx:c,abortSignal:l});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),await Li(u,_)}return{text:f,inputTokens:p,outputTokens:m,error:h}}function Ki(e){if(e.length===1){let t=e[0];return Rr({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Rr({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
54
54
 
55
55
  ---
56
56
 
57
- `)}`}function Yi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xi(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Zi(e){let t=e.trim();return t===`~`?Se.homedir():t.startsWith(`~/`)||t.startsWith(`~\\`)?N.join(Se.homedir(),t.slice(2)):N.resolve(t)}const Qi=new we({allErrors:!0,strict:!1}),$i=new Map;function ea(e,t){let n=$i.get(t);if(n)return n;let r=Qi.compile(e);return $i.set(t,r),r}function ta(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ea(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function na(e){let t=Xi(e?.allow),n=Xi(e?.deny),r=Xi(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 ra(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=ta({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 ia(e){try{return I.realpathSync(e)}catch{return null}}function aa(e){try{return I.statSync(e)}catch{return null}}function oa(e,t){let n=N.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!N.isAbsolute(n)}function sa(e){return`0o${e.toString(8).padStart(3,`0`)}`}const ca=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),la=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function ua(e){let t=N.join(e,`package.json`);if(I.existsSync(t))try{let e=JSON.parse(I.readFileSync(t,`utf-8`));return Yi(e)?e:void 0}catch{return}}function da(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 fa(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function pa(e){let t=ia(e.source),n=ia(e.rootDir);return!t||!n||oa(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function ma(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=N.resolve(r);if(n.has(t))continue;n.add(t);let i=aa(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 ha(e){return pa({source:e.source,rootDir:e.rootDir})||ma({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:fa(e.ownershipUid)})}function ga(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=${sa(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function _a(e){let t=ha({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:ga(t),source:e.source}),!0):!1}function X(e){return N.basename(e,N.extname(e))}function Z(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 va(e){for(let t of la){let n=N.join(e,t);if(I.existsSync(n))return n}return null}function Q(e){let t;try{t=I.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=N.join(e.rootDir,n.name);if(n.isFile()){if(!ca.has(N.extname(n.name)))continue;let r=N.dirname(t);if(_a({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Z({idHint:X(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=ua(t),i=da(r);if(i.status===`ok`){for(let n of i.entries){let i=N.resolve(t,n);if(!oa(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!I.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!ca.has(N.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(_a({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${X(i)}`:X(i);e.candidates.push(Z({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=va(t);a&&(_a({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Z({idHint:N.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function ya(e){return e?e.map(Zi):[]}function ba(){return N.join(Zi(`~`),`.aimax`,`extensions`)}function xa(e){return N.join(e,`.aimax`,`extensions`)}function Sa(e){return N.join(e,`.aimax`,`extensions`)}function Ca(e={}){let t=[],n=[],r=ya(e.extraPaths);for(let i of r){if(!I.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=aa(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!ca.has(N.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=N.dirname(i);if(_a({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Z({idHint:X(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Q({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}return e.dataDir?Q({rootDir:xa(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Q({rootDir:Sa(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),Q({rootDir:ba(),origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),e.bundledDir&&Q({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function wa(e){let t=e.rejectHardlinks??!0,n=ia(e.rootPath),r=ia(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!oa(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=I.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:I.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ta=`aimax.plugin.json`,Ea=[Ta];function Da(e){for(let t of Ea){let n=N.join(e,t);if(I.existsSync(n))return n}return N.join(e,Ta)}function Oa(e,t=!0){let n=Da(e),r=wa({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(I.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{I.closeSync(r.fd)}if(!Yi(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=Yi(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=Xi(i.skills),f;return Yi(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 ka(e){let t=new Map,n=[];for(let r of e){let e=Oa(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}}var Aa=class{tools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);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)}};let ja=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Ma(){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 Na(e,t,n,r){process.stderr.write(`[${Ma()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Pa(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Na(ja.INFO,e.pluginId,t,n),warn:n=>Na(ja.WARN,e.pluginId,t,n),error:n=>Na(ja.ERROR,e.pluginId,t,n)})}}}function Fa(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 Ia(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 La(e){let n=[...e.registry.diagnostics],r=new Aa,i=new gi,a=[],o=[],s=e.runtime?.llm?Je({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:i,hookCtx:e.runtime.hookCtx}):void 0,c=Ra(e.runtime?.llmAllowlist),l=Te(import.meta.url,{interopDefault:!0,requireCache:!1});for(let u of e.registry.manifests.values()){let d=Fa({config:e.plugins,pluginId:u.id,origin:u.origin,kind:u.manifest.kind}),f=Ia({id:u.id,source:u.source,origin:u.origin,enabled:d,configSchema:!0,skills:u.manifest.skills??[]});if(!d){o.push(f);continue}let p;try{p=l(u.source)}catch(e){f.status=`error`,f.error=String(e),n.push({level:`error`,message:`failed to load plugin ${u.id}: ${String(e)}`,pluginId:u.id,source:u.source}),o.push(f);continue}let m=p&&typeof p==`object`&&`default`in p?p.default:p,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){f.status=`error`,f.error=`plugin module does not export a register function`,n.push({level:`error`,message:`plugin ${u.id} has no register function`,pluginId:u.id,source:u.source}),o.push(f);continue}let g=Pa({pluginId:u.id}),_=e.plugins.entries[u.id]?.config,v={id:u.id,source:u.source,rootDir:u.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!s)throw Error(`LLM client is not configured`);if(!za(u.id,r,c))throw Error(`Plugin ${u.id} is not allowed to use LLM`);return s.chat(e)}},registerTool:(e,t)=>{r.register(u.id,e,t),f.toolCount+=1},registerEmbeddingProvider:e=>{if(u.manifest.kind!==`memory`)throw Error(`Plugin ${u.id} is not allowed to register embedding providers`);t({pluginId:u.id,id:e.id,create:e.create,config:_,rootDir:u.rootDir,source:u.source})},registerMemoryProvider:e=>{if(u.manifest.kind!==`memory`)throw Error(`Plugin ${u.id} is not allowed to register memory providers`);y({pluginId:u.id,id:e.id,create:e.create,config:_,rootDir:u.rootDir,source:u.source})},registerHook:(e,t,n)=>{i.register({pluginId:u.id,hookName:e,handler:t,priority:n?.priority,source:u.source}),f.hookCount+=1},registerSkillDir:e=>{let t=N.isAbsolute(e)?e:N.resolve(u.rootDir,e);a.push(t)}};try{h(v)}catch(e){f.status=`error`,f.error=String(e),n.push({level:`error`,message:`plugin ${u.id} registration failed: ${String(e)}`,pluginId:u.id,source:u.source})}if(u.manifest.skills&&u.manifest.skills.length>0)for(let e of u.manifest.skills){let t=N.isAbsolute(e)?e:N.resolve(u.rootDir,e);a.push(t)}o.push(f)}return{plugins:o,diagnostics:n,tools:r,hooks:i,skills:a}}function Ra(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function za(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Ba(e={}){let t=na(e.config),n=Ca({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=ka(n.candidates),i=ra({config:t,registry:r}),a=La({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 Va(e){let{runParams:t,hookContext:n}=e,r=t.plugins?Ba({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;return{hookRegistry:r?.registry.hooks??new gi,pluginSkillDirs:r?.registry.skills??[],pluginTools:r?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],memoryPluginId:t.memory?.pluginId??r?.normalizedConfig.slots?.memory}}async function Ha(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=N.join(t.dataDir,`workspace`),a=n,o=!a;a?await h(t.dataDir,a):a=await c(t.dataDir,t.channel);let s={sessionId:a,workspaceDir:i,channel:t.channel},l=Va({runParams:t,hookContext:s}),u=l.hookRegistry,d=await kt({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:l.memoryPluginId,eventDispatcher:r,hookRegistry:u});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:u,pluginContext:l,runContext:d,start:e=>Nt({sessionId:a,runParams:t,hookRegistry:u,hookContext:s,eventDispatcher:r,...e})}}function Ua(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 Wa(e,t){Ct();let n=Date.now(),r=new wt(e),i=pn(e),a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await Ha({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;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 ke(e.dataDir),v=[],y=Me(_,{warn:e=>v.push(e)}),b=await Ie(e.dataDir,m.pluginSkillDirs),x=new qe({workspaceDir:d,sessionId:l,skills:b,report:e=>r.dispatchProgress(l,e)}),S=e=>h.appendTranscriptEntry(e),C=await hn({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 w=C.effectivePrompt;a=C.transcriptMessage;let T=await Ii({session:{runParams:e,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:b,effectivePromptText:typeof w==`string`?w:a,pluginTools:m.pluginTools},dependencies:{registry:t,spawnFn:e=>Wa(e,new Ve),createModel:Ua,abortSignal:g.signal}}),E=T.agent,D=T.resolvedModelId,ee=e.timeoutMs??6e5,te=setTimeout(()=>{g.abort(),E.abort()},ee);g.signal.addEventListener(`abort`,()=>E.abort());let O=0,k=0,A=``,j;try{o=await h.persistInitialUserEntry(a)||o;let e=await Ri({agent:E,message:w,sessionId:l,modelId:D,historyMessages:T.historyMessages,eventDispatcher:r,skillUsageTracker:x,hooks:p,hookCtx:f,abortSignal:g.signal});A=e.text,O+=e.inputTokens,k+=e.outputTokens,e.error&&(j=e.error),await zi(S,e);let n=await qi({agent:E,registry:t,sessionId:l,resolvedModelId:D,eventDispatcher:r,skillUsageTracker:x,hookRegistry:p,hookContext:f,abortSignal:g.signal,appendEntry:S});n.text&&(A=n.text),O+=n.inputTokens,k+=n.outputTokens,n.error&&!j&&(j=n.error)}finally{clearTimeout(te),We(l),h.stop()}let ne={input:O,output:k,total:O+k};return It({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:A,usage:ne,error:j})}async function Ga(e,t){return Wa(e,t??new Ve)}const Ka={"AGENTS.md":`---
57
+ `)}`}function qi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ji(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Yi(e){let t=e.trim();return t===`~`?Se.homedir():t.startsWith(`~/`)||t.startsWith(`~\\`)?N.join(Se.homedir(),t.slice(2)):N.resolve(t)}const Xi=new we({allErrors:!0,strict:!1}),Zi=new Map;function Qi(e,t){let n=Zi.get(t);if(n)return n;let r=Xi.compile(e);return Zi.set(t,r),r}function $i(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Qi(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function ea(e){let t=Ji(e?.allow),n=Ji(e?.deny),r=Ji(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 ta(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=$i({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 na(e){try{return I.realpathSync(e)}catch{return null}}function ra(e){try{return I.statSync(e)}catch{return null}}function ia(e,t){let n=N.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!N.isAbsolute(n)}function aa(e){return`0o${e.toString(8).padStart(3,`0`)}`}const oa=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),sa=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function ca(e){let t=N.join(e,`package.json`);if(I.existsSync(t))try{let e=JSON.parse(I.readFileSync(t,`utf-8`));return qi(e)?e:void 0}catch{return}}function la(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 ua(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function da(e){let t=na(e.source),n=na(e.rootDir);return!t||!n||ia(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function fa(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=N.resolve(r);if(n.has(t))continue;n.add(t);let i=ra(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 pa(e){return da({source:e.source,rootDir:e.rootDir})||fa({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:ua(e.ownershipUid)})}function ma(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=${aa(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function ha(e){let t=pa({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:ma(t),source:e.source}),!0):!1}function ga(e){return N.basename(e,N.extname(e))}function _a(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 va(e){for(let t of sa){let n=N.join(e,t);if(I.existsSync(n))return n}return null}function Q(e){let t;try{t=I.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=N.join(e.rootDir,n.name);if(n.isFile()){if(!oa.has(N.extname(n.name)))continue;let r=N.dirname(t);if(ha({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(_a({idHint:ga(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=ca(t),i=la(r);if(i.status===`ok`){for(let n of i.entries){let i=N.resolve(t,n);if(!ia(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!I.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!oa.has(N.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(ha({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${ga(i)}`:ga(i);e.candidates.push(_a({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=va(t);a&&(ha({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(_a({idHint:N.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function ya(e){return e?e.map(Yi):[]}function ba(){return N.join(Yi(`~`),`.aimax`,`extensions`)}function xa(e){return N.join(e,`.aimax`,`extensions`)}function Sa(e){return N.join(e,`.aimax`,`extensions`)}function Ca(e={}){let t=[],n=[],r=ya(e.extraPaths);for(let i of r){if(!I.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=ra(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!oa.has(N.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=N.dirname(i);if(ha({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(_a({idHint:ga(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Q({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}return e.dataDir?Q({rootDir:xa(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Q({rootDir:Sa(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),Q({rootDir:ba(),origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),e.bundledDir&&Q({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function wa(e){let t=e.rejectHardlinks??!0,n=na(e.rootPath),r=na(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!ia(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=I.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:I.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ta=`aimax.plugin.json`,Ea=[Ta];function Da(e){for(let t of Ea){let n=N.join(e,t);if(I.existsSync(n))return n}return N.join(e,Ta)}function Oa(e,t=!0){let n=Da(e),r=wa({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(I.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{I.closeSync(r.fd)}if(!qi(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=qi(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=Ji(i.skills),f;return qi(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 ka(e){let t=new Map,n=[];for(let r of e){let e=Oa(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}}var Aa=class{tools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);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)}};let ja=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Ma(){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 Na(e,t,n,r){process.stderr.write(`[${Ma()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function Pa(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Na(ja.INFO,e.pluginId,t,n),warn:n=>Na(ja.WARN,e.pluginId,t,n),error:n=>Na(ja.ERROR,e.pluginId,t,n)})}}}function Fa(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 Ia(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 La(e){let n=[...e.registry.diagnostics],r=new Aa,i=new mi,a=[],o=[],s=e.runtime?.llm?Je({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:i,hookCtx:e.runtime.hookCtx}):void 0,c=Ra(e.runtime?.llmAllowlist),l=Te(import.meta.url,{interopDefault:!0,requireCache:!1});for(let u of e.registry.manifests.values()){let d=Fa({config:e.plugins,pluginId:u.id,origin:u.origin,kind:u.manifest.kind}),f=Ia({id:u.id,source:u.source,origin:u.origin,enabled:d,configSchema:!0,skills:u.manifest.skills??[]});if(!d){o.push(f);continue}let p;try{p=l(u.source)}catch(e){f.status=`error`,f.error=String(e),n.push({level:`error`,message:`failed to load plugin ${u.id}: ${String(e)}`,pluginId:u.id,source:u.source}),o.push(f);continue}let m=p&&typeof p==`object`&&`default`in p?p.default:p,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){f.status=`error`,f.error=`plugin module does not export a register function`,n.push({level:`error`,message:`plugin ${u.id} has no register function`,pluginId:u.id,source:u.source}),o.push(f);continue}let g=Pa({pluginId:u.id}),_=e.plugins.entries[u.id]?.config,v={id:u.id,source:u.source,rootDir:u.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!s)throw Error(`LLM client is not configured`);if(!za(u.id,r,c))throw Error(`Plugin ${u.id} is not allowed to use LLM`);return s.chat(e)}},registerTool:(e,t)=>{r.register(u.id,e,t),f.toolCount+=1},registerEmbeddingProvider:e=>{if(u.manifest.kind!==`memory`)throw Error(`Plugin ${u.id} is not allowed to register embedding providers`);t({pluginId:u.id,id:e.id,create:e.create,config:_,rootDir:u.rootDir,source:u.source})},registerMemoryProvider:e=>{if(u.manifest.kind!==`memory`)throw Error(`Plugin ${u.id} is not allowed to register memory providers`);y({pluginId:u.id,id:e.id,create:e.create,config:_,rootDir:u.rootDir,source:u.source})},registerHook:(e,t,n)=>{i.register({pluginId:u.id,hookName:e,handler:t,priority:n?.priority,source:u.source}),f.hookCount+=1},registerSkillDir:e=>{let t=N.isAbsolute(e)?e:N.resolve(u.rootDir,e);a.push(t)}};try{h(v)}catch(e){f.status=`error`,f.error=String(e),n.push({level:`error`,message:`plugin ${u.id} registration failed: ${String(e)}`,pluginId:u.id,source:u.source})}if(u.manifest.skills&&u.manifest.skills.length>0)for(let e of u.manifest.skills){let t=N.isAbsolute(e)?e:N.resolve(u.rootDir,e);a.push(t)}o.push(f)}return{plugins:o,diagnostics:n,tools:r,hooks:i,skills:a}}function Ra(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function za(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Ba(e={}){let t=ea(e.config),n=Ca({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=ka(n.candidates),i=ta({config:t,registry:r}),a=La({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 Va(e){let{runParams:t,hookContext:n}=e,r=t.plugins?Ba({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;return{hookRegistry:r?.registry.hooks??new mi,pluginSkillDirs:r?.registry.skills??[],pluginTools:r?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],memoryPluginId:t.memory?.pluginId??r?.normalizedConfig.slots?.memory}}async function Ha(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=N.join(t.dataDir,`workspace`),a=n,o=!a;a?await h(t.dataDir,a):a=await c(t.dataDir,t.channel);let s={sessionId:a,workspaceDir:i,channel:t.channel},l=Va({runParams:t,hookContext:s}),u=l.hookRegistry,d=await kt({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:l.memoryPluginId,eventDispatcher:r,hookRegistry:u});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:u,pluginContext:l,runContext:d,start:e=>Nt({sessionId:a,runParams:t,hookRegistry:u,hookContext:s,eventDispatcher:r,...e})}}function Ua(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 Wa(e,t){Ct();let n=Date.now(),r=new wt(e),i=pn(e),a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await Ha({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;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 ke(e.dataDir),v=[],y=Me(_,{warn:e=>v.push(e)}),b=await Ie(e.dataDir,m.pluginSkillDirs),x=new qe({workspaceDir:d,sessionId:l,skills:b,report:e=>r.dispatchProgress(l,e)}),S=e=>h.appendTranscriptEntry(e),C=await hn({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 w=C.effectivePrompt;a=C.transcriptMessage;let T=await Pi({session:{runParams:e,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:b,effectivePromptText:typeof w==`string`?w:a,pluginTools:m.pluginTools},dependencies:{registry:t,spawnFn:e=>Wa(e,new Ve),createModel:Ua,abortSignal:g.signal}}),E=T.agent,D=T.resolvedModelId;g.signal.addEventListener(`abort`,()=>E.abort());let O=0,k=0,A=``,j;try{o=await h.persistInitialUserEntry(a)||o;let e=await Ii({agent:E,message:w,sessionId:l,modelId:D,historyMessages:T.historyMessages,eventDispatcher:r,skillUsageTracker:x,hooks:p,hookCtx:f,abortSignal:g.signal});A=e.text,O+=e.inputTokens,k+=e.outputTokens,e.error&&(j=e.error),await Li(S,e);let n=await Gi({agent:E,registry:t,sessionId:l,resolvedModelId:D,eventDispatcher:r,skillUsageTracker:x,hookRegistry:p,hookContext:f,abortSignal:g.signal,appendEntry:S});n.text&&(A=n.text),O+=n.inputTokens,k+=n.outputTokens,n.error&&!j&&(j=n.error)}finally{We(l),h.stop()}let ee={input:O,output:k,total:O+k};return It({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:A,usage:ee,error:j})}async function Ga(e,t){return Wa(e,t??new Ve)}const Ka={"AGENTS.md":`---
58
58
  title: "AGENTS.md Template"
59
59
  summary: ".aimax template for AGENTS.md"
60
60
  read_when:
@@ -501,4 +501,4 @@ read_when:
501
501
  # Add tasks below when you want the agent to check something periodically.
502
502
 
503
503
  # This file lives at .aimax/HEARTBEAT.md, not in workspace/.
504
- `},qa=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`,`HEARTBEAT.md`];async function $(e,t){try{if(!(await M.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 M.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Ja(e,t,n){try{if(!(await M.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 M.mkdir(N.dirname(e),{recursive:!0});try{await M.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 Ya(e){let t=L(e);return[e,t,N.join(t,`skills`),N.join(t,`sessions`),N.join(t,`memory`),N.join(e,`workspace`)]}function Xa(e){let t=L(e);return[...qa.filter(e=>e!==`BOOTSTRAP.md`).map(e=>N.join(t,e)),N.join(t,`MEMORY.md`)]}async function Za(e){let t=[],n=[];for(let n of Ya(e))try{(await M.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Xa(e))try{(await M.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 Qa(e){return(await Za(e)).ready}async function $a(e){return(await Za(e)).ready?{ready:!0,performedBootstrap:!1}:{ready:!0,performedBootstrap:!0,result:await eo(e)}}async function eo(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=L(e),r=N.join(e,`workspace`),i=N.join(n,`skills`),a=N.join(n,`sessions`),o=N.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 qa){let r=Ka[e]??``;await Ja(N.join(n,e),r,t)}return await Ja(N.join(n,`MEMORY.md`),``,t),t}async function to(e){let t=N.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await M.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 no(e,t){let n=N.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 M.mkdir(N.dirname(n),{recursive:!0}),await M.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function ro(e,t){let n=await to(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 io(e,t=7){let n=await to(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 no(e,n),i}export{Oe as BOOTSTRAP_FILE_NAMES,Ee as BOOTSTRAP_MAX_CHARS,De as BOOTSTRAP_TOTAL_MAX_CHARS,Be as MAX_CHILDREN_PER_SESSION,ze as MAX_SUBAGENT_DEPTH,p as MemoryIndexManager,Ta as PLUGIN_MANIFEST_FILENAME,Ea as PLUGIN_MANIFEST_FILENAMES,gi as PluginHookRegistry,Aa as PluginToolRegistry,Ve as SubagentRegistry,re as addAgent,k as addBinding,L as aimaxDir,Ar as appendToMemory,n as appendTranscriptEntry,eo as bootstrapMountLayout,Me as buildBootstrapContextFiles,Re as buildSkillsPrompt,Br as buildSubagentAnnounceMessage,mi as buildSystemPrompt,io as cleanupOldSubagentRecords,Jr as createAgentTools,ur as createApplyPatchTool,qn as createBashTool,u as createBuiltinMemoryProvider,nr as createEditFileTool,Fn as createExecTool,qr as createImageTool,ir as createListDirTool,Rr as createMemoryAppendTool,Ir as createMemoryGetTool,Pr as createMemorySearchTool,Pa as createPluginRuntime,Rn as createProcessTool,Qn as createReadFileTool,c as createSession,Vr as createSessionsSpawnTool,Gr as createSubagentsTool,er as createWriteFileTool,Mr as deleteMemoryFile,Ca as discoverAIMaxPlugins,$a as ensureBootstrapMountLayout,h as ensureSession,Tt as generateSessionTitle,ee as getAgentConfig,kr as getMemoryLines,Ba as initializePluginSystem,Za as inspectBootstrapMountLayout,Qa as isBootstrapMountLayoutReady,S as listAgents,Vt as listAvailableSlashCommands,A as listBindings,Tr as listMemoryFiles,r as listSessionSummaries,i as listSessions,ro as listSubagentRunsFromDisk,ne as loadAgentsConfig,ke as loadBootstrapFiles,Oa as loadPluginManifest,ka as loadPluginManifestRegistry,La as loadPlugins,f as loadSessionMetadata,Fe as loadSkills,Le as loadSkillsFromDirs,Ie as loadSkillsWithPluginDirs,to as loadSubagentRegistryFromDisk,l as loadTranscript,Sr as memoryDir,o as metadataPath,C as normalizeAgentId,na as normalizePluginsConfig,Cr as primaryMemoryPath,Er as readMemoryFile,Dr as readPrimaryMemory,t as registerEmbeddingProvider,y as registerMemoryProvider,te as removeAgent,ie as removeBindings,jr as replaceMemoryFile,d as resetEmbeddingProviderRegistryForTests,b as resetMemoryProviderRegistryForTests,w as resolveAgentDir,T as resolveAgentIdByBinding,j as resolveAgentsConfigPath,O as resolveDefaultAgentId,m as resolveEmbeddingProvider,v as resolveMemoryProvider,D as resolveModelFallbacks,E as resolveModelString,Da as resolvePluginManifestPath,Ga as runAgent,x as saveAgentsConfig,a as saveSessionMetadata,no as saveSubagentRegistryToDisk,Or as searchMemory,e as sessionDir,g as sessionsDir,Ne as skillsDir,_ as transcriptPath,ae as updateAgentIdentity,ra as validatePluginsConfig,hi as wrapToolsWithHooks};
504
+ `},qa=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`,`HEARTBEAT.md`];async function $(e,t){try{if(!(await M.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 M.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Ja(e,t,n){try{if(!(await M.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 M.mkdir(N.dirname(e),{recursive:!0});try{await M.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 Ya(e){let t=L(e);return[e,t,N.join(t,`skills`),N.join(t,`sessions`),N.join(t,`memory`),N.join(e,`workspace`)]}function Xa(e){let t=L(e);return[...qa.filter(e=>e!==`BOOTSTRAP.md`).map(e=>N.join(t,e)),N.join(t,`MEMORY.md`)]}async function Za(e){let t=[],n=[];for(let n of Ya(e))try{(await M.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Xa(e))try{(await M.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 Qa(e){return(await Za(e)).ready}async function $a(e){return(await Za(e)).ready?{ready:!0,performedBootstrap:!1}:{ready:!0,performedBootstrap:!0,result:await eo(e)}}async function eo(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=L(e),r=N.join(e,`workspace`),i=N.join(n,`skills`),a=N.join(n,`sessions`),o=N.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 qa){let r=Ka[e]??``;await Ja(N.join(n,e),r,t)}return await Ja(N.join(n,`MEMORY.md`),``,t),t}async function to(e){let t=N.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await M.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 no(e,t){let n=N.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 M.mkdir(N.dirname(n),{recursive:!0}),await M.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function ro(e,t){let n=await to(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 io(e,t=7){let n=await to(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 no(e,n),i}export{Oe as BOOTSTRAP_FILE_NAMES,Ee as BOOTSTRAP_MAX_CHARS,De as BOOTSTRAP_TOTAL_MAX_CHARS,Be as MAX_CHILDREN_PER_SESSION,ze as MAX_SUBAGENT_DEPTH,p as MemoryIndexManager,Ta as PLUGIN_MANIFEST_FILENAME,Ea as PLUGIN_MANIFEST_FILENAMES,mi as PluginHookRegistry,Aa as PluginToolRegistry,Ve as SubagentRegistry,re as addAgent,j as addBinding,L as aimaxDir,Or as appendToMemory,n as appendTranscriptEntry,eo as bootstrapMountLayout,Me as buildBootstrapContextFiles,Re as buildSkillsPrompt,Rr as buildSubagentAnnounceMessage,fi as buildSystemPrompt,io as cleanupOldSubagentRecords,Kr as createAgentTools,cr as createApplyPatchTool,Kn as createBashTool,u as createBuiltinMemoryProvider,er as createEditFileTool,Fn as createExecTool,Gr as createImageTool,nr as createListDirTool,Ir as createMemoryAppendTool,Pr as createMemoryGetTool,Mr as createMemorySearchTool,Pa as createPluginRuntime,Rn as createProcessTool,Xn as createReadFileTool,c as createSession,zr as createSessionsSpawnTool,Ur as createSubagentsTool,Qn as createWriteFileTool,Ar as deleteMemoryFile,Ca as discoverAIMaxPlugins,$a as ensureBootstrapMountLayout,h as ensureSession,Tt as generateSessionTitle,O as getAgentConfig,Dr as getMemoryLines,Ba as initializePluginSystem,Za as inspectBootstrapMountLayout,Qa as isBootstrapMountLayoutReady,S as listAgents,Vt as listAvailableSlashCommands,ee as listBindings,Cr as listMemoryFiles,r as listSessionSummaries,i as listSessions,ro as listSubagentRunsFromDisk,ne as loadAgentsConfig,ke as loadBootstrapFiles,Oa as loadPluginManifest,ka as loadPluginManifestRegistry,La as loadPlugins,f as loadSessionMetadata,Fe as loadSkills,Le as loadSkillsFromDirs,Ie as loadSkillsWithPluginDirs,to as loadSubagentRegistryFromDisk,l as loadTranscript,br as memoryDir,o as metadataPath,C as normalizeAgentId,ea as normalizePluginsConfig,xr as primaryMemoryPath,wr as readMemoryFile,Tr as readPrimaryMemory,t as registerEmbeddingProvider,y as registerMemoryProvider,k as removeAgent,ie as removeBindings,kr as replaceMemoryFile,d as resetEmbeddingProviderRegistryForTests,b as resetMemoryProviderRegistryForTests,w as resolveAgentDir,T as resolveAgentIdByBinding,te as resolveAgentsConfigPath,A as resolveDefaultAgentId,m as resolveEmbeddingProvider,v as resolveMemoryProvider,D as resolveModelFallbacks,E as resolveModelString,Da as resolvePluginManifestPath,Ga as runAgent,x as saveAgentsConfig,a as saveSessionMetadata,no as saveSubagentRegistryToDisk,Er as searchMemory,e as sessionDir,g as sessionsDir,Ne as skillsDir,_ as transcriptPath,ae as updateAgentIdentity,ta as validatePluginsConfig,pi as wrapToolsWithHooks};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.0.10",
3
+ "version": "0.0.11",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",