@gencode/agents 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,107 +1,110 @@
1
- import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,R as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,j as C,k as w,l as T,m as E,n as D,o as O,p as k,r as A,s as ee,u as j,v as M,w as N,x as P,y as F}from"./builtin-provider-BX9aHHJK.js";import{i as I,n as L,r as R}from"./provider-registry-CxtHsHdk.js";import{_ as z,a as te,c as ne,d as re,f as ie,g as ae,h as oe,i as se,l as ce,m as le,n as ue,o as de,p as fe,s as pe,t as me,u as he,v as ge}from"./config-DG3Q1aJ6.js";import{formatTaskForDisplay as _e,isHitlExpired as ve,isHitlTool as ye,validateUiToolResult as be}from"@gencode/shared";import B,{readFile as xe}from"node:fs/promises";import V,{join as Se}from"node:path";import Ce from"gray-matter";import H from"node:fs";import we from"log4js";import{Type as U,calculateCost as Te,getEnvApiKey as Ee,parseStreamingJson as De,registerApiProvider as Oe,registerBuiltInApiProviders as ke,supportsXhigh as Ae}from"@mariozechner/pi-ai";import je from"openai";import{AssistantMessageEventStream as Me}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as Ne}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as Pe,hasCopilotVisionInput as Fe}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as Ie,clampReasoning as Le}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as Re}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import{createHash as ze,randomUUID as Be}from"node:crypto";import{Agent as Ve}from"@mariozechner/pi-agent-core";import He from"node:os";import{spawn as Ue}from"node:child_process";import{isBinaryFile as We}from"isbinaryfile";import Ge from"node:readline";import{AsyncLocalStorage as Ke}from"node:async_hooks";import qe from"ajv";import{createJiti as Je}from"jiti";const Ye=2e4,Xe=15e4,Ze=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Qe(e){return V.join(e,`.aimax`)}async function $e(e){let t=Qe(e),n=[];for(let e of Ze){let r=V.join(t,e);try{let t=await B.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await B.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 et(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{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,K as l,L as u,M as d,N as f,O as p,P as m,R as h,S as g,T as _,U as v,V as y,W as b,_ as x,a as S,b as C,c as w,d as T,f as E,g as D,h as O,i as k,j as A,k as ee,l as j,m as M,n as N,o as P,p as F,r as I,s as L,u as R,v as z,w as te,x as ne,y as re,z as ie}from"./builtin-provider-_CdSlTJE.js";import{i as ae,n as oe,r as se}from"./provider-registry-CxtHsHdk.js";import{_ as ce,a as le,c as ue,d as de,f as fe,g as pe,h as me,i as he,l as ge,m as _e,n as ve,o as ye,p as be,s as xe,t as Se,u as Ce,v as we}from"./config-DG3Q1aJ6.js";import{formatTaskForDisplay as Te,isHitlExpired as Ee,isHitlTool as De,validateUiToolResult as Oe}from"@gencode/shared";import B,{readFile as ke}from"node:fs/promises";import V,{join as Ae}from"node:path";import je from"gray-matter";import H from"node:fs";import Me from"log4js";import{Type as U,calculateCost as Ne,getEnvApiKey as Pe,parseStreamingJson as Fe,registerApiProvider as Ie,registerBuiltInApiProviders as Le,supportsXhigh as Re}from"@mariozechner/pi-ai";import ze from"openai";import{AssistantMessageEventStream as Be}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as Ve}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as He,hasCopilotVisionInput as Ue}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as We,clampReasoning as Ge}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as Ke}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import{createHash as qe,randomUUID as Je}from"node:crypto";import{Agent as Ye}from"@mariozechner/pi-agent-core";import Xe from"node:os";import{spawn as Ze}from"node:child_process";import{isBinaryFile as Qe}from"isbinaryfile";import{AsyncLocalStorage as $e}from"node:async_hooks";import et from"ajv";import{createJiti as tt}from"jiti";const nt=2e4,rt=15e4,it=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function at(e){return V.join(e,`.aimax`)}async function ot(e){let t=at(e),n=[];for(let e of it){let r=V.join(t,e);try{let t=await B.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await B.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 st(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
- `),truncated:!0,originalLength:r.length}}function tt(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function nt(e,t){let n=t?.maxChars??Ye,r=Math.max(1,t?.totalMaxChars??Math.max(n,Xe)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=tt(`[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}=et(a.content??``,a.name,e),l=tt(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const rt=`You are a personal assistant running inside AiMax.`;async function it(e){try{return{presetSystemPrompt:Ce(await B.readFile(e,`utf-8`)).content.trim()||rt}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:rt};throw e}}async function at(){return it(`/aimax/system_prompt.md`)}function ot(e){return V.join(e,`.aimax`,`skills`)}function st(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function ct(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${st(n)}\n`)}function lt(e){let t=Ce(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
4
- `);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}async function ut(e){return ft([ot(e)])}async function dt(e,t,n=[]){return ft([...n,...t,ot(e)])}async function ft(e){let t=new Map;for(let n of e){let e;try{e=await B.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=V.join(n,e,`SKILL.md`),i;try{i=await B.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a;try{a=lt(i)}catch(t){ct(e,r,t);continue}t.set(e,{name:e,description:a,location:r})}}return Array.from(t.values()).slice(0,50)}async function pt(e,t){let n=t.trim();if(!n)return;let r=(await ft(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:V.dirname(r.location)}}async function mt(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=V.resolve(r),a=V.basename(i)===`SKILL.md`?i:V.join(i,`SKILL.md`);if(V.basename(a)!==`SKILL.md`)return;let o;try{o=await B.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s;try{s=lt(o)}catch(e){ct(n,a,e);return}return{skill:{name:n,description:s,location:a},rootDir:V.dirname(a)}}async function ht(e,t,n){let r=n?.trim()?await mt(t,n):await pt(e,t);if(!r)return;let i=await B.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function gt(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(`
3
+ `),truncated:!0,originalLength:r.length}}function ct(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function lt(e,t){let n=t?.maxChars??nt,r=Math.max(1,t?.totalMaxChars??Math.max(n,rt)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=ct(`[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}=st(a.content??``,a.name,e),l=ct(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const ut=`You are a personal assistant running inside AiMax.`;async function dt(e){try{return{presetSystemPrompt:je(await B.readFile(e,`utf-8`)).content.trim()||ut}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:ut};throw e}}async function ft(){return dt(`/aimax/system_prompt.md`)}function pt(e){return V.join(e,`.aimax`,`skills`)}function mt(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function ht(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${mt(n)}\n`)}function gt(e){let t=je(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
4
+ `);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}async function _t(e){return yt([pt(e)])}async function vt(e,t,n=[]){return yt([...n,...t,pt(e)])}async function yt(e){let t=new Map;for(let n of e){let e;try{e=await B.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=V.join(n,e,`SKILL.md`),i;try{i=await B.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a;try{a=gt(i)}catch(t){ht(e,r,t);continue}t.set(e,{name:e,description:a,location:r})}}return Array.from(t.values()).slice(0,50)}async function bt(e,t){let n=t.trim();if(!n)return;let r=(await yt(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:V.dirname(r.location)}}async function xt(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=V.resolve(r),a=V.basename(i)===`SKILL.md`?i:V.join(i,`SKILL.md`);if(V.basename(a)!==`SKILL.md`)return;let o;try{o=await B.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s;try{s=gt(o)}catch(e){ht(n,a,e);return}return{skill:{name:n,description:s,location:a},rootDir:V.dirname(a)}}async function St(e,t,n){let r=n?.trim()?await xt(t,n):await bt(e,t);if(!r)return;let i=await B.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Ct(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(`
5
5
  `)).join(`
6
- `)}\n</available_skills>`}const _t=`/aimax/agents`,vt=/^[a-z]+(?:-[a-z]+)*$/;function yt(e){let t=[{dir:e.systemAgentsDir??_t,source:`system`},{dir:V.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:V.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function bt(e){let t=new Map;for(let n of yt(e)){let e=await xt(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}async function xt(e,t){let n;try{n=await B.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=V.join(e,i.name),a=St(await B.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function St(e,t){let n=Ce(e),r=Ot(n.data.name)?.trim(),i=Ot(n.data.description)?.trim();if(!r||!vt.test(r)||!i)return;let a=Ot(n.data.model)?.trim(),o=Ot(n.data.initPrompt)?.trim()??Ot(n.data.initialPrompt)?.trim(),s=kt(n.data.maxTurns),c=At(n.data.tools),l=At(n.data.disallowedTools),u=At(n.data.skills);return{name:r,description:i,...c?{tools:c}:{},...l?{disallowedTools:l}:{},...a&&a!==`inherit`?{model:a}:{},...s?{maxTurns:s}:{},...o?{initPrompt:o}:{},...u?{skills:u}:{},systemPrompt:n.content.trim(),sourcePath:t.sourcePath,source:t.source}}function Ct(e,t){let n=t?.trim();if(n)return e.find(e=>e.name===n)}function wt(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Tt(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(jt)):void 0,r=new Set((t.disallowedTools??[]).map(jt));return e.filter(e=>{let t=typeof e.name==`string`?jt(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Et(e){return``}function Dt(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Ot(e){return typeof e==`string`?e:void 0}function kt(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function At(e){let t;if(typeof e==`string`)t=e.split(`,`);else if(Array.isArray(e))t=e.filter(e=>typeof e==`string`);else return;let n=t.map(e=>e.trim()).filter(Boolean);return n.length>0?n:void 0}function jt(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}function Mt(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function Nt(e=new Date){let t=Mt(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let Pt=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Ft=null;function It(){return Nt()}function Lt(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Rt(e){return V.join(e,`.aimax`)}function zt(e){return{appLogPath:V.join(e,`app.log`),errorLogPath:V.join(e,`errors.log`)}}function Bt(e){let{appLogPath:t,errorLogPath:n}=zt(e);we.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function Vt(e,t,n){return`[${It()}] [${e}] ${t}${Lt(n)}`}function Ht(e,t,n){process.stderr.write(`${Vt(e,t,n)}\n`)}function Ut(e,t,n){if(!Ft){Ht(e,t,n);return}let r=Vt(e,t,n),i=we.getLogger();if(e===Pt.ERROR){i.error(r);return}if(e===Pt.WARN){i.warn(r);return}i.info(r)}function Wt(e){let t=Rt(e);Ft?.dataDir!==e&&(H.mkdirSync(t,{recursive:!0}),Bt(t),Ft={dataDir:e,logDir:t})}const W={info:(e,t)=>Ut(Pt.INFO,e,t),warn:(e,t)=>Ut(Pt.WARN,e,t),error:(e,t)=>Ut(Pt.ERROR,e,t)};function Gt(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}const Kt=2,qt=5;var Jt=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),W.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:Gt(e.task),startedAt:e.startedAt})}complete(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`done`,n.record.result=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&W.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){W.info(`subagent status changed`,t);return}if(e.status===`killed`){W.warn(`subagent status changed`,t);return}W.error(`subagent status changed`,t)}};const Yt=new Map;function Xt(e){let t=Yt.get(e);return t||(t={},Yt.set(e,t)),t}function Zt(e){Yt.delete(e)}var G=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function Qt(e){return{async chat(t){let n=$t(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await nn(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:en(n),historyMessages:n},e.hookCtx);let i={model:r,messages:n,stream:!1};typeof t.temperature==`number`&&(i.temperature=t.temperature),typeof t.maxTokens==`number`&&(i.max_tokens=t.maxTokens);let{signal:a,clear:o,didTimeout:s}=rn(t.signal,t.timeoutMs);try{let t;try{let n=e.baseUrl.replace(/\/$/,``);t=await fetch(`${n}/chat/completions`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:JSON.stringify(i),signal:a})}catch(e){throw on(e,s())}if(!t.ok){let e=await an(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new G({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:cn(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new G({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}let c=o.choices?.[0]?.message?.content??o.choices?.[0]?.text??``,l=tn(o.usage),u=Math.max(0,Date.now()-n);return await nn(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:c?[c]:[],durationMs:u,usage:l},e.hookCtx),{text:c,usage:l,raw:o}}finally{o()}}}}function $t(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function en(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
7
- `)}function tn(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}async function nn(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function rn(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function an(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function on(e,t){return e instanceof G?e:sn(e)?t?new G({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new G({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function sn(e){return e instanceof Error&&e.name===`AbortError`}function cn(e){return e===408||e===409||e===425||e===429||e>=500}function ln(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function un(e){if(!ln(e))return null;let t=e,n=dn(t.message),r=K(n?.code)??K(t.code),i=K(n?.type)??K(t.type),a=K(n?.message)??fn(t.error)??K(t.message)??`Unknown upstream error`;return{message:pn(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:mn(r,i),raw:e}}function dn(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function fn(e){if(!(!e||typeof e!=`object`))return K(e.message)}function K(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function pn(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function mn(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}const hn=(e,t,n)=>{let r=new Me;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0};try{let a=_n(e,t,n?.apiKey||Ee(e.provider)||``,n?.headers),o=vn(e,t,n);n?.onPayload?.(o);let s=await a.chat.completions.create(o,{signal:n?.signal});r.push({type:`start`,partial:i});let c=null,l=i.content,u=()=>l.length-1,d=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:u(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:u(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=De(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=un(t);if(n)throw new G({message:`LLM upstream returned an error payload in a 200 stream: ${n.message}`,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Te(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=wn(a.finish_reason)),!a.delta))continue;a.delta.content!==null&&a.delta.content!==void 0&&a.delta.content.length>0&&((!c||c.type!==`text`)&&(d(c),c={type:`text`,text:``},i.content.push(c),r.push({type:`text_start`,contentIndex:u(),partial:i})),c.text+=a.delta.content,r.push({type:`text_delta`,contentIndex:u(),delta:a.delta.content,partial:i}));let o=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=a.delta[e];return t!=null&&t.length>0});if(o){(!c||c.type!==`thinking`)&&(d(c),c={type:`thinking`,thinking:``,thinkingSignature:o},i.content.push(c),r.push({type:`thinking_start`,contentIndex:u(),partial:i}));let e=a.delta[o];c.thinking+=e,r.push({type:`thinking_delta`,contentIndex:u(),delta:e,partial:i})}if(a.delta.tool_calls)for(let e of a.delta.tool_calls){(!c||c.type!==`toolCall`||e.id&&c.id!==e.id)&&(d(c),c={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(c),r.push({type:`toolcall_start`,contentIndex:u(),partial:i})),e.id&&(c.id=e.id),e.function?.name&&(c.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,c.partialArgs+=e.function.arguments,c.arguments=De(c.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:u(),delta:t,partial:i})}let s=a.delta.reasoning_details;if(s&&Array.isArray(s)){for(let e of s)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(d(c),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(e){for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e),e instanceof G&&Object.assign(i,{errorCode:e.code,statusCode:e.statusCode,statusText:e.statusText,providerMessage:e.providerMessage,providerCode:e.providerCode,providerType:e.providerType,retryable:e.retryable});let t=e?.error?.metadata?.raw;t&&(i.errorMessage+=`\n${t}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},gn=(e,t,n)=>{let r=n?.apiKey||Ee(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Ie(e,n,r),a=Ae(e)?n?.reasoning:Le(n?.reasoning);return hn(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function _n(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};if(e.provider===`github-copilot`){let e=Fe(t.messages);Object.assign(i,Pe({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new je({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function vn(e,t,n){let r=En(e),i=Sn(e,t,r);xn(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=Cn(t.tools,r):yn(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),(r.thinkingFormat===`zai`||r.thinkingFormat===`qwen`)&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort&&(a.reasoning_effort=n.reasoningEffort),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function yn(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function bn(e){let t=e.replace(/[^a-zA-Z0-9]/g,``);return t.length<9?t+=`ABCDEFGHI`.slice(0,9-t.length):t.length>9&&(t=t.slice(0,9)),t}function xn(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function Sn(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return bn(t);if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=Re(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Ne(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:Ne(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Ne(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>Ne(e.text)).join(``):a.map(e=>({type:`text`,text:Ne(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
6
+ `)}\n</available_skills>`}const wt=`/aimax/agents`,Tt=/^[a-z]+(?:-[a-z]+)*$/;function Et(e){let t=[{dir:e.systemAgentsDir??wt,source:`system`},{dir:V.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:V.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function Dt(e){let t=new Map;for(let n of Et(e)){let e=await Ot(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}async function Ot(e,t){let n;try{n=await B.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=V.join(e,i.name),a=kt(await B.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function kt(e,t){let n=je(e),r=Ft(n.data.name)?.trim(),i=Ft(n.data.description)?.trim();if(!r||!Tt.test(r)||!i)return;let a=Ft(n.data.model)?.trim(),o=Ft(n.data.initPrompt)?.trim()??Ft(n.data.initialPrompt)?.trim(),s=It(n.data.maxTurns),c=Lt(n.data.tools),l=Lt(n.data.disallowedTools),u=Lt(n.data.skills);return{name:r,description:i,...c?{tools:c}:{},...l?{disallowedTools:l}:{},...a&&a!==`inherit`?{model:a}:{},...s?{maxTurns:s}:{},...o?{initPrompt:o}:{},...u?{skills:u}:{},systemPrompt:n.content.trim(),sourcePath:t.sourcePath,source:t.source}}function At(e,t){let n=t?.trim();if(n)return e.find(e=>e.name===n)}function jt(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Mt(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Rt)):void 0,r=new Set((t.disallowedTools??[]).map(Rt));return e.filter(e=>{let t=typeof e.name==`string`?Rt(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Nt(e){return e.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.",e.map(e=>`- ${e.name}: ${e.description}`).join(`
7
+ `),``].join(`
8
+ `)}function Pt(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Ft(e){return typeof e==`string`?e:void 0}function It(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Lt(e){let t;if(typeof e==`string`)t=e.split(`,`);else if(Array.isArray(e))t=e.filter(e=>typeof e==`string`);else return;let n=t.map(e=>e.trim()).filter(Boolean);return n.length>0?n:void 0}function Rt(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}function zt(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function Bt(e=new Date){let t=zt(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let Vt=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Ht=null;function Ut(){return Bt()}function Wt(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Gt(e){return V.join(e,`.aimax`)}function Kt(e){return{appLogPath:V.join(e,`app.log`),errorLogPath:V.join(e,`errors.log`)}}function qt(e){let{appLogPath:t,errorLogPath:n}=Kt(e);Me.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function Jt(e,t,n){return`[${Ut()}] [${e}] ${t}${Wt(n)}`}function Yt(e,t,n){process.stderr.write(`${Jt(e,t,n)}\n`)}function Xt(e,t,n){if(!Ht){Yt(e,t,n);return}let r=Jt(e,t,n),i=Me.getLogger();if(e===Vt.ERROR){i.error(r);return}if(e===Vt.WARN){i.warn(r);return}i.info(r)}function Zt(e){let t=Gt(e);Ht?.dataDir!==e&&(H.mkdirSync(t,{recursive:!0}),qt(t),Ht={dataDir:e,logDir:t})}const W={info:(e,t)=>Xt(Vt.INFO,e,t),warn:(e,t)=>Xt(Vt.WARN,e,t),error:(e,t)=>Xt(Vt.ERROR,e,t)};function Qt(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}const $t=2,en=5;var tn=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),W.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:Qt(e.task),startedAt:e.startedAt})}complete(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`done`,n.record.result=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&W.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){W.info(`subagent status changed`,t);return}if(e.status===`killed`){W.warn(`subagent status changed`,t);return}W.error(`subagent status changed`,t)}};const nn=new Map;function rn(e){let t=nn.get(e);return t||(t={},nn.set(e,t)),t}function an(e){nn.delete(e)}var G=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function on(e){return{async chat(t){let n=sn(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await un(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:cn(n),historyMessages:n},e.hookCtx);let i={model:r,messages:n,stream:!1};typeof t.temperature==`number`&&(i.temperature=t.temperature),typeof t.maxTokens==`number`&&(i.max_tokens=t.maxTokens);let{signal:a,clear:o,didTimeout:s}=dn(t.signal,t.timeoutMs);try{let t;try{let n=e.baseUrl.replace(/\/$/,``);t=await fetch(`${n}/chat/completions`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:JSON.stringify(i),signal:a})}catch(e){throw pn(e,s())}if(!t.ok){let e=await fn(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new G({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:hn(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new G({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}let c=o.choices?.[0]?.message?.content??o.choices?.[0]?.text??``,l=ln(o.usage),u=Math.max(0,Date.now()-n);return await un(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:c?[c]:[],durationMs:u,usage:l},e.hookCtx),{text:c,usage:l,raw:o}}finally{o()}}}}function sn(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function cn(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
9
+ `)}function ln(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}async function un(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function dn(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function fn(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function pn(e,t){return e instanceof G?e:mn(e)?t?new G({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new G({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function mn(e){return e instanceof Error&&e.name===`AbortError`}function hn(e){return e===408||e===409||e===425||e===429||e>=500}function gn(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function _n(e){if(!gn(e))return null;let t=e,n=vn(t.message),r=K(n?.code)??K(t.code),i=K(n?.type)??K(t.type),a=K(n?.message)??yn(t.error)??K(t.message)??`Unknown upstream error`;return{message:bn(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:xn(r,i),raw:e}}function vn(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function yn(e){if(!(!e||typeof e!=`object`))return K(e.message)}function K(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function bn(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function xn(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}const Sn=(e,t,n)=>{let r=new Be;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0};try{let a=wn(e,t,n?.apiKey||Pe(e.provider)||``,n?.headers),o=Tn(e,t,n);n?.onPayload?.(o);let s=await a.chat.completions.create(o,{signal:n?.signal});r.push({type:`start`,partial:i});let c=null,l=i.content,u=()=>l.length-1,d=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:u(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:u(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=Fe(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=_n(t);if(n)throw new G({message:`LLM upstream returned an error payload in a 200 stream: ${n.message}`,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Ne(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=jn(a.finish_reason)),!a.delta))continue;a.delta.content!==null&&a.delta.content!==void 0&&a.delta.content.length>0&&((!c||c.type!==`text`)&&(d(c),c={type:`text`,text:``},i.content.push(c),r.push({type:`text_start`,contentIndex:u(),partial:i})),c.text+=a.delta.content,r.push({type:`text_delta`,contentIndex:u(),delta:a.delta.content,partial:i}));let o=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=a.delta[e];return t!=null&&t.length>0});if(o){(!c||c.type!==`thinking`)&&(d(c),c={type:`thinking`,thinking:``,thinkingSignature:o},i.content.push(c),r.push({type:`thinking_start`,contentIndex:u(),partial:i}));let e=a.delta[o];c.thinking+=e,r.push({type:`thinking_delta`,contentIndex:u(),delta:e,partial:i})}if(a.delta.tool_calls)for(let e of a.delta.tool_calls){(!c||c.type!==`toolCall`||e.id&&c.id!==e.id)&&(d(c),c={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(c),r.push({type:`toolcall_start`,contentIndex:u(),partial:i})),e.id&&(c.id=e.id),e.function?.name&&(c.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,c.partialArgs+=e.function.arguments,c.arguments=Fe(c.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:u(),delta:t,partial:i})}let s=a.delta.reasoning_details;if(s&&Array.isArray(s)){for(let e of s)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(d(c),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(e){for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e),e instanceof G&&Object.assign(i,{errorCode:e.code,statusCode:e.statusCode,statusText:e.statusText,providerMessage:e.providerMessage,providerCode:e.providerCode,providerType:e.providerType,retryable:e.retryable});let t=e?.error?.metadata?.raw;t&&(i.errorMessage+=`\n${t}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Cn=(e,t,n)=>{let r=n?.apiKey||Pe(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=We(e,n,r),a=Re(e)?n?.reasoning:Ge(n?.reasoning);return Sn(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function wn(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};if(e.provider===`github-copilot`){let e=Ue(t.messages);Object.assign(i,He({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new ze({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Tn(e,t,n){let r=Nn(e),i=kn(e,t,r);On(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=An(t.tools,r):En(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),(r.thinkingFormat===`zai`||r.thinkingFormat===`qwen`)&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort&&(a.reasoning_effort=n.reasoningEffort),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function En(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function Dn(e){let t=e.replace(/[^a-zA-Z0-9]/g,``);return t.length<9?t+=`ABCDEFGHI`.slice(0,9-t.length):t.length>9&&(t=t.slice(0,9)),t}function On(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function kn(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Dn(t);if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=Ke(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Ve(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:Ve(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Ve(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>Ve(e.text)).join(``):a.map(e=>({type:`text`,text:Ve(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
8
10
 
9
11
  `);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
10
12
  `))}let c=i.content.filter(e=>e.type===`toolCall`);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}let l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t),o=i.role;continue}if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s+=1){let t=a[s],o=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
11
- `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:Ne(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function Cn(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function wn(e){if(e===null)return`stop`;switch(e){case`stop`:return`stop`;case`length`:return`length`;case`function_call`:case`tool_calls`:return`toolUse`;case`error`:case`content_filter`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}function Tn(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||t===`opencode`||n.includes(`opencode.ai`),a=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),o=t===`xai`||n.includes(`api.x.ai`),s=t===`mistral`||n.includes(`mistral.ai`);return{supportsStore:!i,supportsDeveloperRole:!i,supportsReasoningEffort:!o&&!r,supportsUsageInStreaming:!0,maxTokensField:a?`max_tokens`:`max_completion_tokens`,requiresToolResultName:s,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:s,requiresMistralToolIds:s,thinkingFormat:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},supportsStrictMode:!0}}function En(e){let t=Tn(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresMistralToolIds:e.compat.requiresMistralToolIds??t.requiresMistralToolIds,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode}:t}let Dn=!1;function On(){Dn||=(ke(),Oe({api:`openai-completions`,stream:hn,streamSimple:gn}),!0)}var kn=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};await this.params.onProgress?.(n)}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};const An=[`You are a session title generator. Generate a concise title (max 80 chars) for the given user message.`,``,`Rules:`,`- The title should capture the main topic or intent of the message`,`- Keep it short and descriptive`,`- Use the user's language (Chinese for Chinese messages, English for English messages)`,`- Output only the title text — no preamble, no quotes, no extra formatting`,`- As the user role, summarize the title based on the conversation content`,`- The principle of title generation is to describe the behavioral characteristics of the user in the conversation, rather than answering based on the content of the conversation`].join(`
12
- `);async function jn(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o}=e,s=t.trim().replace(/\s+/g,` `);if(!s)return`New session`;if(!r.flashModel)return Nn(s);let c=r.flashModel,l=Qt({baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:c,hooks:a,hookCtx:o}),u=[{role:`user`,content:s}];n&&u.push({role:`assistant`,content:n});for(let e=1;e<=3;e++)try{let e=(await l.chat({system:An,user:JSON.stringify(u),temperature:0,maxTokens:100,signal:i})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;e<3&&await Mn(500*e)}return Nn(s)}function Mn(e){return new Promise(t=>setTimeout(t,e))}function Nn(e,t=80){if(!e)return`New session`;try{let t=JSON.parse(e);if(Array.isArray(t))return t?.[0]?.content?.[0].text??e}catch{}let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}function q(e){return{storeName:e.sessionStoreName,...e.sessionPathScope}}async function Pn(e){let{sessionId:t,resetCommand:n,previousSessionId:r,resetMessage:i,startMessage:a,hookRegistry:o,hookContext:s,eventDispatcher:c}=e;n&&i&&await c.dispatchProgress(t,{type:`session_reset`,action:n.action,previousSessionId:r,message:i}),n&&i&&await o.dispatch(`session_reset`,{action:n.action,sessionId:t,previousSessionId:r,message:i},s,{eventDispatcher:c}),await c.dispatchProgress(t,{type:`start`,message:a}),await o.dispatch(`session_start`,{sessionId:t},s,{eventDispatcher:c})}async function Fn(e){let{sessionId:t,result:r,runParams:i,hookRegistry:a,hookContext:o}=e;await a.dispatch(`agent_end`,{success:!r.error,error:r.error,durationMs:r.durationMs},o,{eventDispatcher:e.eventDispatcher});let s=await n(i.dataDir,t,{...q(i)});await a.dispatch(`session_end`,{sessionId:t,messageCount:s.length,durationMs:r.durationMs},o,{eventDispatcher:e.eventDispatcher})}async function In(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:o=!1,runParams:s,hookRegistry:c,hookContext:l,startTime:u,compactionEntry:f,eventDispatcher:p}=e,m=q(s);if(o||await y(s.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},m),f&&await y(s.dataDir,n,f,m),await y(s.dataDir,n,{role:`assistant`,content:t,timestamp:new Date().toISOString()},m),r){let t=await jn({message:i.trim()?i:`New session`,llm:s.llm,text:e.replyText,hooks:c,hookCtx:l});await d(s.dataDir,n,{title:t},m),await p.dispatchProgress(n,{type:`title_updated`,title:t})}let h=Date.now()-u,g={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:h,context:{snapshotPath:x(s.dataDir,n,q(s)),toolResultsDir:a(s.dataDir,n,q(s))}};return W.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:h,isNewSession:r,textLength:t.length,hasCompactionEntry:!!f,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir}),await Fn({sessionId:n,result:g,runParams:s,hookRegistry:c,hookContext:l,eventDispatcher:p}),g}async function Ln(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:o,hookContext:s,startTime:c,text:l,usage:u,error:f,paused:p,uiToolPending:m,eventDispatcher:h}=e;if(n){let n=q(i),a=await jn({message:r,llm:i.llm,text:e.text,hooks:o,hookCtx:s});await d(i.dataDir,t,{title:a},n),await h.dispatchProgress(t,{type:`title_updated`,title:a})}let g={sessionId:t,text:l,usage:u,durationMs:Date.now()-c,error:f,paused:p,uiToolPending:m,context:{snapshotPath:x(i.dataDir,t,q(i)),toolResultsDir:a(i.dataDir,t,q(i))}},_={sessionId:t,kind:`completed`,durationMs:g.durationMs,isNewSession:n,inputTokens:u.input,outputTokens:u.output,totalTokens:u.total,hasError:!!f,error:f,paused:!!p,uiToolPending:!!m,textLength:l.length,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir};return f?W.warn(`agent run finalized with error`,_):W.info(`agent run finalized`,_),await Fn({sessionId:t,result:g,runParams:i,hookRegistry:o,hookContext:s,eventDispatcher:h}),g}const Rn=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`}];function zn(){return Rn.map(e=>({...e}))}function Bn(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Vn(e){let t=new Set,n=[];for(let r of e){let e=Bn(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Hn(e){let t=zn(),n=Vn(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function Un(e){let t=e.trim();if(!t)return``;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s);if(!n)return t;let[,r,i]=n,a=i.trimStart();return a?`/${r} ${a}`:`/${r}`}function Wn(e){let t=Un(e);if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]+))?$/);if(!n)return null;let r=n[1]?.trim().toLowerCase()??``,i=(n[2]??``).trim();return r?{name:r,rest:i}:null}function Gn(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s),r=(n?(()=>{let[,e,t]=n,r=t.trimStart();return r?`/${e} ${r}`:`/${e}`})():t).match(/^\/([^\s@]+)(?:@[^\s]+)?(?:\s+([\s\S]+))?$/);if(!r)return null;let i=r[1]?.trim().toLowerCase()??``;if(i!==`new`&&i!==`reset`)return null;let a=(r[2]??``).trim();return{action:i===`new`?`new`:`reset`,remainder:a}}function Kn(e,t){let n=Wn(e);if(!n)return{kind:`none`};if(n.name===`help`)return n.rest?{kind:`unknown`,name:n.name,args:n.rest}:{kind:`help`};if(n.name===`compact`)return{kind:`compact`,instructions:n.rest};if(n.name===`new`||n.name===`reset`)return{kind:`reset`,action:n.name===`new`?`new`:`reset`,remainder:n.rest};if(n.name===`skill`){if(!n.rest)return{kind:`unknown`,name:n.name,args:``};let e=n.rest.match(/^([^\s]+)(?:\s+([\s\S]+))?$/);return e?{kind:`skill`,name:Bn(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Vn(t).map(e=>e.name.slice(1))).has(n.name)?{kind:`skill-direct`,name:n.name,args:n.rest}:{kind:`unknown`,name:n.name,args:n.rest}}const qn=new Set([`/new`,`/reset`,`/compact`]),Jn=new Set([`/help`]);function Yn(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function Xn(e){if(e.length===0)return[];let t=e.map(Yn),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Zn(e){let t=Hn(e.skills),n=t.builtin.filter(e=>qn.has(e.name)),r=t.builtin.filter(e=>e.name===`/skill`),i=t.builtin.filter(e=>Jn.has(e.name)),a=t.skillCommands.slice(0,4),o=[];return o.push(`帮助`),o.push(``),o.push(`会话命令`),o.push(...Xn(n)),o.push(``),o.push(`技能命令`),o.push(...Xn(r)),a.length>0?(o.push(...Xn(a)),t.skillCommands.length>a.length&&o.push(` ... 还有 ${t.skillCommands.length-a.length} 个`)):o.push(` 未安装技能命令`),o.push(``),o.push(`其他命令`),o.push(...Xn(i)),{kind:`reply`,text:o.join(`
13
- `)}}function Qn(e,t){let n=t.trim().toLowerCase();return n&&Vn(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function $n(e){let t=Qn(e.ctx.skills,e.skillName);return t?{kind:`rewrite`,message:[`Use the "${t.name}" skill for this request.`,e.args?`User input:\n${e.args}`:null].filter(e=>!!e).join(`
13
+ `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:Ve(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function An(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function jn(e){if(e===null)return`stop`;switch(e){case`stop`:return`stop`;case`length`:return`length`;case`function_call`:case`tool_calls`:return`toolUse`;case`error`:case`content_filter`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}function Mn(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||t===`opencode`||n.includes(`opencode.ai`),a=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),o=t===`xai`||n.includes(`api.x.ai`),s=t===`mistral`||n.includes(`mistral.ai`);return{supportsStore:!i,supportsDeveloperRole:!i,supportsReasoningEffort:!o&&!r,supportsUsageInStreaming:!0,maxTokensField:a?`max_tokens`:`max_completion_tokens`,requiresToolResultName:s,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:s,requiresMistralToolIds:s,thinkingFormat:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},supportsStrictMode:!0}}function Nn(e){let t=Mn(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresMistralToolIds:e.compat.requiresMistralToolIds??t.requiresMistralToolIds,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode}:t}let Pn=!1;function Fn(){Pn||=(Le(),Ie({api:`openai-completions`,stream:Sn,streamSimple:Cn}),!0)}var In=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};await this.params.onProgress?.(n)}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};const Ln=[`You are a session title generator. Generate a concise title (max 80 chars) for the given user message.`,``,`Rules:`,`- The title should capture the main topic or intent of the message`,`- Keep it short and descriptive`,`- Use the user's language (Chinese for Chinese messages, English for English messages)`,`- Output only the title text — no preamble, no quotes, no extra formatting`,`- As the user role, summarize the title based on the conversation content`,`- The principle of title generation is to describe the behavioral characteristics of the user in the conversation, rather than answering based on the content of the conversation`].join(`
14
+ `);async function Rn(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o}=e,s=t.trim().replace(/\s+/g,` `);if(!s)return`New session`;if(!r.flashModel)return Bn(s);let c=r.flashModel,l=on({baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:c,hooks:a,hookCtx:o}),u=[{role:`user`,content:s}];n&&u.push({role:`assistant`,content:n});for(let e=1;e<=3;e++)try{let e=(await l.chat({system:Ln,user:JSON.stringify(u),temperature:0,maxTokens:100,signal:i})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;e<3&&await zn(500*e)}return Bn(s)}function zn(e){return new Promise(t=>setTimeout(t,e))}function Bn(e,t=80){if(!e)return`New session`;try{let t=JSON.parse(e);if(Array.isArray(t))return t?.[0]?.content?.[0].text??e}catch{}let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}function q(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}async function Vn(e){let{sessionId:t,resetCommand:n,previousSessionId:r,resetMessage:i,startMessage:a,hookRegistry:o,hookContext:s,eventDispatcher:c}=e;n&&i&&await c.dispatchProgress(t,{type:`session_reset`,action:n.action,previousSessionId:r,message:i}),n&&i&&await o.dispatch(`session_reset`,{action:n.action,sessionId:t,previousSessionId:r,message:i},s,{eventDispatcher:c}),await c.dispatchProgress(t,{type:`start`,message:a}),await o.dispatch(`session_start`,{sessionId:t},s,{eventDispatcher:c})}async function Hn(e){let{sessionId:t,result:n,runParams:i,hookRegistry:a,hookContext:o}=e;await a.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs},o,{eventDispatcher:e.eventDispatcher});let s=await r(i.dataDir,t,{...q(i)});await a.dispatch(`session_end`,{sessionId:t,messageCount:s.length,durationMs:n.durationMs},o,{eventDispatcher:e.eventDispatcher})}async function Un(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:a=!1,runParams:o,hookRegistry:s,hookContext:l,startTime:u,compactionEntry:d,eventDispatcher:f}=e,p=q(o);if(a||await E(o.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},p),d&&await E(o.dataDir,n,d,p),await E(o.dataDir,n,{role:`assistant`,content:t,timestamp:new Date().toISOString()},p),r){let t=await Rn({message:i.trim()?i:`New session`,llm:o.llm,text:e.replyText,hooks:s,hookCtx:l});await h(o.dataDir,n,{title:t},p),await f.dispatchProgress(n,{type:`title_updated`,title:t})}let m=Date.now()-u,g={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:m,context:{snapshotPath:O(o.dataDir,n,q(o)),toolResultsDir:c(o.dataDir,n,q(o))}};return W.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:m,isNewSession:r,textLength:t.length,hasCompactionEntry:!!d,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir}),await Hn({sessionId:n,result:g,runParams:o,hookRegistry:s,hookContext:l,eventDispatcher:f}),g}async function Wn(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:a,hookContext:o,startTime:s,text:l,usage:u,error:d,paused:f,uiToolPending:p,eventDispatcher:m}=e;if(n){let n=q(i),s=await Rn({message:r,llm:i.llm,text:e.text,hooks:a,hookCtx:o});await h(i.dataDir,t,{title:s},n),await m.dispatchProgress(t,{type:`title_updated`,title:s})}let g={sessionId:t,text:l,usage:u,durationMs:Date.now()-s,error:d,paused:f,uiToolPending:p,context:{snapshotPath:O(i.dataDir,t,q(i)),toolResultsDir:c(i.dataDir,t,q(i))}},_={sessionId:t,kind:`completed`,durationMs:g.durationMs,isNewSession:n,inputTokens:u.input,outputTokens:u.output,totalTokens:u.total,hasError:!!d,error:d,paused:!!f,uiToolPending:!!p,textLength:l.length,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir};return d?W.warn(`agent run finalized with error`,_):W.info(`agent run finalized`,_),await Hn({sessionId:t,result:g,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:m}),g}const Gn=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`}];function Kn(){return Gn.map(e=>({...e}))}function qn(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Jn(e){let t=new Set,n=[];for(let r of e){let e=qn(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Yn(e){let t=Kn(),n=Jn(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function Xn(e){let t=e.trim();if(!t)return``;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s);if(!n)return t;let[,r,i]=n,a=i.trimStart();return a?`/${r} ${a}`:`/${r}`}function Zn(e){let t=Xn(e);if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]+))?$/);if(!n)return null;let r=n[1]?.trim().toLowerCase()??``,i=(n[2]??``).trim();return r?{name:r,rest:i}:null}function Qn(e){let t=e.trim();if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s),r=(n?(()=>{let[,e,t]=n,r=t.trimStart();return r?`/${e} ${r}`:`/${e}`})():t).match(/^\/([^\s@]+)(?:@[^\s]+)?(?:\s+([\s\S]+))?$/);if(!r)return null;let i=r[1]?.trim().toLowerCase()??``;if(i!==`new`&&i!==`reset`)return null;let a=(r[2]??``).trim();return{action:i===`new`?`new`:`reset`,remainder:a}}function $n(e,t){let n=Zn(e);if(!n)return{kind:`none`};if(n.name===`help`)return n.rest?{kind:`unknown`,name:n.name,args:n.rest}:{kind:`help`};if(n.name===`compact`)return{kind:`compact`,instructions:n.rest};if(n.name===`new`||n.name===`reset`)return{kind:`reset`,action:n.name===`new`?`new`:`reset`,remainder:n.rest};if(n.name===`skill`){if(!n.rest)return{kind:`unknown`,name:n.name,args:``};let e=n.rest.match(/^([^\s]+)(?:\s+([\s\S]+))?$/);return e?{kind:`skill`,name:qn(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Jn(t).map(e=>e.name.slice(1))).has(n.name)?{kind:`skill-direct`,name:n.name,args:n.rest}:{kind:`unknown`,name:n.name,args:n.rest}}const er=new Set([`/new`,`/reset`,`/compact`]),tr=new Set([`/help`]);function nr(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function rr(e){if(e.length===0)return[];let t=e.map(nr),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function ir(e){let t=Yn(e.skills),n=t.builtin.filter(e=>er.has(e.name)),r=t.builtin.filter(e=>e.name===`/skill`),i=t.builtin.filter(e=>tr.has(e.name)),a=t.skillCommands.slice(0,4),o=[];return o.push(`帮助`),o.push(``),o.push(`会话命令`),o.push(...rr(n)),o.push(``),o.push(`技能命令`),o.push(...rr(r)),a.length>0?(o.push(...rr(a)),t.skillCommands.length>a.length&&o.push(` ... 还有 ${t.skillCommands.length-a.length} 个`)):o.push(` 未安装技能命令`),o.push(``),o.push(`其他命令`),o.push(...rr(i)),{kind:`reply`,text:o.join(`
15
+ `)}}function ar(e,t){let n=t.trim().toLowerCase();return n&&Jn(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function or(e){let t=ar(e.ctx.skills,e.skillName);return t?{kind:`rewrite`,message:[`Use the "${t.name}" skill for this request.`,e.args?`User input:\n${e.args}`:null].filter(e=>!!e).join(`
14
16
 
15
- `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function er(e){let t=Kn(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Zn(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?$n({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:{kind:`pass`,message:e.message}}function tr(e){return Math.ceil(e.length/4*1.2)}function nr(e){if(e.role===`user`)return tr(e.content);if(e.role===`assistant`){let t=tr(e.content);for(let n of e.toolCalls??[])t+=tr(n.name)+tr(JSON.stringify(n.arguments));return t}let t=e.toolResultRef?[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,e.toolResultRef.preview].filter(Boolean).join(`
16
- `):e.content;return tr(e.toolName)+tr(t)}function J(e){return e.reduce((e,t)=>e+nr(t),0)}const rr=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- A list of skill names and their locations/paths mentioned or loaded in the compressed content, especially skill_load names and paths`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
17
- `);async function ir(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=or(t,r,i),l,u=Qt({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:rr,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 ar(500*e)}throw l}function ar(e){return new Promise(t=>setTimeout(t,e))}function or(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.toolName===`skill_load`?sr(t):t.toolResultRef?[`[tool result persisted] ${t.toolResultRef.toolName} (${t.toolResultRef.originalChars} chars).`,`Full output: ${t.toolResultRef.storagePath}`,t.toolResultRef.preview.trim()?`Preview:\n${t.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
17
+ `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function sr(e){let t=$n(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?ir(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?or({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:{kind:`pass`,message:e.message}}function cr(e){return Math.ceil(e.length/4*1.2)}function lr(e){if(e.role===`user`)return cr(e.content);if(e.role===`assistant`){let t=cr(e.content);for(let n of e.toolCalls??[])t+=cr(n.name)+cr(JSON.stringify(n.arguments));return t}let t=e.toolResultRef?[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,e.toolResultRef.preview].filter(Boolean).join(`
18
+ `):e.content;return cr(e.toolName)+cr(t)}function J(e){return e.reduce((e,t)=>e+lr(t),0)}const ur=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- A list of skill names and their locations/paths mentioned or loaded in the compressed content, especially skill_load names and paths`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
19
+ `);async function dr(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=pr(t,r,i),l,u=on({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:ur,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 fr(500*e)}throw l}function fr(e){return new Promise(t=>setTimeout(t,e))}function pr(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.toolName===`skill_load`?mr(t):t.toolResultRef?[`[tool result persisted] ${t.toolResultRef.toolName} (${t.toolResultRef.originalChars} chars).`,`Full output: ${t.toolResultRef.storagePath}`,t.toolResultRef.preview.trim()?`Preview:\n${t.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
18
20
  `):t.content,i=n.length>2e3?`${n.slice(0,2e3)}… [truncated]`:n;r.push(`Tool(${t.toolName})[${e}]: ${i}`)}return r.join(`
19
- `)}function sr(e){let t=cr(e),n=t.name??`<skill-name>`,r=t.path,i=r?`skill_load(name="${n}", skillPath="${r}")`:`skill_load(name="${n}")`;return[`[skill content folded] skill_load result for "${n}" is not a reliable source for future instructions.`,r?`Original path: ${r}`:``,`If this skill is needed later, call ${i} again.`,`Do not summarize, infer, or reconstruct SKILL.md instructions from this history.`].filter(Boolean).join(`
20
- `)}function cr(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=lr(t);if(e.name||e.path)return e}return{}}function lr(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function ur(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=nr(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function dr(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 fr(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=pr(t),l=c>=0?t[c].content:void 0,u=dr(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}=ur(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:J(u)}:{status:`compacted`,entry:{role:`compaction`,content:await ir({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:J(d)}}function pr(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const mr=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
21
- `),hr=[`.aimax/new.txt`];async function gr(e){try{return(await xe(e,`utf-8`)).trim()||null}catch{return null}}async function _r(e){for(let t of hr){let n=await gr(Se(e,t));if(n)return n}return await gr(`/aimax/new.txt`)||mr}async function vr(e){return{kind:`reply`,text:await _r(e)}}function yr(){return{kind:`reply`,text:`✅ Session reset.`}}function br(e){let t=Cr(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?wr(r):null,a=n??i?.text,o=a?Gn(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Tr(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Er(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function xr(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=er({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:Tr(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Er(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Sr(e){let t=xr(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 In({replyText:(t.action===`reset`?yr():await vr(e.runParams.dataDir)).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 In({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 r=await fr({entries:e.runParams.channel===`CRON`?[]:await n(e.runParams.dataDir,e.sessionId,q(e.runParams)),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 In({replyText:r.status===`compacted`?`⚙️ Compacted (kept ${r.keptCount}, dropped ${r.droppedCount}).`:`⚙️ Compaction skipped: ${r.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:r.status===`compacted`?r.entry:void 0,eventDispatcher:e.eventDispatcher})}}function Cr(e){return typeof e.message==`string`}function wr(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 Tr(e,t){let n=wr(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 Er(e){return typeof e==`string`?e:JSON.stringify(e)}function Dr(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 Or=[`If you need content beyond this preview, do not load the full output into the parent context.`,`Use subagent_spawn to inspect the Full output file and return only a concise, query-focused summary.`,`Pass the Full output path, note that it is relative to dataDir when not absolute, and include the current question or search target in the subagent task.`],kr={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Ar(e,t){return e.map(e=>jr(e,t))}function jr(e,t){let n=new Date(e.timestamp).getTime();if(Mr(e))return{role:`user`,content:e.content,timestamp:n};if(Nr(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:kr,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:Pr(r)}],isError:r.isError,timestamp:n}}function Mr(e){return e.role===`user`}function Nr(e){return e.role===`assistant`}function Pr(e){if(!e.toolResultRef)return e.content;let t=e.toolResultRef.preview.trimEnd(),n=[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,`Instruction:`,...Or];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
22
- `)}const Fr=[`If you need content beyond this preview, do not load the full output into the parent context.`,`Use subagent_spawn to inspect the Full output file and return only a concise, query-focused summary.`,`Pass the Full output path, note that it is relative to dataDir when not absolute, and include the current question or search target in the subagent task.`];async function Ir(e){let t=x(e.dataDir,e.sessionId,e),n=new Map,r=new Map,i=[],o=[],s=[],c,l,u=0,d,f,p=await Vr(t);for(let e of p.readStates)n.set(Lr(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);i.push(...p.compaction.budgets),o.push(...p.compaction.snips),s.push(...p.compaction.collapseSpans),c=p.compaction.sessionMemory,l=p.compaction.modelUsage,u=p.compaction.consecutiveAutocompactFailures,d=p.compaction.lastCompactionAt,f=p.compaction.lastCompactionLayer;let m=async()=>{let e={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await B.mkdir(V.dirname(t),{recursive:!0}),await B.writeFile(t,JSON.stringify(e,null,2),`utf-8`)};return{async findReusableRead(e,t,r){let i=Lr(e,t,r),a=n.get(i);if(!a)return null;let o=await zr(e);return o===null||o!==a.lastModifiedMs?(n.delete(i),await m(),null):a},async recordRead(e){let t=new Date().toISOString(),r={path:e.path,offset:e.offset,limit:e.limit,contentHash:Br(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await zr(e.path)??Date.now()};return n.set(Lr(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())Rr(i.path)===Rr(e)&&(n.delete(r),t=!0);t&&await m()},async persistToolResult(t){let n=t.thresholdChars??12e3;if(t.content.length<=n)return{content:t.content};let o=t.previewChars??2e3,s=a(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=V.join(s,c);await B.mkdir(s,{recursive:!0}),await B.writeFile(l,t.content,`utf-8`);let u=V.relative(e.dataDir,l).split(V.sep).join(`/`),p=Gr(t.content,o),h={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:u,preview:p,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(h.toolCallId,h),i.push({toolCallId:h.toolCallId,toolName:h.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:p.length,strategy:`persist`,createdAt:h.createdAt}),d=h.createdAt,f=`L2`,await m(),{content:Wr(h),reference:h}},async recordSnip(e){o.push(e),d=e.createdAt,f=e.reason===`context_dedup`?`L1`:e.reason===`microcompact`?`L4`:`L3`,await m()},async recordCollapse(e){s.push(e),d=e.createdAt,f=e.layer,await m()},async setSessionMemory(t){c=t,await Kr(e.dataDir,e.sessionId,t,e),await m()},async recordModelUsage(e){l=e,await m()},async recordAutocompactResult(e){u=e.failed?u+1:0,d=e.timestamp,f=`L6`,await m()},getSnapshot(){return{version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function Lr(e,t,n){return`${Rr(e)}::${t??``}::${n??``}`}function Rr(e){return V.normalize(e)}async function zr(e){try{return(await B.stat(e)).mtimeMs}catch{return null}}function Br(e){return ze(`sha1`).update(e).digest(`hex`)}async function Vr(e){try{let t=await B.readFile(e,`utf-8`),n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?Hr():{version:2,updatedAt:typeof n.updatedAt==`string`?n.updatedAt:new Date(0).toISOString(),readStates:Array.isArray(n.readStates)?n.readStates:[],toolResults:Array.isArray(n.toolResults)?n.toolResults:[],compaction:{sessionMemory:n.compaction?.sessionMemory,modelUsage:Ur(n.compaction?.modelUsage),budgets:Array.isArray(n.compaction?.budgets)?n.compaction.budgets:[],snips:Array.isArray(n.compaction?.snips)?n.compaction.snips:[],collapseSpans:Array.isArray(n.compaction?.collapseSpans)?n.compaction.collapseSpans:[],consecutiveAutocompactFailures:typeof n.compaction?.consecutiveAutocompactFailures==`number`?n.compaction.consecutiveAutocompactFailures:0,lastCompactionAt:typeof n.compaction?.lastCompactionAt==`string`?n.compaction.lastCompactionAt:void 0,lastCompactionLayer:n.compaction?.lastCompactionLayer===`L1`||n.compaction?.lastCompactionLayer===`L2`||n.compaction?.lastCompactionLayer===`L3`||n.compaction?.lastCompactionLayer===`L4`||n.compaction?.lastCompactionLayer===`L5`||n.compaction?.lastCompactionLayer===`L6`?n.compaction.lastCompactionLayer:void 0}}}catch{return Hr()}}function Hr(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Ur(e){if(!e||typeof e!=`object`)return;let t=e;if(!(t.version!==1||typeof t.model!=`string`||typeof t.inputTokens!=`number`||typeof t.outputTokens!=`number`||typeof t.totalTokens!=`number`||typeof t.coveredTranscriptEntryCount!=`number`||typeof t.recordedAt!=`string`))return{version:1,model:t.model,inputTokens:Math.max(0,Math.floor(t.inputTokens)),outputTokens:Math.max(0,Math.floor(t.outputTokens)),totalTokens:Math.max(0,Math.floor(t.totalTokens)),coveredTranscriptEntryCount:Math.max(0,Math.floor(t.coveredTranscriptEntryCount)),recordedAt:t.recordedAt}}function Wr(e){let t=e.preview.length<e.originalChars?`
23
- ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...Fr,`Preview:`,e.preview+t].join(`
24
- `)}function Gr(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
25
- `),r=n>t*.5?n:t;return e.slice(0,r)}async function Kr(e,t,n,r){let i=u(e,t,r);await B.mkdir(V.dirname(i),{recursive:!0}),await B.writeFile(i,JSON.stringify(n,null,2),`utf-8`)}const qr=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Jr(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,signal:c,hooks:l,hookCtx:u,contextStore:d,dataDir:f,sessionId:p,sessionStoreName:m,sessionPathScope:h}=e,g,_=oi(t),v=_>=0?t.slice(_+1):t;_>=0&&(g=t[_].content);let y=t.length,b=dr(Dr(v,a)),x=[];d&&(g=await Yr({entries:b,existingSummary:g,llm:i,contextStore:d,signal:c,hooks:l,hookCtx:u}));let S=b;if(S=await Xr({entries:S,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:d,compactionEvents:x}),S=await Zr({entries:S,contextStore:d,compactionEvents:x}),S=await Qr({entries:S,contextStore:d,compactionEvents:x,dataDir:f,sessionId:p,sessionStoreName:m,sessionPathScope:h}),!o)return{messages:Ar(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:J(S),compacted:!1},compactionEvents:x};let C=d?.getSnapshot(),w=Math.max(1e3,Math.floor(r*.7)),T=si({entries:t,workingEntries:S,pendingUserMessage:s,checkpoint:C?.compaction.modelUsage}).projectedInputTokens>=w,E=C?.compaction.consecutiveAutocompactFailures??0;if(!T||E>=3)return{messages:Ar(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:J(S),compacted:!1},compactionEvents:x};let{toKeep:D,toSummarise:O}=ur(S,r);if(O.length===0)return{messages:Ar(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:J(S),compacted:!1},compactionEvents:x};let k=new Date().toISOString();try{let e=C?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await ir({entries:O,llm:i,previousSummary:g,signal:c,hooks:l,hookCtx:u}),r={role:`compaction`,content:t,keptCount:D.length,droppedCount:O.length,timestamp:k};return await d?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:k}),x.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${O.length} entries with session memory`:`Autocompact summarised ${O.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,J(O)),affectedEntries:O.length,snapshotVersion:2}),{messages:Ar(dr(D),n),priorSummary:t,compactionEntry:r,stats:{originalCount:y,keptCount:D.length,estimatedTokens:J(D),compacted:!0},compactionEvents:x}}catch{return await d?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:k}),{messages:Ar(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:J(S),compacted:!1},compactionEvents:[...x,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function Yr(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=J(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&ai(t)>=3;if(!u&&!d)return n??l?.summary;let f=await ir({entries:t,llm:r,previousSummary:n??l?.summary,instructions:[`Produce a durable session memory for future compaction and resume.`,`If skill_load results are present, do not restate or reconstruct SKILL.md instructions.`,`Record only that the skill was loaded and that it must be reloaded with skill_load if its full content is not visible.`].join(` `),signal:a,hooks:o,hookCtx:s}),p={version:1,summary:f,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:c,trigger:u?`threshold`:`autocompact`};return await i.setSessionMemory(p),f}async function Xr(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(ei).length<=n)return t;let c=n,l=[],u=0,d=0;for(let e=t.length-1;e>=0;--e){let n=t[e];if(!ei(n)){l.push(n);continue}if(c>0&&n.content.length<=r){--c,l.push(n);continue}let i=n.toolResultRef?.preview?.trim()||n.content.slice(0,r).trim(),s=ti(n)?ni(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
26
- `);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),dr(l.reverse())}async function Zr(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-36e5,a=0,o=0,s=[];for(let e of t){if(!ei(e)){s.push(e);continue}let t=Date.parse(e.timestamp);if(!(t>0&&t<i)){s.push(e);continue}let r=ti(e)?ni(e):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${e.toolName}`,`Preview:\n${e.toolResultRef?.preview?.trim()||e.content.slice(0,400).trim()}`].join(`
27
- `);r!==e.content&&(a+=1,o+=Math.max(0,Math.floor((e.content.length-r.length)/4)),await n?.recordSnip({toolCallId:e.toolCallId,toolName:e.toolName,originalChars:e.content.length,retainedChars:r.length,reason:`microcompact`,createdAt:new Date().toISOString()})),s.push({...e,content:r})}return a===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${a} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:o,affectedEntries:a,snapshotVersion:2}),Xr({entries:s,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Qr(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o,sessionPathScope:s}=e,c={storeName:o,...s},l=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(l.length<=2)return t;let u=l[l.length-2]??t.length,d=[],f=0,p=0,m=0;for(;f<t.length;){if(f>=u||t[f]?.role===`user`){d.push(t[f]),f+=1;continue}let e=f;for(;f<u&&t[f]?.role!==`user`;)f+=1;let r=t.slice(e,f),o=r.filter(ei).filter(e=>qr.has(e.toolName)),s=o.reduce((e,t)=>e+t.content.length,0);if(o.length<3||s<1500){d.push(...r);continue}let l=$r(r,o),h=new Date().toISOString(),g={role:`assistant`,content:l,timestamp:h};d.push(g),p+=r.length,m+=Math.max(0,Math.floor(J(r)-J([g])));let _={id:Be(),layer:`L5`,startEntryIndex:e,endEntryIndex:f-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:m,createdAt:h};await n?.recordCollapse(_),i&&a&&await ci(i,a,_,c)}return p>0&&r.push({type:`compaction`,reason:`Collapsed ${p} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:m,affectedEntries:p,snapshotVersion:2}),d}function $r(e,t){let n=[...new Set(t.map(e=>e.toolName))],r=t.slice(-3).map(e=>`- ${e.toolName}: ${(e.toolResultRef?.preview||e.content).slice(0,180).trim()}`).join(`
21
+ `)}function mr(e){let t=hr(e),n=t.name??`<skill-name>`,r=t.path,i=r?`skill_load(name="${n}", skillPath="${r}")`:`skill_load(name="${n}")`;return[`[skill content folded] skill_load result for "${n}" is not a reliable source for future instructions.`,r?`Original path: ${r}`:``,`If this skill is needed later, call ${i} again.`,`Do not summarize, infer, or reconstruct SKILL.md instructions from this history.`].filter(Boolean).join(`
22
+ `)}function hr(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=gr(t);if(e.name||e.path)return e}return{}}function gr(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function _r(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=lr(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function vr(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 yr(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=br(t),l=c>=0?t[c].content:void 0,u=vr(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}=_r(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:J(u)}:{status:`compacted`,entry:{role:`compaction`,content:await dr({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:J(d)}}function br(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const xr=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
23
+ `),Sr=[`.aimax/new.txt`];async function Cr(e){try{return(await ke(e,`utf-8`)).trim()||null}catch{return null}}async function wr(e){for(let t of Sr){let n=await Cr(Ae(e,t));if(n)return n}return await Cr(`/aimax/new.txt`)||xr}async function Tr(e){return{kind:`reply`,text:await wr(e)}}function Er(){return{kind:`reply`,text:`✅ Session reset.`}}function Dr(e){let t=Ar(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?jr(r):null,a=n??i?.text,o=a?Qn(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Mr(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Nr(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Or(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=sr({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:Mr(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Nr(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function kr(e){let t=Or(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 Un({replyText:(t.action===`reset`?Er():await Tr(e.runParams.dataDir)).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 Un({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 yr({entries:e.runParams.channel===`CRON`?[]:await r(e.runParams.dataDir,e.sessionId,q(e.runParams)),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 Un({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 Ar(e){return typeof e.message==`string`}function jr(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 Mr(e,t){let n=jr(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 Nr(e){return typeof e==`string`?e:JSON.stringify(e)}function Pr(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 Fr=[`If you need content beyond this preview, do not load the full output into the parent context.`,`Use subagent_spawn to inspect the Full output file and return only a concise, query-focused summary.`,`Pass the Full output path, note that it is relative to dataDir when not absolute, and include the current question or search target in the subagent task.`],Ir={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Lr(e,t){return e.map(e=>Rr(e,t))}function Rr(e,t){let n=new Date(e.timestamp).getTime();if(zr(e))return{role:`user`,content:e.content,timestamp:n};if(Br(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:Ir,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:Vr(r)}],isError:r.isError,timestamp:n}}function zr(e){return e.role===`user`}function Br(e){return e.role===`assistant`}function Vr(e){if(!e.toolResultRef)return e.content;let t=e.toolResultRef.preview.trimEnd(),n=[`[tool result persisted] ${e.toolResultRef.toolName} (${e.toolResultRef.originalChars} chars).`,`Full output: ${e.toolResultRef.storagePath}`,`Instruction:`,...Fr];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
24
+ `)}const Hr=[`If you need content beyond this preview, do not load the full output into the parent context.`,`Use subagent_spawn to inspect the Full output file and return only a concise, query-focused summary.`,`Pass the Full output path, note that it is relative to dataDir when not absolute, and include the current question or search target in the subagent task.`];async function Ur(e){let t=O(e.dataDir,e.sessionId,e),n=new Map,r=new Map,i=[],a=[],o=[],s,u,d=0,f,p,m=await Jr(t);for(let e of m.readStates)n.set(Wr(e.path,e.offset,e.limit),e);for(let e of m.toolResults)r.set(e.toolCallId,e);i.push(...m.compaction.budgets),a.push(...m.compaction.snips),o.push(...m.compaction.collapseSpans),s=m.compaction.sessionMemory,u=m.compaction.modelUsage,d=m.compaction.consecutiveAutocompactFailures,f=m.compaction.lastCompactionAt,p=m.compaction.lastCompactionLayer;let h=async()=>{let c={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:s,modelUsage:u,budgets:i.slice(-200),snips:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:d,lastCompactionAt:f,lastCompactionLayer:p}};await B.mkdir(V.dirname(t),{recursive:!0});let m=e.encryptSessions??!1;await l(t,JSON.stringify(c,null,2),m)};return{async findReusableRead(e,t,r){let i=Wr(e,t,r),a=n.get(i);if(!a)return null;let o=await Kr(e);return o===null||o!==a.lastModifiedMs?(n.delete(i),await h(),null):a},async recordRead(e){let t=new Date().toISOString(),r={path:e.path,offset:e.offset,limit:e.limit,contentHash:qr(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await Kr(e.path)??Date.now()};return n.set(Wr(e.path,e.offset,e.limit),r),await h(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())Gr(i.path)===Gr(e)&&(n.delete(r),t=!0);t&&await h()},async persistToolResult(t){let n=t.thresholdChars??12e3;if(t.content.length<=n)return{content:t.content};let a=t.previewChars??2e3,o=c(e.dataDir,e.sessionId,e),s=`${t.toolCallId}.txt`,u=V.join(o,s);await B.mkdir(o,{recursive:!0});let d=e.encryptSessions??!1;await l(u,t.content,d);let m=V.relative(e.dataDir,u).split(V.sep).join(`/`),g=Qr(t.content,a),_={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:m,preview:g,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(_.toolCallId,_),i.push({toolCallId:_.toolCallId,toolName:_.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:g.length,strategy:`persist`,createdAt:_.createdAt}),f=_.createdAt,p=`L2`,await h(),{content:Zr(_),reference:_}},async recordSnip(e){a.push(e),f=e.createdAt,p=e.reason===`context_dedup`?`L1`:e.reason===`microcompact`?`L4`:`L3`,await h()},async recordCollapse(e){o.push(e),f=e.createdAt,p=e.layer,await h()},async setSessionMemory(t){s=t,await $r(e.dataDir,e.sessionId,t,e),await h()},async recordModelUsage(e){u=e,await h()},async recordAutocompactResult(e){d=e.failed?d+1:0,f=e.timestamp,p=`L6`,await h()},getSnapshot(){return{version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:s,modelUsage:u,budgets:i.slice(-200),snips:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:d,lastCompactionAt:f,lastCompactionLayer:p}}}}}function Wr(e,t,n){return`${Gr(e)}::${t??``}::${n??``}`}function Gr(e){return V.normalize(e)}async function Kr(e){try{return(await B.stat(e)).mtimeMs}catch{return null}}function qr(e){return qe(`sha1`).update(e).digest(`hex`)}async function Jr(e){try{let t=await b(e);if(t===null)return Yr();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?Yr():{version:2,updatedAt:typeof n.updatedAt==`string`?n.updatedAt:new Date(0).toISOString(),readStates:Array.isArray(n.readStates)?n.readStates:[],toolResults:Array.isArray(n.toolResults)?n.toolResults:[],compaction:{sessionMemory:n.compaction?.sessionMemory,modelUsage:Xr(n.compaction?.modelUsage),budgets:Array.isArray(n.compaction?.budgets)?n.compaction.budgets:[],snips:Array.isArray(n.compaction?.snips)?n.compaction.snips:[],collapseSpans:Array.isArray(n.compaction?.collapseSpans)?n.compaction.collapseSpans:[],consecutiveAutocompactFailures:typeof n.compaction?.consecutiveAutocompactFailures==`number`?n.compaction.consecutiveAutocompactFailures:0,lastCompactionAt:typeof n.compaction?.lastCompactionAt==`string`?n.compaction.lastCompactionAt:void 0,lastCompactionLayer:n.compaction?.lastCompactionLayer===`L1`||n.compaction?.lastCompactionLayer===`L2`||n.compaction?.lastCompactionLayer===`L3`||n.compaction?.lastCompactionLayer===`L4`||n.compaction?.lastCompactionLayer===`L5`||n.compaction?.lastCompactionLayer===`L6`?n.compaction.lastCompactionLayer:void 0}}}catch{return Yr()}}function Yr(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Xr(e){if(!e||typeof e!=`object`)return;let t=e;if(!(t.version!==1||typeof t.model!=`string`||typeof t.inputTokens!=`number`||typeof t.outputTokens!=`number`||typeof t.totalTokens!=`number`||typeof t.coveredTranscriptEntryCount!=`number`||typeof t.recordedAt!=`string`))return{version:1,model:t.model,inputTokens:Math.max(0,Math.floor(t.inputTokens)),outputTokens:Math.max(0,Math.floor(t.outputTokens)),totalTokens:Math.max(0,Math.floor(t.totalTokens)),coveredTranscriptEntryCount:Math.max(0,Math.floor(t.coveredTranscriptEntryCount)),recordedAt:t.recordedAt}}function Zr(e){let t=e.preview.length<e.originalChars?`
25
+ ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...Hr,`Preview:`,e.preview+t].join(`
26
+ `)}function Qr(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
27
+ `),r=n>t*.5?n:t;return e.slice(0,r)}async function $r(e,t,n,r){let i=m(e,t,r);await B.mkdir(V.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await l(i,JSON.stringify(n,null,2),a)}const ei=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function ti(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,signal:c,hooks:l,hookCtx:u,contextStore:d,dataDir:f,sessionId:p,sessionStoreName:m,sessionPathScope:h}=e,g,_=pi(t),v=_>=0?t.slice(_+1):t;_>=0&&(g=t[_].content);let y=t.length,b=vr(Pr(v,a)),x=[];d&&(g=await ni({entries:b,existingSummary:g,llm:i,contextStore:d,signal:c,hooks:l,hookCtx:u}));let S=b;if(S=await ri({entries:S,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:d,compactionEvents:x}),S=await ii({entries:S,contextStore:d,compactionEvents:x}),S=await ai({entries:S,contextStore:d,compactionEvents:x,dataDir:f,sessionId:p,sessionStoreName:m,sessionPathScope:h}),!o)return{messages:Lr(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:J(S),compacted:!1},compactionEvents:x};let C=d?.getSnapshot(),w=Math.max(1e3,Math.floor(r*.7)),T=mi({entries:t,workingEntries:S,pendingUserMessage:s,checkpoint:C?.compaction.modelUsage}).projectedInputTokens>=w,E=C?.compaction.consecutiveAutocompactFailures??0;if(!T||E>=3)return{messages:Lr(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:J(S),compacted:!1},compactionEvents:x};let{toKeep:D,toSummarise:O}=_r(S,r);if(O.length===0)return{messages:Lr(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:J(S),compacted:!1},compactionEvents:x};let k=new Date().toISOString();try{let e=C?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await dr({entries:O,llm:i,previousSummary:g,signal:c,hooks:l,hookCtx:u}),r={role:`compaction`,content:t,keptCount:D.length,droppedCount:O.length,timestamp:k};return await d?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:k}),x.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${O.length} entries with session memory`:`Autocompact summarised ${O.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,J(O)),affectedEntries:O.length,snapshotVersion:2}),{messages:Lr(vr(D),n),priorSummary:t,compactionEntry:r,stats:{originalCount:y,keptCount:D.length,estimatedTokens:J(D),compacted:!0},compactionEvents:x}}catch{return await d?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:k}),{messages:Lr(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:J(S),compacted:!1},compactionEvents:[...x,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function ni(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=J(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&fi(t)>=3;if(!u&&!d)return n??l?.summary;let f=await dr({entries:t,llm:r,previousSummary:n??l?.summary,instructions:[`Produce a durable session memory for future compaction and resume.`,`If skill_load results are present, do not restate or reconstruct SKILL.md instructions.`,`Record only that the skill was loaded and that it must be reloaded with skill_load if its full content is not visible.`].join(` `),signal:a,hooks:o,hookCtx:s}),p={version:1,summary:f,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:c,trigger:u?`threshold`:`autocompact`};return await i.setSessionMemory(p),f}async function ri(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(si).length<=n)return t;let c=n,l=[],u=0,d=0;for(let e=t.length-1;e>=0;--e){let n=t[e];if(!si(n)){l.push(n);continue}if(c>0&&n.content.length<=r){--c,l.push(n);continue}let i=n.toolResultRef?.preview?.trim()||n.content.slice(0,r).trim(),s=ci(n)?li(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
28
+ `);if(s===n.content){l.push(n);continue}u+=1,d+=Math.max(0,Math.floor((n.content.length-s.length)/4));let f=new Date().toISOString();await o?.recordSnip({toolCallId:n.toolCallId,toolName:n.toolName,originalChars:n.content.length,retainedChars:s.length,reason:a===`microcompact`?`microcompact`:`history_snip`,createdAt:f}),l.push({...n,content:s})}return u>0&&s.push({type:`compaction`,reason:`${a===`snip`?`Snip compacted`:`Microcompacted`} ${u} tool results`,layer:i,strategy:a,estimatedTokensFreed:d,affectedEntries:u,snapshotVersion:2}),vr(l.reverse())}async function ii(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-36e5,a=0,o=0,s=[];for(let e of t){if(!si(e)){s.push(e);continue}let t=Date.parse(e.timestamp);if(!(t>0&&t<i)){s.push(e);continue}let r=ci(e)?li(e):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${e.toolName}`,`Preview:\n${e.toolResultRef?.preview?.trim()||e.content.slice(0,400).trim()}`].join(`
29
+ `);r!==e.content&&(a+=1,o+=Math.max(0,Math.floor((e.content.length-r.length)/4)),await n?.recordSnip({toolCallId:e.toolCallId,toolName:e.toolName,originalChars:e.content.length,retainedChars:r.length,reason:`microcompact`,createdAt:new Date().toISOString()})),s.push({...e,content:r})}return a===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${a} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:o,affectedEntries:a,snapshotVersion:2}),ri({entries:s,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function ai(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o,sessionPathScope:s}=e,c={storeName:o,...s},l=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(l.length<=2)return t;let u=l[l.length-2]??t.length,d=[],f=0,p=0,m=0;for(;f<t.length;){if(f>=u||t[f]?.role===`user`){d.push(t[f]),f+=1;continue}let e=f;for(;f<u&&t[f]?.role!==`user`;)f+=1;let r=t.slice(e,f),o=r.filter(si).filter(e=>ei.has(e.toolName)),s=o.reduce((e,t)=>e+t.content.length,0);if(o.length<3||s<1500){d.push(...r);continue}let l=oi(r,o),h=new Date().toISOString(),g={role:`assistant`,content:l,timestamp:h};d.push(g),p+=r.length,m+=Math.max(0,Math.floor(J(r)-J([g])));let _={id:Je(),layer:`L5`,startEntryIndex:e,endEntryIndex:f-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:m,createdAt:h};await n?.recordCollapse(_),i&&a&&await hi(i,a,_,c)}return p>0&&r.push({type:`compaction`,reason:`Collapsed ${p} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:m,affectedEntries:p,snapshotVersion:2}),d}function oi(e,t){let n=[...new Set(t.map(e=>e.toolName))],r=t.slice(-3).map(e=>`- ${e.toolName}: ${(e.toolResultRef?.preview||e.content).slice(0,180).trim()}`).join(`
28
30
  `),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
29
31
  `);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
30
32
 
31
- `)}function ei(e){return e.role===`tool_result`}function ti(e){return e.toolName===`skill_load`}function ni(e){let t=ri(e),n=t.name||`<skill-name>`,r=t.path?`skill_load(name="${n}", skillPath="${t.path}")`:`skill_load(name="${n}")`;return[`[skill content folded] The previous skill_load result for "${n}" was folded out of model-visible context.`,`The complete SKILL.md content is no longer available in the current prompt.`,`Before using this skill again, call ${r} again. Do not infer or reconstruct the skill instructions from memory or summaries.`,t.path?`Original path: ${t.path}`:``].filter(Boolean).join(`
32
- `)}function ri(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=ii(t);if(e.name||e.path)return e}return{}}function ii(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function ai(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function oi(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function si(e){let t=e.pendingUserMessage?.trim()?J([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=J(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=J(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function ci(e,t,n,r){let i=E(e,t,r);await B.mkdir(V.dirname(i),{recursive:!0}),await B.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function li(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await Ir({dataDir:e.dataDir,sessionId:e.sessionId,...t});return{async getReusableRead(e,t,r){let i=await n.findReusableRead(e,t,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await n.recordRead(e)},async invalidateReadPath(e){await n.invalidatePath(e)},persistToolResult(e){return n.persistToolResult(e)},async recordModelUsage(e){await n.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(t){return Jr({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function ui(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName}):Jr({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName})}var di=class extends Error{isHitlPause=!0;constructor(e,t,n,r=!1){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.transparentPause=r,this.name=`HitlPauseSignal`}};function Y(e){return!!(e instanceof di||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const fi=U.Object({command:U.String({description:`Shell command to execute`}),workdir:U.Optional(U.String({description:`Working directory (relative to workspace root)`})),env:U.Optional(U.Record(U.String(),U.String())),timeout:U.Optional(U.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:U.Optional(U.Number({description:`Wait this many milliseconds before returning running state`})),background:U.Optional(U.Boolean({description:`Return immediately with running session`}))});function pi(e,t,n){return Math.max(t,Math.min(n,e))}function mi(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function hi(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:pi(Math.floor(e),0,12e4)}function gi(e,t){if(!t?.trim())return e;let n=V.isAbsolute(t)?V.normalize(t):V.normalize(V.join(e,t));if(!n.startsWith(e+V.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function _i(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 vi(e){return bi({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
33
- `)}function yi(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function bi(e){let t=yi(e.stdout),n=e.stderr.trim();if(e.exitCode!==void 0&&e.exitCode!==0){let t=`Exit code: ${e.exitCode===null?`null`:e.exitCode}`;n=n.length>0?`${n}\n${t}`:t}return[t.length>0?t:`(no output)`,n,e.backgroundInfo?.trim()||``].filter(e=>e.length>0)}function xi(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands. Prefer modern tools: rg (not grep), fd (not find), jq (not python/awk) for JSON. For long-running tasks set background:true and poll with process tool.`,parameters:fi,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=gi(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=mi(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,hi(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:_i(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}};let d=e.registry.readOutput(l.sessionId,e.scopeKey),f=d?bi({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[vi(l)],p=yi(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
34
- `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Si=U.Object({action:U.String({description:`Process action: list | poll | log | kill`}),sessionId:U.Optional(U.String({description:`Session id for non-list actions`})),offset:U.Optional(U.Number({description:`Log line offset (0-based)`})),limit:U.Optional(U.Number({description:`Maximum lines to return`})),timeout:U.Optional(U.Number({description:`Poll wait time in milliseconds`}))});function Ci(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function wi(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Ti(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:Si,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(`
35
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return wi(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Ci(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`}}:wi(`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}}:wi(`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}}:wi(`No session found for ${i}`)}return wi(`Unsupported action: ${n.action}`)}}}const Ei=2e5;function Di(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Oi(e,t){let n=e+t;return n.length<=Ei?{text:n,truncated:!1}:{text:n.slice(-Ei),truncated:!0}}function ki(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Oi(e.output,r);e.output=i.text;let a=Oi(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function X(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:Di(e.output),stdoutTail:Di(e.stdout),stderrTail:Di(e.stderr),outputTruncated:e.outputTruncated}}function Ai(e,t){return t?e.scopeKey===t:!0}function ji(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Mi(e){return e?e.split(/\r?\n/):[]}function Ni(e){let t=Mi(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=ji(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(`
36
- `);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 Pi(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Fi(){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),Pi(e))};return{start(t){let n=Ue(`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:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>ki(o,`stdout`,e)),n.stderr.on(`data`,e=>ki(o,`stderr`,e));let s=ji(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,ki(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),ki(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),X(o)},get(e,t){let n=r(e);return!n||!Ai(n,t)?null:X(n)},list(n){return[...e.values(),...t.values()].filter(e=>Ai(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>X(e))},async wait(e,t,n){let i=r(e);if(!i||!Ai(i,t))return null;if(i.status!==`running`)return X(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||!Ai(a,t)?null:X(a)},readLog(e){let t=r(e.sessionId);return!t||!Ai(t,e.scopeKey)?null:Ni({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Ai(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!Ai(n,t))return null;if(n.status!==`running`)return X(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?X(i):null}}}function Ii(e){return xi({workspaceDir:e,registry:Fi(),scopeKey:e})}const Li=5*1024*1024,Ri=2e3;async function zi(e,t){e&&await e(t).catch(()=>{})}function Bi(e,t){return V.isAbsolute(e)?V.normalize(e):V.normalize(V.join(t,e))}const Vi=U.Object({path:U.String({description:`File path (relative to workspace or absolute)`}),offset:U.Optional(U.Number({description:`Line offset (1-based, default: 1)`})),limit:U.Optional(U.Number({description:`Maximum lines to read (default: 2000)`}))});function Hi(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Vi,async execute(n,r){let i;try{i=Bi(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await B.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await We(s,s.length))return{content:[{type:`text`,text:`Error: read_file only supports text files. ${r.path} appears to be binary; use another tool or install an appropriate skill to handle it.`}],details:{content:``,lines:0,truncated:!1}};if(o.length>Li){let e=o.slice(0,Li).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Li} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
37
- `),l=Math.max(1,r.offset??1),u=Math.min(Ri,r.limit??Ri),d=c.slice(l-1,l-1+u),f=d.length<c.length-(l-1),p=d.map((e,t)=>`${(l+t).toString().padStart(4)} ${e}`).join(`
38
- `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
39
- `),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
40
- `),lines:d.length,truncated:f}}}}}const Ui=U.Object({path:U.String({description:`File path (relative to workspace or absolute)`}),content:U.String({description:`File content to write`})});function Wi(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Ui,async execute(r,i){let a;try{a=Bi(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await B.mkdir(V.dirname(a),{recursive:!0}),await B.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await zi(n,{type:`write`,operation:`write_file`,file:a,content:i.content,toolCallId:r,toolName:`write_file`})}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:a}}}return{content:[{type:`text`,text:`File written: ${i.path}`}],details:{path:a}}}}}const Gi=U.Object({path:U.String({description:`File path (relative to workspace or absolute)`}),old_string:U.String({description:`Exact text to replace`}),new_string:U.String({description:`Replacement text`})});function Ki(e,t,n){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Gi,async execute(r,i){let a;try{a=Bi(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await B.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await B.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await zi(n,{type:`edit`,operation:`edit_file`,file:a,content:s,toolCallId:r,toolName:`edit_file`}),{content:[{type:`text`,text:`File edited: ${i.path}`}],details:{path:a,occurrences:1}}}}}const qi=U.Object({path:U.Optional(U.String({description:`Directory path (default: workspace root)`}))});function Ji(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:qi,async execute(t,n){let r=n.path??`.`,i;try{i=Bi(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await B.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(`
41
- `)||`(empty directory)`}],details:{entries:a}}}}}const Yi=U.Object({input:U.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Xi(e,t){let n=V.isAbsolute(e)?V.normalize(e):V.normalize(V.join(t,e));if(!n.startsWith(t+V.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Zi(e,t){let n=V.relative(t,e);return!n||n===``?V.basename(e):n.startsWith(`..`)||V.isAbsolute(n)?e:n}async function Qi(e){await B.mkdir(V.dirname(e),{recursive:!0})}async function $i(e,t){e&&await e(t).catch(()=>{})}function ea(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(`
42
- `)}function ta(e,t={}){return{name:`apply_patch`,label:`apply_patch`,description:`Apply a patch to one or more files using the apply_patch format. The input should include *** Begin Patch and *** End Patch markers.`,parameters:Yi,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=ra(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let r of a.hunks){if(r.kind===`add`){let i=Xi(r.path,e);await Qi(i),await B.writeFile(i,r.contents,`utf-8`),await $i(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),na(o,s,`added`,Zi(i,e));continue}if(r.kind===`delete`){let i=Xi(r.path,e);await B.rm(i,{force:!0,recursive:!1}),await $i(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),na(o,s,`deleted`,Zi(i,e));continue}let i=Xi(r.path,e),a=await sa(i,r.chunks);if(r.movePath){let c=Xi(r.movePath,e);await Qi(c),await B.writeFile(c,a,`utf-8`),await B.rm(i,{force:!0,recursive:!1}),await $i(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),na(o,s,`modified`,Zi(c,e))}else await B.writeFile(i,a,`utf-8`),await $i(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),na(o,s,`modified`,Zi(i,e))}return{content:[{type:`text`,text:ea(o)}],details:{summary:o}}}catch(e){if(Y(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function na(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function ra(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);ia(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=aa(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function ia(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 aa(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}=oa(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 oa(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 sa(e,t){let n=(await B.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
43
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=la(n,ca(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
44
- `)}function ca(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=ua(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=ua(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=ua(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
45
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function la(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 ua(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(da(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(da(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(da(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(da(e,t,n,e=>fa(e.trim())))return n;return null}function da(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 fa(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 pa(e){return V.join(e,`.aimax`)}function ma(e){return V.join(pa(e),`MEMORY.md`)}async function Z(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function ha(e,t){let n=pa(e),r=I({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?{provider:r.provider,resolvedProviderId:r.registration.id,source:`plugin`}:{provider:D({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function ga(e){return ee(pa(e))}async function _a(e){try{return await B.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function va(e){return _a(ma(e))}async function ya(e,t,n){let{provider:r}=ha(e,n);return await r.search(t)}async function ba(e,t,n,r,i){try{let{provider:a}=ha(e,i);return await a.getLines(t,n,r)}catch{return null}}async function xa(e,t,n){let{provider:r,resolvedProviderId:i}=ha(e,n);await r.append(t),await Z(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}async function Sa(e,t,n,r){let{provider:i,resolvedProviderId:a}=ha(e,r),o=n===`session`&&r?.sessionId?`session-${r.sessionId}.md`:`${new Date().toISOString().slice(0,10)}.md`;if(i.appendRecent){await i.appendRecent(t,n),await Z(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Z(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});return}await Z(i,r?.onMemoryChanged,{reason:`appendRecent_fallback`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});let s=new Date().toISOString().slice(0,10),c=n===`session`&&r?.sessionId?`[session:${r.sessionId}]`:`[${s}]`;await i.append(`${c} ${t}\n`),await Z(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Z(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Q(e,t,n,r){let{provider:i,resolvedProviderId:a}=ha(e,r);await i.updateFile(t,n),await Z(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Ca(e,t,n){let{provider:r,resolvedProviderId:i}=ha(e,n);await r.deleteFile(t),await Z(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const wa=U.Object({query:U.String({description:`Search query (case-insensitive substring match)`})});function Ta(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search durable long-term memory docs (for stable facts, preferences, decisions, and project constraints). Use this for persistent knowledge retrieval, not for reconstructing past chat timelines. If the user asks what happened in previous sessions, use session_search instead.`,parameters:wa,async execute(n,r){let i=(await ya(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({id:e.id,file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.id?`[${e.id}] `:``}${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
46
- `)}],details:{matches:i}}}}}const Ea=U.Object({file:U.String({description:`Memory file path (from memory_search results)`}),start_line:U.Number({description:`Start line number (1-based)`}),end_line:U.Number({description:`End line number (1-based)`})});function Da(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read a specific memory entry's content after memory_search identifies the target path and range`,parameters:Ea,async execute(n,r){let i=await ba(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(`
47
- `)||`(empty)`}],details:{lines:i}}}}}const Oa=U.Object({content:U.String({description:`Content to write to memory`})});function ka(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append a small new fact or note to MEMORY.md without replacing existing sections`,parameters:Oa,async execute(n,r){try{return await xa(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 Aa=U.Object({section:U.Optional(U.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:U.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:U.Union([U.Literal(`append`),U.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function ja(e,t){return{name:`memory_write`,label:`Write Memory`,description:`Write or update a section in long-term memory (MEMORY.md). Use for durable facts, preferences, decisions, and project constraints. If section is omitted, appends a flat unstructured note. Use mode "append" to add entries and "replace" to rewrite a section.`,parameters:Aa,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await xa(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}let o=`${`## ${i}`}\n${r.content.trimEnd()}\n`;try{return a===`replace`?await Q(e,`MEMORY.md`,Ma(await va(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await xa(e,o,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: section "${i}" (${a})`}],details:{section:i,mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}}}}function Ma(e,t,n){let r=e.split(`
33
+ `)}function si(e){return e.role===`tool_result`}function ci(e){return e.toolName===`skill_load`}function li(e){let t=ui(e),n=t.name||`<skill-name>`,r=t.path?`skill_load(name="${n}", skillPath="${t.path}")`:`skill_load(name="${n}")`;return[`[skill content folded] The previous skill_load result for "${n}" was folded out of model-visible context.`,`The complete SKILL.md content is no longer available in the current prompt.`,`Before using this skill again, call ${r} again. Do not infer or reconstruct the skill instructions from memory or summaries.`,t.path?`Original path: ${t.path}`:``].filter(Boolean).join(`
34
+ `)}function ui(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=di(t);if(e.name||e.path)return e}return{}}function di(e){let t=e.trim();if(!t)return{};try{let e=JSON.parse(t);if(e.success===!0)return{name:typeof e.name==`string`?e.name:void 0,path:typeof e.path==`string`?e.path:void 0}}catch{}let n=t.match(/\[skill content persisted\] skill_load output for "([^"]+)"/)?.[1],r=t.match(/\[skill content folded\] The previous skill_load result for "([^"]+)"/)?.[1],i=t.match(/^Original path: (.+)$/m)?.[1]?.trim();return{name:n??r,path:i}}function fi(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function pi(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function mi(e){let t=e.pendingUserMessage?.trim()?J([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=J(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=J(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function hi(e,t,n,r){let i=M(e,t,r);await B.mkdir(V.dirname(i),{recursive:!0}),await B.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function gi(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await Ur({dataDir:e.dataDir,sessionId:e.sessionId,...t});return{async getReusableRead(e,t,r){let i=await n.findReusableRead(e,t,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await n.recordRead(e)},async invalidateReadPath(e){await n.invalidatePath(e)},persistToolResult(e){return n.persistToolResult(e)},async recordModelUsage(e){await n.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(t){return ti({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function _i(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName}):ti({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName})}var vi=class extends Error{isHitlPause=!0;constructor(e,t,n,r=!1){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.transparentPause=r,this.name=`HitlPauseSignal`}};function Y(e){return!!(e instanceof vi||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const yi=U.Object({command:U.String({description:`Shell command to execute`}),workdir:U.Optional(U.String({description:`Working directory (relative to workspace root)`})),env:U.Optional(U.Record(U.String(),U.String())),timeout:U.Optional(U.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:U.Optional(U.Number({description:`Wait this many milliseconds before returning running state`})),background:U.Optional(U.Boolean({description:`Return immediately with running session`}))});function bi(e,t,n){return Math.max(t,Math.min(n,e))}function xi(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Si(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:bi(Math.floor(e),0,12e4)}function Ci(e,t){if(!t?.trim())return e;let n=V.isAbsolute(t)?V.normalize(t):V.normalize(V.join(e,t));if(!n.startsWith(e+V.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function wi(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 Ti(e){return Di({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
35
+ `)}function Ei(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Di(e){let t=Ei(e.stdout),n=e.stderr.trim();if(e.exitCode!==void 0&&e.exitCode!==0){let t=`Exit code: ${e.exitCode===null?`null`:e.exitCode}`;n=n.length>0?`${n}\n${t}`:t}return[t.length>0?t:`(no output)`,n,e.backgroundInfo?.trim()||``].filter(e=>e.length>0)}function Oi(e){return{name:`exec`,label:`Exec`,description:`Execute shell commands. Prefer modern tools: rg (not grep), fd (not find), jq (not python/awk) for JSON. For long-running tasks set background:true and poll with process tool.`,parameters:yi,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=Ci(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=xi(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,Si(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:wi(l)}],details:{status:`running`,sessionId:l.sessionId,command:l.command,cwd:l.cwd,pid:l.pid}};let d=e.registry.readOutput(l.sessionId,e.scopeKey),f=d?Di({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[Ti(l)],p=Ei(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
36
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const ki=U.Object({action:U.String({description:`Process action: list | poll | log | kill`}),sessionId:U.Optional(U.String({description:`Session id for non-list actions`})),offset:U.Optional(U.Number({description:`Log line offset (0-based)`})),limit:U.Optional(U.Number({description:`Maximum lines to return`})),timeout:U.Optional(U.Number({description:`Poll wait time in milliseconds`}))});function Ai(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function ji(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Mi(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:ki,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(`
37
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return ji(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Ai(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`}}:ji(`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}}:ji(`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}}:ji(`No session found for ${i}`)}return ji(`Unsupported action: ${n.action}`)}}}const Ni=2e5;function Pi(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Fi(e,t){let n=e+t;return n.length<=Ni?{text:n,truncated:!1}:{text:n.slice(-Ni),truncated:!0}}function Ii(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Fi(e.output,r);e.output=i.text;let a=Fi(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Li(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:Pi(e.output),stdoutTail:Pi(e.stdout),stderrTail:Pi(e.stderr),outputTruncated:e.outputTruncated}}function X(e,t){return t?e.scopeKey===t:!0}function Ri(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function zi(e){return e?e.split(/\r?\n/):[]}function Bi(e){let t=zi(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Ri(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(`
38
+ `);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 Vi(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Hi(){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),Vi(e))};return{start(t){let n=Ze(`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:Je(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:n,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:a,resolveDone:r};e.set(o.sessionId,o),n.stdout.on(`data`,e=>Ii(o,`stdout`,e)),n.stderr.on(`data`,e=>Ii(o,`stderr`,e));let s=Ri(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Ii(o,`stderr`,Buffer.from(`\n[Timed out after ${s}s]\n`)),o.child.kill(`SIGTERM`),o.killTimer=setTimeout(()=>{(o.status===`running`||o.status===`timeout`)&&o.child.kill(`SIGKILL`)},1e3))},s*1e3),n.on(`error`,e=>{i(o,()=>{o.status===`running`&&(o.status=`failed`),Ii(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),Li(o)},get(e,t){let n=r(e);return!n||!X(n,t)?null:Li(n)},list(n){return[...e.values(),...t.values()].filter(e=>X(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Li(e))},async wait(e,t,n){let i=r(e);if(!i||!X(i,t))return null;if(i.status!==`running`)return Li(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||!X(a,t)?null:Li(a)},readLog(e){let t=r(e.sessionId);return!t||!X(t,e.scopeKey)?null:Bi({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!X(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!X(n,t))return null;if(n.status!==`running`)return Li(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?Li(i):null}}}function Ui(e){return Oi({workspaceDir:e,registry:Hi(),scopeKey:e})}const Wi=5*1024*1024,Gi=2e3;async function Ki(e,t){e&&await e(t).catch(()=>{})}function qi(e,t){return V.isAbsolute(e)?V.normalize(e):V.normalize(V.join(t,e))}const Ji=U.Object({path:U.String({description:`File path (relative to workspace or absolute)`}),offset:U.Optional(U.Number({description:`Line offset (1-based, default: 1)`})),limit:U.Optional(U.Number({description:`Maximum lines to read (default: 2000)`}))});function Yi(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Ji,async execute(n,r){let i;try{i=qi(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await B.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await Qe(s,s.length))return{content:[{type:`text`,text:`Error: read_file only supports text files. ${r.path} appears to be binary; use another tool or install an appropriate skill to handle it.`}],details:{content:``,lines:0,truncated:!1}};if(o.length>Wi){let e=o.slice(0,Wi).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Wi} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`);v(c)&&(c=y(c));let l=c.split(`
39
+ `),u=Math.max(1,r.offset??1),d=Math.min(Gi,r.limit??Gi),f=l.slice(u-1,u-1+d),p=f.length<l.length-(u-1),m=f.map((e,t)=>`${(u+t).toString().padStart(4)} ${e}`).join(`
40
+ `),h=p?`\n[...${l.length-(u-1+f.length)} more lines]`:``;return await t?.rememberRead({path:i,content:f.join(`
41
+ `),lineCount:f.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:m+h}],details:{content:f.join(`
42
+ `),lines:f.length,truncated:p}}}}}const Xi=U.Object({path:U.String({description:`File path (relative to workspace or absolute)`}),content:U.String({description:`File content to write`})});function Zi(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Xi,async execute(r,i){let a;try{a=qi(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await B.mkdir(V.dirname(a),{recursive:!0}),await B.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await Ki(n,{type:`write`,operation:`write_file`,file:a,content:i.content,toolCallId:r,toolName:`write_file`})}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:a}}}return{content:[{type:`text`,text:`File written: ${i.path}`}],details:{path:a}}}}}const Qi=U.Object({path:U.String({description:`File path (relative to workspace or absolute)`}),old_string:U.String({description:`Exact text to replace`}),new_string:U.String({description:`Replacement text`})});function $i(e,t,n){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Qi,async execute(r,i){let a;try{a=qi(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await B.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await B.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await Ki(n,{type:`edit`,operation:`edit_file`,file:a,content:s,toolCallId:r,toolName:`edit_file`}),{content:[{type:`text`,text:`File edited: ${i.path}`}],details:{path:a,occurrences:1}}}}}const ea=U.Object({path:U.Optional(U.String({description:`Directory path (default: workspace root)`}))});function ta(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:ea,async execute(t,n){let r=n.path??`.`,i;try{i=qi(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await B.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(`
43
+ `)||`(empty directory)`}],details:{entries:a}}}}}const na=U.Object({input:U.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function ra(e,t){let n=V.isAbsolute(e)?V.normalize(e):V.normalize(V.join(t,e));if(!n.startsWith(t+V.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function ia(e,t){let n=V.relative(t,e);return!n||n===``?V.basename(e):n.startsWith(`..`)||V.isAbsolute(n)?e:n}async function aa(e){await B.mkdir(V.dirname(e),{recursive:!0})}async function oa(e,t){e&&await e(t).catch(()=>{})}function sa(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(`
44
+ `)}function ca(e,t={}){return{name:`apply_patch`,label:`apply_patch`,description:`Apply a patch to one or more files using the apply_patch format. The input should include *** Begin Patch and *** End Patch markers.`,parameters:na,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=ua(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let r of a.hunks){if(r.kind===`add`){let i=ra(r.path,e);await aa(i),await B.writeFile(i,r.contents,`utf-8`),await oa(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),la(o,s,`added`,ia(i,e));continue}if(r.kind===`delete`){let i=ra(r.path,e);await B.rm(i,{force:!0,recursive:!1}),await oa(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),la(o,s,`deleted`,ia(i,e));continue}let i=ra(r.path,e),a=await ma(i,r.chunks);if(r.movePath){let c=ra(r.movePath,e);await aa(c),await B.writeFile(c,a,`utf-8`),await B.rm(i,{force:!0,recursive:!1}),await oa(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),la(o,s,`modified`,ia(c,e))}else await B.writeFile(i,a,`utf-8`),await oa(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),la(o,s,`modified`,ia(i,e))}return{content:[{type:`text`,text:sa(o)}],details:{summary:o}}}catch(e){if(Y(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function la(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function ua(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);da(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=fa(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function da(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 fa(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}=pa(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 pa(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 ma(e,t){let n=(await B.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
45
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=ga(n,ha(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
46
+ `)}function ha(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=_a(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=_a(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=_a(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
47
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function ga(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 _a(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(va(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(va(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(va(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(va(e,t,n,e=>ya(e.trim())))return n;return null}function va(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 ya(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 ba(e){return V.join(e,`.aimax`)}function xa(e){return V.join(ba(e),`MEMORY.md`)}async function Z(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function Sa(e,t){let n=ba(e),r=ae({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?{provider:r.provider,resolvedProviderId:r.registration.id,source:`plugin`}:{provider:N({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function Ca(e){return L(ba(e))}async function wa(e){try{return await B.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ta(e){return wa(xa(e))}async function Ea(e,t,n){let{provider:r}=Sa(e,n);return await r.search(t)}async function Da(e,t,n,r,i){try{let{provider:a}=Sa(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Oa(e,t,n){let{provider:r,resolvedProviderId:i}=Sa(e,n);await r.append(t),await Z(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}async function ka(e,t,n,r){let{provider:i,resolvedProviderId:a}=Sa(e,r),o=n===`session`&&r?.sessionId?`session-${r.sessionId}.md`:`${new Date().toISOString().slice(0,10)}.md`;if(i.appendRecent){await i.appendRecent(t,n),await Z(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Z(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});return}await Z(i,r?.onMemoryChanged,{reason:`appendRecent_fallback`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()});let s=new Date().toISOString().slice(0,10),c=n===`session`&&r?.sessionId?`[session:${r.sessionId}]`:`[${s}]`;await i.append(`${c} ${t}\n`),await Z(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Z(i,r?.onMemoryChanged,{reason:`appendRecent_route`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Q(e,t,n,r){let{provider:i,resolvedProviderId:a}=Sa(e,r);await i.updateFile(t,n),await Z(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Aa(e,t,n){let{provider:r,resolvedProviderId:i}=Sa(e,n);await r.deleteFile(t),await Z(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const ja=U.Object({query:U.String({description:`Search query (case-insensitive substring match)`})});function Ma(e,t){return{name:`memory_search`,label:`Memory Search`,description:`Search durable long-term memory docs (for stable facts, preferences, decisions, and project constraints). Use this for persistent knowledge retrieval, not for reconstructing past chat timelines. If the user asks what happened in previous sessions, use session_search instead.`,parameters:ja,async execute(n,r){let i=(await Ea(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({id:e.id,file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.id?`[${e.id}] `:``}${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
48
+ `)}],details:{matches:i}}}}}const Na=U.Object({file:U.String({description:`Memory file path (from memory_search results)`}),start_line:U.Number({description:`Start line number (1-based)`}),end_line:U.Number({description:`End line number (1-based)`})});function Pa(e,t){return{name:`memory_get`,label:`Memory Get`,description:`Read a specific memory entry's content after memory_search identifies the target path and range`,parameters:Na,async execute(n,r){let i=await Da(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(`
49
+ `)||`(empty)`}],details:{lines:i}}}}}const Fa=U.Object({content:U.String({description:`Content to write to memory`})});function Ia(e,t){return{name:`memory_append`,label:`Memory Append`,description:`Append a small new fact or note to MEMORY.md without replacing existing sections`,parameters:Fa,async execute(n,r){try{return await Oa(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 La=U.Object({section:U.Optional(U.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:U.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:U.Union([U.Literal(`append`),U.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Ra(e,t){return{name:`memory_write`,label:`Write Memory`,description:`Write or update a section in long-term memory (MEMORY.md). Use for durable facts, preferences, decisions, and project constraints. If section is omitted, appends a flat unstructured note. Use mode "append" to add entries and "replace" to rewrite a section.`,parameters:La,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Oa(e,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated.`}],details:{mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}let o=`${`## ${i}`}\n${r.content.trimEnd()}\n`;try{return a===`replace`?await Q(e,`MEMORY.md`,za(await Ta(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Oa(e,o,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: section "${i}" (${a})`}],details:{section:i,mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}}}}function za(e,t,n){let r=e.split(`
48
50
  `),i=`## ${t}`,a=`${i}\n${n.trimEnd()}`.trimEnd(),o=-1;for(let e=0;e<r.length;e+=1)if(r[e]?.trim()===i){o=e;break}if(o===-1){let t=e.trimEnd();return`${t?`${t}\n`:``}${a}\n`}let s=r.length;for(let e=o+1;e<r.length;e+=1)if(/^##\s+/.test(r[e]??``)){s=e;break}return`${[r.slice(0,o).join(`
49
51
  `).trimEnd(),a,r.slice(s).join(`
50
52
  `).trimStart()].filter(e=>e.length>0).join(`
51
- `)}\n`}function Na(e,t){let n=e.split(`
53
+ `)}\n`}function Ba(e,t){let n=e.split(`
52
54
  `),r=`## ${t}`,i=-1;for(let e=0;e<n.length;e+=1)if(n[e]?.trim()===r){i=e;break}if(i===-1)return null;let a=n.length;for(let e=i+1;e<n.length;e+=1)if(/^##\s+/.test(n[e]??``)){a=e;break}let o=[n.slice(0,i).join(`
53
55
  `).trimEnd(),n.slice(a).join(`
54
56
  `).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
55
- `)}\n`:``}function Pa(e,t){let n=e.split(`
57
+ `)}\n`:``}function Va(e,t){let n=e.split(`
56
58
  `);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
57
- `)}\n`:``)}function Fa(e,t,n){let r=e.split(`
59
+ `)}\n`:``)}function Ha(e,t,n){let r=e.split(`
58
60
  `);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
59
- `)}\n`)}function Ia(e){let t=e.indexOf(`#`);if(t===-1)return{filePath:e};let n=e.slice(0,t),r=e.slice(t+1),i=r.match(/^L(\d+)$/);return i?{filePath:n,line:Number(i[1])}:{filePath:n,section:r}}function La(e,t){let n=[],r=t.split(`
60
- `);for(let t of r){let r=t.match(/^##\s+(.+)$/);if(r?.[1]){let t=r[1].trim(),i=`${e}#${t}`;n.push({id:i,heading:t})}}if(n.length===0){let t=0;for(let i of r){t+=1;let r=i.trim();if(!r||r.startsWith(`---`)||r.startsWith(`# `))continue;let a=r.length>60?`${r.slice(0,57)}...`:r;if(n.push({id:`${e}#L${t}`,heading:a}),n.length>=20)break}}return n}const Ra=U.Object({content:U.String({description:`Note to append to today's daily log`}),scope:U.Optional(U.Union([U.Literal(`daily`),U.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function za(e,t){return{name:`memory_log`,label:`Daily Log`,description:`Append a timestamped daily or session note for short-term context, progress updates, and open questions.`,parameters:Ra,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Sa(e,r.content,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Logged to ${a} memory: ${r.content}`}],details:{date:i,scope:a}}}catch(e){throw Error(`Failed to write daily log: ${e instanceof Error?e.message:String(e)}`)}}}}const Ba=U.Object({scope:U.Optional(U.Union([U.Literal(`long-term`),U.Literal(`recent`),U.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Va(e,t){return{name:`memory_list`,label:`List Memories`,description:`List stored memories so you can inspect available entries and obtain exact ids or paths before update/delete.`,parameters:Ba,async execute(n,r){try{let n=r.scope??`all`,i=await ga(e),a=[];for(let n of i.slice(0,30)){let r=await ba(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
61
- `),t=La(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
61
+ `)}\n`)}function Ua(e){let t=e.indexOf(`#`);if(t===-1)return{filePath:e};let n=e.slice(0,t),r=e.slice(t+1),i=r.match(/^L(\d+)$/);return i?{filePath:n,line:Number(i[1])}:{filePath:n,section:r}}function Wa(e,t){let n=[],r=t.split(`
62
+ `);for(let t of r){let r=t.match(/^##\s+(.+)$/);if(r?.[1]){let t=r[1].trim(),i=`${e}#${t}`;n.push({id:i,heading:t})}}if(n.length===0){let t=0;for(let i of r){t+=1;let r=i.trim();if(!r||r.startsWith(`---`)||r.startsWith(`# `))continue;let a=r.length>60?`${r.slice(0,57)}...`:r;if(n.push({id:`${e}#L${t}`,heading:a}),n.length>=20)break}}return n}const Ga=U.Object({content:U.String({description:`Note to append to today's daily log`}),scope:U.Optional(U.Union([U.Literal(`daily`),U.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Ka(e,t){return{name:`memory_log`,label:`Daily Log`,description:`Append a timestamped daily or session note for short-term context, progress updates, and open questions.`,parameters:Ga,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await ka(e,r.content,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Logged to ${a} memory: ${r.content}`}],details:{date:i,scope:a}}}catch(e){throw Error(`Failed to write daily log: ${e instanceof Error?e.message:String(e)}`)}}}}const qa=U.Object({scope:U.Optional(U.Union([U.Literal(`long-term`),U.Literal(`recent`),U.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Ja(e,t){return{name:`memory_list`,label:`List Memories`,description:`List stored memories so you can inspect available entries and obtain exact ids or paths before update/delete.`,parameters:qa,async execute(n,r){try{let n=r.scope??`all`,i=await Ca(e),a=[];for(let n of i.slice(0,30)){let r=await Da(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
63
+ `),t=Wa(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
62
64
  `):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
63
65
 
64
- `)||`(no memories)`}],details:{count:a.length,scope:n,files:a}}}catch(e){throw Error(`Failed to list memories: ${e instanceof Error?e.message:String(e)}`)}}}}const Ha=U.Object({id:U.Optional(U.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:U.Optional(U.String({description:`Search query used to find memories to delete`})),limit:U.Optional(U.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:U.Optional(U.Union([U.Literal(`long-term`),U.Literal(`recent`),U.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Ua(e,t){return{name:`memory_forget`,label:`Forget Memory`,description:`Delete a specific memory by its entry ID, or delete matching memories by search query. IDs with # (e.g. MEMORY.md#Preferences) delete only that section from the file. Prefer memory_list or memory_search first so you know the target.`,parameters:Ha,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Ia(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Na(await va(e)??``,t.section);return n===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Q(e,t.filePath,n,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}let n=await ba(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=Na(n.join(`
65
- `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Q(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}if(t.line!==void 0){let n=await ba(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=Pa(n.join(`
66
- `),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Q(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten line ${t.line} from ${t.filePath}`}],details:{removed:1,id:r.id}})}return r.id===`MEMORY.md`?{content:[{type:`text`,text:`Cannot delete MEMORY.md directly. Use id with a section (e.g. MEMORY.md#SectionName) to remove individual entries, or use query mode.`}],details:{removed:0,id:r.id}}:(await Ca(e,r.id,i),{content:[{type:`text`,text:`Forgotten memory: ${r.id}`}],details:{removed:1,id:r.id}})}if(r.query){let t=Math.min(Math.max(r.limit??5,1),20),n=await ya(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await Ca(e,r.path,i),a+=1);return{content:[{type:`text`,text:`Forgotten ${a} memor${a===1?`y`:`ies`} matching: ${r.query}`}],details:{removed:a,query:r.query}}}return{content:[{type:`text`,text:`Provide id or query to forget memories.`}],details:{removed:0}}}catch(e){throw Error(`Failed to forget memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Wa=U.Object({id:U.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:U.String({description:`New content to replace the existing memory with`})});function Ga(e,t){return{name:`memory_update`,label:`Update Memory`,description:`Replace an existing memory's content by its entry ID. Use memory_list or memory_search first to find the correct ID. IDs with # (e.g. MEMORY.md#Preferences) update only that section; IDs without # replace the entire file.`,parameters:Wa,async execute(n,r){try{let n=Ia(r.id);if(n.section){let i=Ma(await va(e)??``,n.section,r.content);return await Q(e,n.filePath,i,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (section "${n.section}")`}],details:{id:r.id}}}if(n.line!==void 0){let i=await ba(e,n.filePath,1,1e4,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(!i)throw Error(`File not found: ${n.filePath}`);let a=Fa(i.join(`
67
- `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Q(e,n.filePath,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (line ${n.line})`}],details:{id:r.id}}}return await Q(e,r.id,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id}`}],details:{id:r.id}}}catch(e){throw Error(`Failed to update memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Ka=U.Object({query:U.Optional(U.String({description:`Search query; omit to browse recent sessions.`})),role_filter:U.Optional(U.Union([U.Literal(`user`),U.Literal(`assistant`),U.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:U.Optional(U.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:U.Optional(U.Union([U.Literal(`llm`),U.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function qa(e,t){return{name:`session_search`,label:`Session Search`,description:`Search past conversation transcripts across sessions for cross-session recall. Use when the user asks about what was discussed, decided, or done in previous chats (e.g. last time, before, remember when). Omit query to browse recent sessions with zero LLM cost; include query to search transcripts and return summaries. Do not use this as the only source for stable project policy/config if long-term memory docs exist (use memory_search for durable docs).`,parameters:Ka,async execute(r,i){let a=Ja(i.limit),o=i.summary_mode??`llm`,s=i.query?.trim(),c=i.role_filter;if(!s){let n=await Ya(e,a,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let l=await Xa({dataDir:e,query:s,roleFilter:c,messageLimit:50,sessionLimit:a,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(l.length===0){let e={mode:`query`,query:s,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let u=[];for(let r of l){let i=lo(s,r.snippets);if(o===`off`){u.push({session_id:r.sessionId,summary:i,when:r.when,source:r.source,meta:{summary_source:`extractive`,snippet:r.snippets[0],score:Number(r.score.toFixed(4))}});continue}if(!t?.llm){u.push({session_id:r.sessionId,summary:i,when:r.when,source:r.source,meta:{summary_source:`extractive_short_circuit`,snippet:r.snippets[0],score:Number(r.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let a=await ir({entries:oo(ao(await n(e,r.sessionId,{storeName:t?.sessionStoreName})),s,1e5),llm:t.llm,instructions:co({query:s})});u.push({session_id:r.sessionId,summary:a.trim()||i,when:r.when,source:r.source,meta:{summary_source:`llm`,snippet:r.snippets[0],score:Number(r.score.toFixed(4))}})}catch(e){u.push({session_id:r.sessionId,summary:i,when:r.when,source:r.source,meta:{summary_source:`llm_fallback_extractive`,snippet:r.snippets[0],score:Number(r.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let d={mode:`query`,query:s,count:u.length,results:u};return{content:[{type:`text`,text:JSON.stringify(d,null,2)}],details:d}}}}function Ja(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Ya(e,t,n){let i=await f(e,{storeName:n?.sessionStoreName}),a=[];for(let t of i){if(t===n?.sessionId)continue;let i=await r(e,t,{storeName:n?.sessionStoreName});i&&a.push({id:t,when:i.updatedAt||i.createdAt||``,source:i.channel??`unknown`,title:i.title?.trim()||`Session activity summary unavailable.`})}return a.sort((e,t)=>t.when.localeCompare(e.when)),a.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function Xa(e){let t=e.messageLimit??50,n=(await f(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),i=eo(e.query),a=(await uo(n,6,async t=>Za({dataDir:e.dataDir,sessionId:t,terms:i,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(io).slice(0,t);if(a.length===0)return[];let o=new Map;for(let e of a){let t=o.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),o.set(e.sessionId,t)}let s=Array.from(o.values());for(let t of s){let n=await r(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return s.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),s.slice(0,e.sessionLimit)}async function Za(e){let t=o(e.dataDir,e.sessionId,{storeName:e.storeName});if(!H.existsSync(t))return[];let n=[],r=H.createReadStream(t,{encoding:`utf-8`}),i=Ge.createInterface({input:r,crlfDelay:1/0});try{for await(let t of i){let r=t.trim();if(!r||!Qa(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!$a(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=no(i.content,e.terms,i.role);if(a<=0)continue;let o=ro(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(io),n.length=20)}}finally{i.close(),r.destroy()}return n.sort(io),n}function Qa(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function $a(e){return e===`user`||e===`assistant`||e===`tool_result`}function eo(e){let t=e.toLowerCase().trim(),n=new Set;t.length>0&&n.add(t);let r=t.match(/[\p{L}\p{N}_-]+/gu)??[];for(let e of r)e.length>=2&&n.add(e);let i=Array.from(t).filter(e=>to(e)).join(``);if(i.length>=2)for(let e=0;e<=i.length-2;e+=1)n.add(i.slice(e,e+2));return Array.from(n).slice(0,30)}function to(e){let t=e.codePointAt(0)??0;return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=12352&&t<=12543||t>=44032&&t<=55215}function no(e,t,n){let r=e.toLowerCase(),i=0;for(let e of t)e&&r.includes(e)&&(i+=1);if(i===0)return 0;let a=n===`user`?1.2:n===`assistant`?1:.7;return i*i*a}function ro(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function io(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function ao(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function oo(e,t,n){if(e.length===0)return e;let r=eo(t);if(e.reduce((e,t)=>e+t.content.length,0)<=n)return e;let i=[];for(let t=0;t<e.length;t+=1){let n=e[t].content.toLowerCase();r.some(e=>e&&n.includes(e))&&i.push(t)}if(i.length===0)return so(e,n);let a=i[0],o=i[0],s=e[a].content.length;for(;s<n&&(a>0||o<e.length-1);){if(o<e.length-1){let t=e[o+1].content.length;if(s+t<=n)o+=1,s+=t;else break}if(a>0){let t=e[a-1].content.length;if(s+t<=n)--a,s+=t;else break}}return e.slice(a,o+1)}function so(e,t){let n=[],r=0;for(let i=e.length-1;i>=0;--i){let a=e[i];if(r+a.content.length>t)break;n.push(a),r+=a.content.length}return n.reverse()}function co(e){let t=e.languageHint?.trim(),n=[`Summarize this past session for retrieval use.`,`Focus query: ${e.query}`,`Prioritize: final outcome, key actions, concrete evidence (files/commands/ids), unresolved items.`,`Do not invent facts. If evidence is missing, say so explicitly.`,`Keep it concise and factual.`];return t&&n.push(`Respond in: ${t}`),n.join(`
68
- `)}function lo(e,t){return t.length===0?`No direct transcript snippet was extracted for query: ${e}`:`Extractive summary for "${e}":\n${t.slice(0,3).map((e,t)=>`${t+1}. ${e}`).join(`
69
- `)}`}async function uo(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}const fo=U.Object({category:U.Optional(U.String({description:`Reserved category filter field. Not used yet.`}))}),po=U.Object({name:U.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:U.Optional(U.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function mo(e,t,n=[]){return[...n,...t,ot(e)]}function ho(e,t,n=[]){let r=mo(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:fo,async execute(e,t){let n=await ft(r),i={skills:n.map(e=>({name:e.name,description:e.description})),count:n.length};return{content:[{type:`text`,text:JSON.stringify({success:!0,...i,hint:`Use skill_load(name) to load the skill's SKILL.md entrypoint.`})}],details:i}}}}function go(e){let t=mo(e.dataDir,e.pluginDirs,e.skillsLoadPaths),n=new Set;return{name:`skill_load`,label:`Skill Load`,description:`Load a skill's SKILL.md entrypoint. Optionally override lookup with skillPath.`,parameters:po,async execute(r,i){let a=await ht(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``}}}}}const _o=U.Object({task:U.String({description:`The task description for the subagent to execute`}),label:U.Optional(U.String({description:`Optional short label to identify this subagent`}))}),vo=_o,yo=U.Object({tasks:U.Array(_o,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function bo(e){let t=e.label?`"${e.label}"`:`task: ${_e(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${xo(e.result??`(no output)`)}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function xo(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}async function So(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim();if(W.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,taskLength:p.length,taskPreview:Gt(p)}),!p){let e={status:`error`,error:`task must not be empty`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let h=r.checkSpawnAllowed(i,o+1);if(!h.allowed){let e={status:`forbidden`,error:h.reason};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=Be(),_=new AbortController,v=t,y={parentSessionId:i,parentDir:a};try{await b(s,c,{storeName:d.sessionStoreName,subagent:y,sessionId:v})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return W.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}W.info(`subagent session created`,{parentSessionId:i,childSessionId:v,depth:o+1,runId:g});let x={runId:g,childSessionId:v,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:_};await d.onProgress?.({type:`subagent_spawn`,childSessionId:v,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let S=f({dataDir:s,sessionId:v,message:p,channel:c,llm:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[]},loopDetection:u,abortSignal:_.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(g,e.error);return}r.complete(g,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(g,t)});r.register(x,S),W.info(`subagent run registered`,{runId:g,parentSessionId:i,childSessionId:v,depth:o+1}),await S,W.info(`subagent run settled`,{runId:g,parentSessionId:i,childSessionId:v,status:x.status,durationMs:x.endedAt?x.endedAt-x.startedAt:void 0,hasError:!!x.error}),r.markAnnounced(g),await d.onProgress?.({type:`subagent_complete`,childSessionId:v,task:p,status:x.status,sessionId:i,messageId:d.messageId,depth:o+1});let C=bo({task:p,label:m,status:x.status,result:x.result,error:x.error});if(x.status===`done`){let e={status:`done`,childSessionId:v,runId:g,result:x.result??``};return W.info(`subagent spawn completed`,{runId:g,parentSessionId:i,childSessionId:v,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:C}],details:e}}let w=x.status===`killed`?{status:`killed`,childSessionId:v,runId:g,error:`subagent killed`}:{status:`error`,childSessionId:v,runId:g,error:x.error??`unknown error`};return W.warn(`subagent spawn completed with non-success status`,{runId:g,parentSessionId:i,childSessionId:v,status:w.status,error:w.error}),{content:[{type:`text`,text:C}],isError:!0,details:w}}function Co(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. `+(r===0?`IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. `:`WARNING: You are already running as a subagent (depth ${r}). Spawning further subagents creates deeply nested hierarchies that are expensive and error-prone. Only use this tool if the current task genuinely cannot be completed with available tools directly. Prefer direct tool calls (exec, read_file, write_file, etc.) over spawning another subagent. `)+`Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:vo,async execute(e,t){return So(u,e,t)}}}function wo(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:yo,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}W.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await So(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`[Batch subagents ${f}] ${o.length-d.length}/${o.length} completed`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${xo(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
66
+ `)||`(no memories)`}],details:{count:a.length,scope:n,files:a}}}catch(e){throw Error(`Failed to list memories: ${e instanceof Error?e.message:String(e)}`)}}}}const Ya=U.Object({id:U.Optional(U.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:U.Optional(U.String({description:`Search query used to find memories to delete`})),limit:U.Optional(U.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:U.Optional(U.Union([U.Literal(`long-term`),U.Literal(`recent`),U.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Xa(e,t){return{name:`memory_forget`,label:`Forget Memory`,description:`Delete a specific memory by its entry ID, or delete matching memories by search query. IDs with # (e.g. MEMORY.md#Preferences) delete only that section from the file. Prefer memory_list or memory_search first so you know the target.`,parameters:Ya,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Ua(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Ba(await Ta(e)??``,t.section);return n===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Q(e,t.filePath,n,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}let n=await Da(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=Ba(n.join(`
67
+ `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Q(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten section "${t.section}" from ${t.filePath}`}],details:{removed:1,id:r.id}})}if(t.line!==void 0){let n=await Da(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=Va(n.join(`
68
+ `),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Q(e,t.filePath,a,i),{content:[{type:`text`,text:`Forgotten line ${t.line} from ${t.filePath}`}],details:{removed:1,id:r.id}})}return r.id===`MEMORY.md`?{content:[{type:`text`,text:`Cannot delete MEMORY.md directly. Use id with a section (e.g. MEMORY.md#SectionName) to remove individual entries, or use query mode.`}],details:{removed:0,id:r.id}}:(await Aa(e,r.id,i),{content:[{type:`text`,text:`Forgotten memory: ${r.id}`}],details:{removed:1,id:r.id}})}if(r.query){let t=Math.min(Math.max(r.limit??5,1),20),n=await Ea(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await Aa(e,r.path,i),a+=1);return{content:[{type:`text`,text:`Forgotten ${a} memor${a===1?`y`:`ies`} matching: ${r.query}`}],details:{removed:a,query:r.query}}}return{content:[{type:`text`,text:`Provide id or query to forget memories.`}],details:{removed:0}}}catch(e){throw Error(`Failed to forget memory: ${e instanceof Error?e.message:String(e)}`)}}}}const Za=U.Object({id:U.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:U.String({description:`New content to replace the existing memory with`})});function Qa(e,t){return{name:`memory_update`,label:`Update Memory`,description:`Replace an existing memory's content by its entry ID. Use memory_list or memory_search first to find the correct ID. IDs with # (e.g. MEMORY.md#Preferences) update only that section; IDs without # replace the entire file.`,parameters:Za,async execute(n,r){try{let n=Ua(r.id);if(n.section){let i=za(await Ta(e)??``,n.section,r.content);return await Q(e,n.filePath,i,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (section "${n.section}")`}],details:{id:r.id}}}if(n.line!==void 0){let i=await Da(e,n.filePath,1,1e4,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(!i)throw Error(`File not found: ${n.filePath}`);let a=Ha(i.join(`
69
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Q(e,n.filePath,a,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id} (line ${n.line})`}],details:{id:r.id}}}return await Q(e,r.id,r.content,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: ${r.id}`}],details:{id:r.id}}}catch(e){throw Error(`Failed to update memory: ${e instanceof Error?e.message:String(e)}`)}}}}const $a=U.Object({query:U.Optional(U.String({description:`Search query; omit to browse recent sessions.`})),role_filter:U.Optional(U.Union([U.Literal(`user`),U.Literal(`assistant`),U.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:U.Optional(U.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:U.Optional(U.Union([U.Literal(`llm`),U.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function eo(e,t){return{name:`session_search`,label:`Session Search`,description:`Search past conversation transcripts across sessions for cross-session recall. Use when the user asks about what was discussed, decided, or done in previous chats (e.g. last time, before, remember when). Omit query to browse recent sessions with zero LLM cost; include query to search transcripts and return summaries. Do not use this as the only source for stable project policy/config if long-term memory docs exist (use memory_search for durable docs).`,parameters:$a,async execute(n,i){let a=to(i.limit),o=i.summary_mode??`llm`,s=i.query?.trim(),c=i.role_filter;if(!s){let n=await no(e,a,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let l=await ro({dataDir:e,query:s,roleFilter:c,messageLimit:50,sessionLimit:a,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(l.length===0){let e={mode:`query`,query:s,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let u=[];for(let n of l){let i=_o(s,n.snippets);if(o===`off`){u.push({session_id:n.sessionId,summary:i,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){u.push({session_id:n.sessionId,summary:i,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let a=await dr({entries:mo(po(await r(e,n.sessionId,{storeName:t?.sessionStoreName})),s,1e5),llm:t.llm,instructions:go({query:s})});u.push({session_id:n.sessionId,summary:a.trim()||i,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){u.push({session_id:n.sessionId,summary:i,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let d={mode:`query`,query:s,count:u.length,results:u};return{content:[{type:`text`,text:JSON.stringify(d,null,2)}],details:d}}}}function to(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function no(e,t,n){let r=await g(e,{storeName:n?.sessionStoreName}),a=[];for(let t of r){if(t===n?.sessionId)continue;let r=await i(e,t,{storeName:n?.sessionStoreName});r&&a.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return a.sort((e,t)=>t.when.localeCompare(e.when)),a.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function ro(e){let t=e.messageLimit??50,n=(await g(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=so(e.query),a=(await vo(n,6,async t=>io({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(fo).slice(0,t);if(a.length===0)return[];let o=new Map;for(let e of a){let t=o.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),o.set(e.sessionId,t)}let s=Array.from(o.values());for(let t of s){let n=await i(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return s.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),s.slice(0,e.sessionLimit)}async function io(e){let t=await b(u(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
70
+ `);for(let t of r){let r=t.trim();if(!r||!ao(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!oo(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=lo(i.content,e.terms,i.role);if(a<=0)continue;let o=uo(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(fo),n.length=20)}return n.sort(fo),n}function ao(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function oo(e){return e===`user`||e===`assistant`||e===`tool_result`}function so(e){let t=e.toLowerCase().trim(),n=new Set;t.length>0&&n.add(t);let r=t.match(/[\p{L}\p{N}_-]+/gu)??[];for(let e of r)e.length>=2&&n.add(e);let i=Array.from(t).filter(e=>co(e)).join(``);if(i.length>=2)for(let e=0;e<=i.length-2;e+=1)n.add(i.slice(e,e+2));return Array.from(n).slice(0,30)}function co(e){let t=e.codePointAt(0)??0;return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=12352&&t<=12543||t>=44032&&t<=55215}function lo(e,t,n){let r=e.toLowerCase(),i=0;for(let e of t)e&&r.includes(e)&&(i+=1);if(i===0)return 0;let a=n===`user`?1.2:n===`assistant`?1:.7;return i*i*a}function uo(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function fo(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function po(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function mo(e,t,n){if(e.length===0)return e;let r=so(t);if(e.reduce((e,t)=>e+t.content.length,0)<=n)return e;let i=[];for(let t=0;t<e.length;t+=1){let n=e[t].content.toLowerCase();r.some(e=>e&&n.includes(e))&&i.push(t)}if(i.length===0)return ho(e,n);let a=i[0],o=i[0],s=e[a].content.length;for(;s<n&&(a>0||o<e.length-1);){if(o<e.length-1){let t=e[o+1].content.length;if(s+t<=n)o+=1,s+=t;else break}if(a>0){let t=e[a-1].content.length;if(s+t<=n)--a,s+=t;else break}}return e.slice(a,o+1)}function ho(e,t){let n=[],r=0;for(let i=e.length-1;i>=0;--i){let a=e[i];if(r+a.content.length>t)break;n.push(a),r+=a.content.length}return n.reverse()}function go(e){let t=e.languageHint?.trim(),n=[`Summarize this past session for retrieval use.`,`Focus query: ${e.query}`,`Prioritize: final outcome, key actions, concrete evidence (files/commands/ids), unresolved items.`,`Do not invent facts. If evidence is missing, say so explicitly.`,`Keep it concise and factual.`];return t&&n.push(`Respond in: ${t}`),n.join(`
71
+ `)}function _o(e,t){return t.length===0?`No direct transcript snippet was extracted for query: ${e}`:`Extractive summary for "${e}":\n${t.slice(0,3).map((e,t)=>`${t+1}. ${e}`).join(`
72
+ `)}`}async function vo(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}const yo=U.Object({category:U.Optional(U.String({description:`Reserved category filter field. Not used yet.`}))}),bo=U.Object({name:U.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:U.Optional(U.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function xo(e,t,n=[]){return[...n,...t,pt(e)]}function So(e,t,n=[]){let r=xo(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:yo,async execute(e,t){let n=await yt(r),i={skills:n.map(e=>({name:e.name,description:e.description})),count:n.length};return{content:[{type:`text`,text:JSON.stringify({success:!0,...i,hint:`Use skill_load(name) to load the skill's SKILL.md entrypoint.`})}],details:i}}}}function Co(e){let t=xo(e.dataDir,e.pluginDirs,e.skillsLoadPaths),n=new Set;return{name:`skill_load`,label:`Skill Load`,description:`Load a skill's SKILL.md entrypoint. Optionally override lookup with skillPath.`,parameters:bo,async execute(r,i){let a=await St(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``}}}}}const wo=U.Object({task:U.String({description:`The task description for the subagent to execute`}),label:U.Optional(U.String({description:`Optional short label to identify this subagent`})),agent:U.Optional(U.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),To=U.Object({task:U.String({description:`The task description for the subagent to execute`}),label:U.Optional(U.String({description:`Optional short label to identify this subagent`})),agent:U.Optional(U.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),Eo=U.Object({tasks:U.Array(wo,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Do(e){let t=e.label?`"${e.label}"`:`task: ${Te(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${Oo(e.result??`(no output)`)}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function Oo(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}async function ko(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(W.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:Qt(p)}),!p){let e={status:`error`,error:`task must not be empty`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Je(),v=new AbortController,y=t,b=At(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await D(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return W.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}W.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let C=f({dataDir:s,sessionId:y,message:b?Pt(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,C),W.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,W.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let w=Do({task:p,label:m,status:S.status,result:S.result,error:S.error});if(S.status===`done`){let e={status:`done`,childSessionId:y,runId:_,result:S.result??``};return W.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:w}],details:e}}let T=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return W.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:T.status,error:T.error}),{content:[{type:`text`,text:w}],isError:!0,details:T}}function Ao(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. `+(r===0?`IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. `:`WARNING: You are already running as a subagent (depth ${r}). Spawning further subagents creates deeply nested hierarchies that are expensive and error-prone. Only use this tool if the current task genuinely cannot be completed with available tools directly. Prefer direct tool calls (exec, read_file, write_file, etc.) over spawning another subagent. `)+`Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:To,async execute(e,t){return ko(u,e,t)}}}function jo(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:Eo,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}W.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await ko(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`[Batch subagents ${f}] ${o.length-d.length}/${o.length} completed`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${Oo(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
70
73
 
71
- `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const To=U.Object({action:U.Union([`list`,`kill`].map(e=>U.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:U.Optional(U.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Eo(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 Do(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 Oo(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:To,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let t=o.map((t,n)=>{let r=t.status===`running`?`running`:e.isAnnounced(t.runId)?`delivered`:`pending`;return{index:n+1,runId:t.runId,label:t.label??t.task.slice(0,40),task:t.task,status:t.status,deliveryStatus:r,depth:t.depth,runtimeMs:t.endedAt?t.endedAt-t.startedAt:a-t.startedAt,...t.result===void 0?{}:{result:t.result},...t.error===void 0?{}:{error:t.error}}}),n={action:`list`,runs:t,text:(t.length===0?[`(no subagents)`]:t.map(e=>{let t=e.deliveryStatus===`running`?``:`, ${e.deliveryStatus}`,n=e.result===void 0?e.error===void 0?``:`\n error: ${e.error}`:`\n result: ${e.result}`;return`${e.index}. [${e.status}${t}] ${e.label} (${Eo(e.runtimeMs)})${n}`})).join(`
72
- `)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Do(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 ko=U.Object({image:U.String({description:`Image path or URL`}),prompt:U.Optional(U.String({description:`Prompt for image analysis`})),model:U.Optional(U.String({description:`Optional model override`})),maxBytesMb:U.Optional(U.Number({description:`Optional size cap in MB`}))});function Ao(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:ko,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}}}}var jo=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function Mo(e){return!!(e instanceof jo||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const No=new Ke;function Po(){return{}}async function Fo(e,t){return await No.run(e,t)}function Io(e){let t=No.getStore();!t||t.signal||(t.signal=e)}const Lo=U.Object({reason:U.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Ro(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??Lo,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=be(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new jo(e,i,t,e,o,s,n);throw Io(r),r}}}function zo(e,t){let n=V.join(e,`workspace`),r=t?.memoryOptions,i=Fi(),a=t?.currentSessionId??t?.sessionId,o=a?async n=>{await j(e,a,n,{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,s=[xi({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Ti({registry:i,scopeKey:n}),Hi(n,t?.contextManager),Wi(n,t?.contextManager,o),Ki(n,t?.contextManager,o),Ji(n),ta(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:o}),Ta(e,r),qa(e,r),Da(e,r),ja(e,r),za(e,r),Va(e,r),Ua(e,r),Ga(e,r),ho(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),go({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return t&&s.push(Co(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),wo(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Oo(t.registry,t.parentSessionId)),s}const Bo={read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Vo=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function Ho(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:[...Vo.filter(e=>t.has(e)),...n.filter(e=>!Vo.includes(e)).sort()],displayName:t}}function Uo(e){let{ordered:t,displayName:n}=Ho(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)??Bo[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
74
+ `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const Mo=U.Object({action:U.Union([`list`,`kill`].map(e=>U.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:U.Optional(U.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function No(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 Po(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 Fo(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:Mo,async execute(n,r){let i=r.action,a=Date.now(),o=e.list(t);if(i===`list`){let t=o.map((t,n)=>{let r=t.status===`running`?`running`:e.isAnnounced(t.runId)?`delivered`:`pending`;return{index:n+1,runId:t.runId,label:t.label??t.task.slice(0,40),task:t.task,status:t.status,deliveryStatus:r,depth:t.depth,runtimeMs:t.endedAt?t.endedAt-t.startedAt:a-t.startedAt,...t.result===void 0?{}:{result:t.result},...t.error===void 0?{}:{error:t.error}}}),n={action:`list`,runs:t,text:(t.length===0?[`(no subagents)`]:t.map(e=>{let t=e.deliveryStatus===`running`?``:`, ${e.deliveryStatus}`,n=e.result===void 0?e.error===void 0?``:`\n error: ${e.error}`:`\n result: ${e.result}`;return`${e.index}. [${e.status}${t}] ${e.label} (${No(e.runtimeMs)})${n}`})).join(`
75
+ `)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Po(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 Io=U.Object({image:U.String({description:`Image path or URL`}),prompt:U.Optional(U.String({description:`Prompt for image analysis`})),model:U.Optional(U.String({description:`Optional model override`})),maxBytesMb:U.Optional(U.Number({description:`Optional size cap in MB`}))});function Lo(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Io,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}}}}var Ro=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function zo(e){return!!(e instanceof Ro||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Bo=new $e;function Vo(){return{}}async function Ho(e,t){return await Bo.run(e,t)}function Uo(e){let t=Bo.getStore();!t||t.signal||(t.signal=e)}const Wo=U.Object({reason:U.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Go(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??Wo,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=Oe(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new Ro(e,i,t,e,o,s,n);throw Uo(r),r}}}function Ko(e,t){let n=V.join(e,`workspace`),r=t?.memoryOptions,i=Hi(),a=t?.sessionId,o=t?.channel!==`CRON`&&a?async n=>{await R(e,a,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,s=[Oi({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Mi({registry:i,scopeKey:n}),Yi(n,t?.contextManager),Zi(n,t?.contextManager,o),$i(n,t?.contextManager,o),ta(n),ca(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:o}),Ma(e,r),eo(e,r),Pa(e,r),Ra(e,r),Ka(e,r),Ja(e,r),Xa(e,r),Qa(e,r),So(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Co({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return t&&s.push(Ao(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),jo(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Fo(t.registry,t.parentSessionId)),s}const qo={read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Jo=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function Yo(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:[...Jo.filter(e=>t.has(e)),...n.filter(e=>!Jo.includes(e)).sort()],displayName:t}}function Xo(e){let{ordered:t,displayName:n}=Yo(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)??qo[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
73
76
  `),``].join(`
74
- `)}function Wo(){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(`
75
- `)}function Go(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
76
- `)}function Ko(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(`
77
- `)}function qo(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
77
+ `)}function Zo(){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(`
78
+ `)}function Qo(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
79
+ `)}function $o(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(`
80
+ `)}function es(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
78
81
  `)).join(`
79
82
  `)}\n</available_skills>`,``].join(`
80
- `)}function Jo(){return[`## Scenes`,'If the user message contains a `<scenes category="..." type="..." items="...">...</scenes>` tag, treat it as an explicit scene activation request.',"In this tag, `category` means the scene category, `type` means the scene name, and `items` means the item list required by that scene.","The `category`, `type`, and `items` attributes may each contain one or more comma-separated values. You must split them on commas, trim whitespace, and use every requested value.","Before executing the task, you must enumerate every requested `<category, scene, item>` combination derived from those attributes.","For each requested item, you must call `skill_load(name=<item>, skillPath=/aimax_pvc/scenes/<category>/<scene>/<item>)` to load that item's `SKILL.md`.","If one `<scenes ...>` tag requests multiple items for the same scene, you must load them one by one. Do not stop after the first matching item.","Do not start implementation, analysis, tool execution, or user-facing conclusions until all required scene skills have been loaded with `skill_load`.","After loading those scene `SKILL.md` files through `skill_load`, you must follow their instructions as mandatory task-specific guidance unless a higher-priority instruction overrides them.","For scene skills, if the exact scene SKILL.md is not visible, reload it again with the original `skillPath`.","Scene skills are not loaded by default. Only load them when the user explicitly includes the `<scenes ...>` tag.","Outside explicit scene activation, normal shared skills from `<available_skills>` must still be loaded with `skill_load(name=<skill-name>)` rather than direct file reads.","When a scene is activated, you must load scene instructions only through `skill_load` with `skillPath` pointing at `/aimax_pvc/scenes/<category>/<scene>/<item>` or that directory's `SKILL.md`.","Do not load, match, or fall back to scene instructions from `<dataDir>/.aimax/skills`.","Do not load, match, or fall back to scene instructions from `/aimax/extensions/`.","Do not load, match, or fall back to scene instructions from any path declared in `<available_skills>`.",`Do not ignore, rewrite, or drop the scene tag semantics even if the natural-language request looks answerable without scene skills.`,``].join(`
81
- `)}function Yo(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: write durable long-term memory to MEMORY.md (facts, preferences, rules, decisions).`,`- memory_log: append short-lived daily/session notes to memory/YYYY-MM-DD.md or session logs.`,`- Choose exactly one write surface per fact by default: long-term -> memory_write; daily/session log -> memory_log.`,`- Do not write the same fact to both memory_write and memory_log unless the user explicitly requests dual-write.`,`- Before memory_update or memory_forget, first run memory_list or memory_search to get the exact id/path.`,`- If the user explicitly names a listed memory tool, prefer calling that exact tool.`,`- Pattern: write/log for new memory; list/search -> update/forget for existing memory.`,``].join(`
82
- `)}function Xo(e){return[`## Memory & session recall`,`Choose the right recall surface:`,"- **Durable memory (Markdown / MEMORY.md / memory/ logs)**: stable facts, preferences, policies, decisions. Prefer `memory_search`, then `memory_get` when you need the full passage. Do not guess entry IDs or file paths.","- **Past chat transcripts across sessions** (what was said or done in earlier conversations): use `session_search`. Omit `query` to browse recent sessions; include `query` to search transcripts. Do not use `memory_search` alone to reconstruct a cross-session chat timeline.",'- **Ambiguous** ("last time" could mean chat or written notes): run `session_search` first for conversational evidence, then `memory_search` for durable notes; merge and attribute each source.',"If a listed memory tool call fails, report the failure; do not claim the tool is unavailable. Use `memory_list` before update/delete when needed.","Short tool chains: `memory_search` → `memory_get`; `memory_list` → `memory_update`; `memory_search` → `memory_forget`.",`Routing examples (intent → tool):`,'1) "上次聊天我们怎么修的" → `session_search` with keywords from the bug/symptom.','2) "团队对 release 的硬性规范是什么" → `memory_search` (durable policy).','3) "最近几个会话在忙什么" → `session_search` with no query (recent mode).','4) "把这条写进长期记忆" → `memory_write` (default), not `memory_log` or `session_search`.','5) "昨天日志里有没有记过 X" → `memory_search` on daily logs / `memory_list`.','6) "上次口头结论 vs 正式文档" → `session_search` then `memory_search`.',e===`off`?`Citations are disabled: do not include memory file paths or line numbers unless the user explicitly asks.`:`When useful, include memory evidence as Source: <path#line>.`,``].join(`
83
- `)}function Zo(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`,o=e.projectDir?.trim(),s=o?[`Current project directory: ${o}`,`Treat this project directory as the default cwd for repository/code work unless the user specifies another directory.`]:[];return[`## Workspace`,`Your cloud working directory is: ${r}`,...s,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, MEMORY.md, and the memory/ directory belong under ${t}.`,`Only create or update those files at their real .aimax paths. Never create cloud workspace copies like ${r}/AGENTS.md or ${r}/MEMORY.md unless the user explicitly asks for separate cloud documents.`,``].join(`
84
- `)}function Qo(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(`
85
- `)}function $o(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=es(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
86
- `)}function es(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(Date.UTC(n,r-1,i));return Number.isNaN(a.getTime())||a.getUTCFullYear()!==n||a.getUTCMonth()!==r-1||a.getUTCDate()!==i?null:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][a.getUTCDay()]}function ts(e){if(e.isMinimal||!e.enabled)return``;let t=(e.channels??[]).map(e=>e.trim()).filter(Boolean);return[`## Messaging`,`Reply in the current session for user-visible responses.`,`Use subagent tools only when the user or system instructions explicitly require subagents, delegation, or parallel agent execution; otherwise stay in the current agent.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
87
- `)}function ns(e){if(!e)return``;let t=[e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
88
- `)}function rs(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(`
89
- `)}function is(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(`
90
- `)}function as(e){return e<=0?``:[`## Subagent Constraint`,`You are running as a subagent (nesting depth: ${e}). Your role is to complete the delegated task directly using available tools.`,`Do NOT spawn further subagents unless the task absolutely cannot be completed any other way.`,`If you find yourself wanting to use subagent_spawn, first ask whether a direct tool call (exec, read_file, write_file, edit_file, etc.) can achieve the same result.`,`Subagent nesting adds overhead and complexity — prefer direct execution in all but the most exceptional cases.`,``].join(`
91
- `)}function os(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(`
92
- `):``}function ss(e){let t=e.promptMode??`full`,n=t===`minimal`,r=e.activeAgentSystemPrompt?.trim()||e.presetSystemPrompt||`You are a personal assistant running inside AiMax.`;if(t===`none`)return r;let i=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Vo],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,as(e.subagentDepth??0),Uo({toolNames:i,toolSummaries:e.toolSummaries}),Ko(n),Wo(),Et(e.availableAgents??[]),qo(a),Jo(),Yo(),Xo(e.memoryCitationsMode??`off`),Zo({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Qo(e.sandboxInfo),$o({currentDate:e.currentDate,timezone:e.timezone}),Go(),ts({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),rs({isMinimal:n}),ns(e.runtimeInfo),is({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),os(e.priorConversationSummary)].filter(Boolean).join(`
93
- `)}const cs=new Ke;async function ls(e,t){return await cs.run(e,t)}function us(e){return{async emit(t){let n=cs.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const ds=Symbol(`pluginToolOwner`);var fs=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,ds,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=Ro({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,ds,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function ps(e){return e[ds]}const ms=new Ke;function hs(){return{}}async function gs(e,t){return await ms.run(e,t)}function _s(e){let t=ms.getStore();!t||t.signal||(t.signal=e)}function vs(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=ps(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await ls({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h;try{h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r)}catch(e){if(Y(e))return _s(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}for(let e of h)e&&(e.params&&(d=e.params),e.block&&(f=!0,p=e.blockReason));if(f)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:p??`blocked by plugin`,durationMs:Date.now()-u},n,r),{content:[{type:`text`,text:p??`Tool blocked by plugin`}],isError:!0,details:{}};try{let o=await m(async()=>await i.execute(e,d,c,l));return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}catch(i){if(Y(i)){_s(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}var ys=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await ls({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const $={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function bs(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function xs(e){let t=bs(e?.warningThreshold,$.warningThreshold),n=bs(e?.criticalThreshold,$.criticalThreshold),r=bs(e?.globalCircuitBreakerThreshold,$.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??$.enabled,historySize:bs(e?.historySize,$.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??$.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??$.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??$.detectors.pingPong}}}function Ss(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Cs(e,t){return`${e}:${Es(t)}`}function ws(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(ws).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${ws(t[e])}`).join(`,`)}}`}function Ts(e){try{return ws(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 Es(e){let t=Ts(e);return ze(`sha256`).update(t).digest(`hex`)}function Ds(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Ss(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Os(e){return!Ss(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Ss(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
94
- `).trim()}function ks(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:ws(e)}function As(e,t,n,r){if(r!==void 0)return`error:${Es(ks(r))}`;if(!Ss(n))return n===void 0?void 0:Es(n);let i=Ss(n.details)?n.details:{},a=Os(n);if(Ds(e,t)&&e===`process`&&Ss(t)){let e=t.action;if(e===`poll`)return Es({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Es({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 Es({details:i,text:a})}function js(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 Ms(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 Ns(e,t){return[e,t].toSorted().join(`|`)}function Ps(e,t,n,r){let i=xs(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Cs(t,n),s=js(a,t,o),c=s.count,l=Ds(t,n),u=Ms(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:${Ns(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 Fs(e,t,n,r,i){let a=xs(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Cs(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Is(e,t){let n=xs(t.config),r=As(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Cs(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 Ls(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 Rs(e){return e&&e.trim()||`tool`}function zs(e,t,n){if(!e.execute)return e;let r=Rs(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Ps(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ls(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Fs(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Is(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Is(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Bs(e,t,n){return e.map(e=>zs(e,t,n))}async function Vs(e){let{session:{runParams:t,sessionId:r,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:c},runtimeInputs:{contextFiles:l,bootstrapWarnings:u,skills:d,effectivePromptText:f,pluginTools:p,pluginSkillDirs:m,skillsLoadPaths:h,presetSystemPrompt:g},dependencies:{registry:_,spawnFn:v,createModel:y,abortSignal:b}}=e,x=t.agentPolicy?.activeAgent,S=t.channel===`CRON`,C=S?[]:await n(t.dataDir,r,q(t)),w={model:t.llm.model,api:`openai-completions`},T=await li({dataDir:t.dataDir,sessionId:r,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),E=S?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await ui({entries:C,modelInfo:w,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,pendingUserMessage:f,signal:b,hooks:i,hookCtx:a,contextManager:T,dataDir:t.dataDir,sessionId:r});await Us({sessionId:r,historyResult:E,runContext:o,eventDispatcher:c,hookRegistry:i,hookContext:a});let D=t.subagentContext?.depth??0,O=s(t.dataDir,r,q(t)),k=Tt([...zo(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??r,currentSessionId:r,currentSessionDir:O,registry:_,parentSessionId:r,depth:D,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:h,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy},loopDetection:t.loopDetection,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:r,sessionStoreName:t.sessionStoreName,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:m,skillsLoadPaths:h,reportSkillUsed:async e=>{await c.dispatchProgress(r,e)},contextManager:T,hitlResume:t.hitlResume,spawnFn:v}),...p],x),A=k.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),ee={};for(let e of k){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||ee[t]||(ee[t]=n)}let j=t.messaging?.enabled??t.channel!==`CRON`,M=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],N=ss({dataDir:t.dataDir,projectDir:t.projectDir,skills:wt(d,x),contextFiles:l,toolNames:A,toolSummaries:ee,promptMode:D>0?`minimal`:`full`,subagentDepth:D,bootstrapWarnings:u,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:j,channels:M},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:He.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:x?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:E.priorSummary});N=await Hs({systemPrompt:N,dataDir:t.dataDir,sessionId:r,sessionStoreName:t.sessionStoreName});let P=await i.dispatch(`before_prompt_build`,{prompt:f},a,{eventDispatcher:c});for(let e of P)e&&(e.systemPrompt&&(N=e.systemPrompt),e.prependContext&&(N=`${e.prependContext}\n\n${N}`));await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:N},a,{eventDispatcher:c});let F=Bs(vs(k,i,a,{eventDispatcher:c}),{sessionId:r,config:t.loopDetection},Xt),I=x?.model??t.llm.model,L=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:c});for(let e of L)e&&e.modelOverride&&(I=e.modelOverride);let R=y({...t.llm,model:I},r,t.messageId,t.channel),z=new Ve({initialState:{systemPrompt:N,model:R,tools:F,messages:[]},getApiKey:e=>t.llm.apiKey});return E.messages.length>0&&z.replaceMessages(E.messages),{agent:z,resolvedModelId:I,historyMessages:E.messages,historyResult:E,contextManager:T,usageBaselineTranscriptEntryCount:C.length,workspaceDir:o.workspaceDir}}async function Hs(e){if((await N(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})).length<=8)return e.systemPrompt;let t=`Older CRON execution records for this session are stored outside the main transcript at ${m(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})}. The main transcript keeps only the latest 8 CRON summaries. Read that jsonl file explicitly if older CRON outcomes matter.`;return`${e.systemPrompt}\n\n${t}`}async function Us(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount,s=Ws(await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i})),c=s.injectRecall?{...n.compactionEntry,content:`${s.injectRecall.trim()}\n\n${n.compactionEntry.content}`}:n.compactionEntry;if(s.skipPersist){await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!s.injectRecall}});return}await r.appendTranscriptEntry(c),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o,{eventDispatcher:i})}}function Ws(e){let t=!1,n=[];for(let r of e)r&&(r.skipPersist&&(t=!0),typeof r.injectRecall==`string`&&r.injectRecall.trim().length>0&&n.push(r.injectRecall.trim()));return{skipPersist:t,injectRecall:n.length>0?n.join(`
95
-
96
- `):void 0}}const Gs=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Ks=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]);function qs(e){let t=Zs(e?.maxAttempts,3),n=Qs(e?.initialDelayMs,250),r=Qs(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Js(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Ys(e,t){if(!(e<=0)){if(t?.aborted)throw Error(`aborted`);await new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`aborted`))},{once:!0})})}}function Xs(e){if(ec(e))return!1;let t=$s(e);if(t?.statusCode!==void 0)return nc(t.statusCode);if(t?.providerCode!==void 0)return tc(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Gs.has(e))return!0;if(Ks.has(e))return!1}return t?.code===`timeout`||t?.code===`network_error`?!0:t?.code===`aborted`||t?.code===`invalid_response`?!1:t?.retryable===!0}function Zs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function Qs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function $s(e){if(!e||typeof e!=`object`)return null;let t=e;return t.retryable===void 0&&t.statusCode===void 0&&t.code===void 0&&t.providerCode===void 0&&t.providerType===void 0?null:{message:typeof t.message==`string`?t.message:void 0,code:t.code,statusCode:t.statusCode,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable}}function ec(e){return $s(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function tc(e){return/^\d+$/.test(e)?nc(Number(e)):!1}function nc(e){return e===408||e===409||e===425||e===429||e>=500}async function rc(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,onTurnRecordProduced:f}=e,p=``,m=``,h=``,g=0,_=0,v,y,b=0,x=0,S=[],C=new Map,w=new Map,T=new Set,E=hs(),D=Po(),O=new Set,k=Promise.resolve(),A,ee=e=>{O.add(e),e.catch(e=>{A??=e}).finally(()=>{O.delete(e)})},j=async()=>{for(;O.size>0;)await Promise.allSettled([...O]);if(A)throw A},M=t.subscribe(e=>{let t=k.then(()=>N(e));k=t.catch(()=>{}),ee(t)});async function N(e){let n=()=>!!D.signal||E.signal?.transparentPause===!0;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(x===0&&(t.type===`text_delta`||t.type===`done`)&&(x=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=bc(`partial`in t?t.partial:void 0)??bc(`message`in t?t.message:void 0)??bc(`message`in e?e.message:void 0),a=xc(t.delta,r,m);r?(m=r,h=r):a&&(h+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){p=``,m=``,h=``,e.usage&&(g=e.usage.input,_=e.usage.output);return}p=vc(e);let r=xc(``,p,h||m);m=p,h=p,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(g=e.usage.input,_=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(g=t.usage.input,_=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=vc(e);await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:t.usage?{input:g,output:_,total:g+_}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(y=sc(t));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:gc(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),r=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),a=new Set(n.map(e=>e.toolCallId));for(let e of w.values())!a.has(e.toolCallId)&&r.has(e.toolCallId)&&n.push(e);for(let e of n)w.delete(e.toolCallId);if(S.push({message:t,toolResults:n}),f){let e=!!E.signal,r=!!D.signal;if(e&&E.signal.transparentPause||await f(mc(pc(t),e||r),r?[]:n.map(hc)),e||r)return}return}if(e.type===`tool_execution_start`){h=``,C.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=typeof e.result==`string`?e.result:JSON.stringify(e.result),r=yc(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:gc(r,i,e.toolCallId,e.toolName),c=C.get(e.toolCallId);if(C.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}w.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let P=qs(d),F=P.enabled?P.maxAttempts:1;try{for(let e=1;e<=F;e++){let d=S.length;y=void 0,v=void 0;try{if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);W.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:F,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),b=Date.now(),await gs(E,async()=>{await Fo(D,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await j();let f=E.signal;if(f)throw f;let m=D.signal;if(m)throw m;let h=typeof t.state.error==`string`?t.state.error:void 0,x=y??h;if(x){if(v=Sc(x),W.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:F,error:v}),await L(x,v,e,d))continue;await s.dispatchProgress(i,{type:`error`,message:v})}v||W.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:F,inputTokens:g,outputTokens:_,turnRecordCount:S.length-d,textLength:p.length});break}catch(t){if(await j(),Y(t)||Mo(t))throw t;if(v=Sc(t),W.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:F,error:v}),await L(t,v,e,d))continue;await s.dispatchProgress(i,{type:`error`,message:v});break}}}finally{M()}function I(){p=``,m=``,h=``}async function L(e,n,r,a){if(!ic({error:e,attempt:r,maxAttempts:F,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=Js(r,P);return W.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:F,delayMs:o,error:n}),await uc({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:F,message:n,delayMs:o}),S.length=a,I(),dc(t),await Ys(o,u),!0}let R=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:R,durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:{input:g,output:_,total:g+_}},l);let z=(D.signal?``:S.length>0?vc(S[S.length-1].message):``)||p||oc(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return f&&!ac(S)&&!v&&p.trim().length>0&&await f({role:`assistant`,content:p,timestamp:new Date().toISOString()},[]),{text:z,inputTokens:g,outputTokens:_,error:v,turnRecords:S}}function ic(e){return e.attempt>=e.maxAttempts||!Xs(e.error)||e.finalAssistantText.trim().length>0||e.streamedAssistantSnapshot.trim().length>0||e.streamedTextSinceBoundary.trim().length>0?!1:e.turnRecords.slice(e.attemptTurnRecordStart).every(e=>e.toolResults.length===0&&vc(e.message).trim().length===0)}function ac(e){return e.some(e=>pc(e.message)!==null||e.toolResults.length>0)}function oc(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];for(let e=r.toolResults.length-1;e>=0;e--){let n=r.toolResults[e];if(n.toolName===t&&n.content.trim().length>0)return n.content}}return``}function sc(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:cc(t.errorCode),statusCode:lc(t.statusCode),providerCode:cc(t.providerCode),providerType:cc(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function cc(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function lc(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function uc(e){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`runner`,phase:`llm_turn_retry_scheduled`,message:`retrying transient LLM turn failure`,details:{attempt:e.attempt,nextAttempt:e.attempt+1,maxAttempts:e.maxAttempts,delayMs:e.delayMs,error:e.message}})}function dc(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&fc(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function fc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function pc(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 mc(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function hc(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function gc(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:_c(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function _c(e){let t=e.indexOf(`
83
+ `)}function ts(){return[`## Scenes`,'If the user message contains a `<scenes category="..." type="..." items="...">...</scenes>` tag, treat it as an explicit scene activation request.',"In this tag, `category` means the scene category, `type` means the scene name, and `items` means the item list required by that scene.","The `category`, `type`, and `items` attributes may each contain one or more comma-separated values. You must split them on commas, trim whitespace, and use every requested value.","Before executing the task, you must enumerate every requested `<category, scene, item>` combination derived from those attributes.","For each requested item, you must call `skill_load(name=<item>, skillPath=/aimax_pvc/scenes/<category>/<scene>/<item>)` to load that item's `SKILL.md`.","If one `<scenes ...>` tag requests multiple items for the same scene, you must load them one by one. Do not stop after the first matching item.","Do not start implementation, analysis, tool execution, or user-facing conclusions until all required scene skills have been loaded with `skill_load`.","After loading those scene `SKILL.md` files through `skill_load`, you must follow their instructions as mandatory task-specific guidance unless a higher-priority instruction overrides them.","For scene skills, if the exact scene SKILL.md is not visible, reload it again with the original `skillPath`.","Scene skills are not loaded by default. Only load them when the user explicitly includes the `<scenes ...>` tag.","Outside explicit scene activation, normal shared skills from `<available_skills>` must still be loaded with `skill_load(name=<skill-name>)` rather than direct file reads.","When a scene is activated, you must load scene instructions only through `skill_load` with `skillPath` pointing at `/aimax_pvc/scenes/<category>/<scene>/<item>` or that directory's `SKILL.md`.","Do not load, match, or fall back to scene instructions from `<dataDir>/.aimax/skills`.","Do not load, match, or fall back to scene instructions from `/aimax/extensions/`.","Do not load, match, or fall back to scene instructions from any path declared in `<available_skills>`.",`Do not ignore, rewrite, or drop the scene tag semantics even if the natural-language request looks answerable without scene skills.`,``].join(`
84
+ `)}function ns(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: write durable long-term memory to MEMORY.md (facts, preferences, rules, decisions).`,`- memory_log: append short-lived daily/session notes to memory/YYYY-MM-DD.md or session logs.`,`- Choose exactly one write surface per fact by default: long-term -> memory_write; daily/session log -> memory_log.`,`- Do not write the same fact to both memory_write and memory_log unless the user explicitly requests dual-write.`,`- Before memory_update or memory_forget, first run memory_list or memory_search to get the exact id/path.`,`- If the user explicitly names a listed memory tool, prefer calling that exact tool.`,`- Pattern: write/log for new memory; list/search -> update/forget for existing memory.`,``].join(`
85
+ `)}function rs(e){return[`## Memory & session recall`,`Choose the right recall surface:`,"- **Durable memory (Markdown / MEMORY.md / memory/ logs)**: stable facts, preferences, policies, decisions. Prefer `memory_search`, then `memory_get` when you need the full passage. Do not guess entry IDs or file paths.","- **Past chat transcripts across sessions** (what was said or done in earlier conversations): use `session_search`. Omit `query` to browse recent sessions; include `query` to search transcripts. Do not use `memory_search` alone to reconstruct a cross-session chat timeline.",'- **Ambiguous** ("last time" could mean chat or written notes): run `session_search` first for conversational evidence, then `memory_search` for durable notes; merge and attribute each source.',"If a listed memory tool call fails, report the failure; do not claim the tool is unavailable. Use `memory_list` before update/delete when needed.","Short tool chains: `memory_search` → `memory_get`; `memory_list` → `memory_update`; `memory_search` → `memory_forget`.",`Routing examples (intent → tool):`,'1) "上次聊天我们怎么修的" → `session_search` with keywords from the bug/symptom.','2) "团队对 release 的硬性规范是什么" → `memory_search` (durable policy).','3) "最近几个会话在忙什么" → `session_search` with no query (recent mode).','4) "把这条写进长期记忆" → `memory_write` (default), not `memory_log` or `session_search`.','5) "昨天日志里有没有记过 X" → `memory_search` on daily logs / `memory_list`.','6) "上次口头结论 vs 正式文档" → `session_search` then `memory_search`.',e===`off`?`Citations are disabled: do not include memory file paths or line numbers unless the user explicitly asks.`:`When useful, include memory evidence as Source: <path#line>.`,``].join(`
86
+ `)}function is(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`,o=e.projectDir?.trim(),s=o?[`Current project directory: ${o}`,`Treat this project directory as the default cwd for repository/code work unless the user specifies another directory.`]:[];return[`## Workspace`,`Your cloud working directory is: ${r}`,...s,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, MEMORY.md, and the memory/ directory belong under ${t}.`,`Only create or update those files at their real .aimax paths. Never create cloud workspace copies like ${r}/AGENTS.md or ${r}/MEMORY.md unless the user explicitly asks for separate cloud documents.`,``].join(`
87
+ `)}function as(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(`
88
+ `)}function os(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=ss(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
89
+ `)}function ss(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),a=new Date(Date.UTC(n,r-1,i));return Number.isNaN(a.getTime())||a.getUTCFullYear()!==n||a.getUTCMonth()!==r-1||a.getUTCDate()!==i?null:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`][a.getUTCDay()]}function cs(e){if(e.isMinimal||!e.enabled)return``;let t=(e.channels??[]).map(e=>e.trim()).filter(Boolean);return[`## Messaging`,`Reply in the current session for user-visible responses.`,`Use subagent tools only when the user or system instructions explicitly require subagents, delegation, or parallel agent execution; otherwise stay in the current agent.`,`Do not use shell/network commands to bypass the platform messaging pipeline.`,t.length>0?`Configured channels: ${t.join(` | `)}`:``,``].filter(Boolean).join(`
90
+ `)}function ls(e){if(!e)return``;let t=[e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
91
+ `)}function us(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(`
92
+ `)}function ds(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(`
93
+ `)}function fs(e){return e<=0?``:[`## Subagent Constraint`,`You are running as a subagent (nesting depth: ${e}). Your role is to complete the delegated task directly using available tools.`,`Do NOT spawn further subagents unless the task absolutely cannot be completed any other way.`,`If you find yourself wanting to use subagent_spawn, first ask whether a direct tool call (exec, read_file, write_file, edit_file, etc.) can achieve the same result.`,`Subagent nesting adds overhead and complexity — prefer direct execution in all but the most exceptional cases.`,``].join(`
94
+ `)}function ps(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(`
95
+ `):``}function ms(e){let t=e.promptMode??`full`,n=t===`minimal`,r=e.activeAgentSystemPrompt?.trim()||e.presetSystemPrompt||`You are a personal assistant running inside AiMax.`;if(t===`none`)return r;let i=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Jo],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,fs(e.subagentDepth??0),Xo({toolNames:i,toolSummaries:e.toolSummaries}),$o(n),Zo(),Nt(e.availableAgents??[]),es(a),ts(),ns(),rs(e.memoryCitationsMode??`off`),is({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),as(e.sandboxInfo),os({currentDate:e.currentDate,timezone:e.timezone}),Qo(),cs({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),us({isMinimal:n}),ls(e.runtimeInfo),ds({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),ps(e.priorConversationSummary)].filter(Boolean).join(`
96
+ `)}const hs=new $e;async function gs(e,t){return await hs.run(e,t)}function _s(e){return{async emit(t){let n=hs.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const vs=Symbol(`pluginToolOwner`);var ys=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,vs,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=Go({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,vs,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function bs(e){return e[vs]}const xs=new $e;function Ss(){return{}}async function Cs(e,t){return await xs.run(e,t)}function ws(e){let t=xs.getStore();!t||t.signal||(t.signal=e)}function Ts(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=bs(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await gs({pluginId:o,hookContext:n,eventDispatcher:r.eventDispatcher},e):await e(),h;try{h=await t.dispatch(`before_tool_call`,{toolCallId:e,toolName:a,params:d},n,r)}catch(e){if(Y(e))return ws(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}for(let e of h)e&&(e.params&&(d=e.params),e.block&&(f=!0,p=e.blockReason));if(f)return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:p??`blocked by plugin`,durationMs:Date.now()-u},n,r),{content:[{type:`text`,text:p??`Tool blocked by plugin`}],isError:!0,details:{}};try{let o=await m(async()=>await i.execute(e,d,c,l));return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}catch(i){if(Y(i)){ws(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}var Es=class{hooks=new Map;register(e){let t=this.hooks.get(e.hookName)??[];t.push(e),t.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,t)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await gs({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const $={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Ds(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Os(e){let t=Ds(e?.warningThreshold,$.warningThreshold),n=Ds(e?.criticalThreshold,$.criticalThreshold),r=Ds(e?.globalCircuitBreakerThreshold,$.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??$.enabled,historySize:Ds(e?.historySize,$.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??$.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??$.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??$.detectors.pingPong}}}function ks(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function As(e,t){return`${e}:${Ns(t)}`}function js(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(js).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${js(t[e])}`).join(`,`)}}`}function Ms(e){try{return js(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 Ns(e){let t=Ms(e);return qe(`sha256`).update(t).digest(`hex`)}function Ps(e,t){if(e===`command_status`)return!0;if(e!==`process`||!ks(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Fs(e){return!ks(e)||!Array.isArray(e.content)?``:e.content.filter(e=>ks(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
97
+ `).trim()}function Is(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:js(e)}function Ls(e,t,n,r){if(r!==void 0)return`error:${Ns(Is(r))}`;if(!ks(n))return n===void 0?void 0:Ns(n);let i=ks(n.details)?n.details:{},a=Fs(n);if(Ps(e,t)&&e===`process`&&ks(t)){let e=t.action;if(e===`poll`)return Ns({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Ns({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 Ns({details:i,text:a})}function Rs(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 zs(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 Bs(e,t){return[e,t].toSorted().join(`|`)}function Vs(e,t,n,r){let i=Os(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=As(t,n),s=Rs(a,t,o),c=s.count,l=Ps(t,n),u=zs(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:${Bs(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 Hs(e,t,n,r,i){let a=Os(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:As(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Us(e,t){let n=Os(t.config),r=Ls(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=As(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 Ws(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 Gs(e){return e&&e.trim()||`tool`}function Ks(e,t,n){if(!e.execute)return e;let r=Gs(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Vs(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ws(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Hs(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Us(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Us(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function qs(e,t,n){return e.map(e=>Ks(e,t,n))}async function Js(e){let{session:{runParams:t,sessionId:n,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:s},runtimeInputs:{contextFiles:c,bootstrapWarnings:l,skills:u,effectivePromptText:f,pluginTools:p,pluginSkillDirs:m,skillsLoadPaths:h,presetSystemPrompt:g},dependencies:{registry:_,spawnFn:v,createModel:y,abortSignal:b}}=e,x=t.agentPolicy?.activeAgent,S=t.channel===`CRON`,C=S?[]:await r(t.dataDir,n,q(t)),w={model:t.llm.model,api:`openai-completions`},T=await gi({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),E=S?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await _i({entries:C,modelInfo:w,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,pendingUserMessage:f,signal:b,hooks:i,hookCtx:a,contextManager:T,dataDir:t.dataDir,sessionId:n});await Xs({sessionId:n,historyResult:E,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let D=t.subagentContext?.depth??0,O=d(t.dataDir,n,q(t)),k=Mt([...Ko(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:O,registry:_,parentSessionId:n,depth:D,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:h,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy},loopDetection:t.loopDetection,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:m,skillsLoadPaths:h,reportSkillUsed:async e=>{await s.dispatchProgress(n,e)},contextManager:T,hitlResume:t.hitlResume,spawnFn:v}),...p],x),A=k.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),ee={};for(let e of k){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||ee[t]||(ee[t]=n)}let j=t.messaging?.enabled??t.channel!==`CRON`,M=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],N=ms({dataDir:t.dataDir,projectDir:t.projectDir,skills:jt(u,x),contextFiles:c,toolNames:A,toolSummaries:ee,promptMode:D>0?`minimal`:`full`,subagentDepth:D,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:j,channels:M},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Xe.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:x?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:E.priorSummary});N=await Ys({systemPrompt:N,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let P=await i.dispatch(`before_prompt_build`,{prompt:f},a,{eventDispatcher:s});for(let e of P)e&&(e.systemPrompt&&(N=e.systemPrompt),e.prependContext&&(N=`${e.prependContext}\n\n${N}`));await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:N},a,{eventDispatcher:s});let F=qs(Ts(k,i,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},rn),I=x?.model??t.llm.model,L=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of L)e&&e.modelOverride&&(I=e.modelOverride);let R=y({...t.llm,model:I},n,t.messageId,t.channel),z=new Ye({initialState:{systemPrompt:N,model:R,tools:F,messages:[]},getApiKey:e=>t.llm.apiKey});return E.messages.length>0&&z.replaceMessages(E.messages),{agent:z,resolvedModelId:I,historyMessages:E.messages,historyResult:E,contextManager:T,usageBaselineTranscriptEntryCount:C.length,workspaceDir:o.workspaceDir}}async function Ys(e){if((await te(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})).length<=8)return e.systemPrompt;let t=`Older CRON execution records for this session are stored outside the main transcript at ${x(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})}. The main transcript keeps only the latest 8 CRON summaries. Read that jsonl file explicitly if older CRON outcomes matter.`;return`${e.systemPrompt}\n\n${t}`}async function Xs(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount,s=Zs(await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i})),c=s.injectRecall?{...n.compactionEntry,content:`${s.injectRecall.trim()}\n\n${n.compactionEntry.content}`}:n.compactionEntry;if(s.skipPersist){await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!s.injectRecall}});return}await r.appendTranscriptEntry(c),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o,{eventDispatcher:i})}}function Zs(e){let t=!1,n=[];for(let r of e)r&&(r.skipPersist&&(t=!0),typeof r.injectRecall==`string`&&r.injectRecall.trim().length>0&&n.push(r.injectRecall.trim()));return{skipPersist:t,injectRecall:n.length>0?n.join(`
98
+
99
+ `):void 0}}const Qs=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),$s=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]);function ec(e){let t=ic(e?.maxAttempts,3),n=ac(e?.initialDelayMs,250),r=ac(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function tc(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function nc(e,t){if(!(e<=0)){if(t?.aborted)throw Error(`aborted`);await new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`aborted`))},{once:!0})})}}function rc(e){if(sc(e))return!1;let t=oc(e);if(t?.statusCode!==void 0)return lc(t.statusCode);if(t?.providerCode!==void 0)return cc(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Qs.has(e))return!0;if($s.has(e))return!1}return t?.code===`timeout`||t?.code===`network_error`?!0:t?.code===`aborted`||t?.code===`invalid_response`?!1:t?.retryable===!0}function ic(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function ac(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function oc(e){if(!e||typeof e!=`object`)return null;let t=e;return t.retryable===void 0&&t.statusCode===void 0&&t.code===void 0&&t.providerCode===void 0&&t.providerType===void 0?null:{message:typeof t.message==`string`?t.message:void 0,code:t.code,statusCode:t.statusCode,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable}}function sc(e){return oc(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function cc(e){return/^\d+$/.test(e)?lc(Number(e)):!1}function lc(e){return e===408||e===409||e===425||e===429||e>=500}async function uc(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,onTurnRecordProduced:f}=e,p=``,m=``,h=``,g=0,_=0,v,y,b=0,x=0,S=[],C=new Map,w=new Map,T=new Set,E=Ss(),D=Vo(),O=new Set,k=Promise.resolve(),A,ee=e=>{O.add(e),e.catch(e=>{A??=e}).finally(()=>{O.delete(e)})},j=async()=>{for(;O.size>0;)await Promise.allSettled([...O]);if(A)throw A},M=t.subscribe(e=>{let t=k.then(()=>N(e));k=t.catch(()=>{}),ee(t)});async function N(e){let n=()=>!!D.signal||E.signal?.transparentPause===!0;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(x===0&&(t.type===`text_delta`||t.type===`done`)&&(x=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=Dc(`partial`in t?t.partial:void 0)??Dc(`message`in t?t.message:void 0)??Dc(`message`in e?e.message:void 0),a=Oc(t.delta,r,m);r?(m=r,h=r):a&&(h+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){p=``,m=``,h=``,e.usage&&(g=e.usage.input,_=e.usage.output);return}p=Tc(e);let r=Oc(``,p,h||m);m=p,h=p,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(g=e.usage.input,_=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(g=t.usage.input,_=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Tc(e);await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:t.usage?{input:g,output:_,total:g+_}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(y=mc(t));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:Cc(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),r=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),a=new Set(n.map(e=>e.toolCallId));for(let e of w.values())!a.has(e.toolCallId)&&r.has(e.toolCallId)&&n.push(e);for(let e of n)w.delete(e.toolCallId);if(S.push({message:t,toolResults:n}),f){let e=!!E.signal,r=!!D.signal;if(e&&E.signal.transparentPause||await f(xc(bc(t),e||r),r?[]:n.map(Sc)),e||r)return}return}if(e.type===`tool_execution_start`){h=``,C.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=typeof e.result==`string`?e.result:JSON.stringify(e.result),r=Ec(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Cc(r,i,e.toolCallId,e.toolName),c=C.get(e.toolCallId);if(C.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}w.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let P=ec(d),F=P.enabled?P.maxAttempts:1;try{for(let e=1;e<=F;e++){let d=S.length;y=void 0,v=void 0;try{if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);W.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:F,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),b=Date.now(),await Cs(E,async()=>{await Ho(D,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await j();let f=E.signal;if(f)throw f;let m=D.signal;if(m)throw m;let h=typeof t.state.error==`string`?t.state.error:void 0,x=y??h;if(x){if(v=kc(x),W.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:F,error:v}),await L(x,v,e,d))continue;await s.dispatchProgress(i,{type:`error`,message:v})}v||W.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:F,inputTokens:g,outputTokens:_,turnRecordCount:S.length-d,textLength:p.length});break}catch(t){if(await j(),Y(t)||zo(t))throw t;if(v=kc(t),W.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:F,error:v}),await L(t,v,e,d))continue;await s.dispatchProgress(i,{type:`error`,message:v});break}}}finally{M()}function I(){p=``,m=``,h=``}async function L(e,n,r,a){if(!dc({error:e,attempt:r,maxAttempts:F,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=tc(r,P);return W.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:F,delayMs:o,error:n}),await _c({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:F,message:n,delayMs:o}),S.length=a,I(),vc(t),await nc(o,u),!0}let R=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:R,durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:{input:g,output:_,total:g+_}},l);let z=(D.signal?``:S.length>0?Tc(S[S.length-1].message):``)||p||pc(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return f&&!fc(S)&&!v&&p.trim().length>0&&await f({role:`assistant`,content:p,timestamp:new Date().toISOString()},[]),{text:z,inputTokens:g,outputTokens:_,error:v,turnRecords:S}}function dc(e){return e.attempt>=e.maxAttempts||!rc(e.error)||e.finalAssistantText.trim().length>0||e.streamedAssistantSnapshot.trim().length>0||e.streamedTextSinceBoundary.trim().length>0?!1:e.turnRecords.slice(e.attemptTurnRecordStart).every(e=>e.toolResults.length===0&&Tc(e.message).trim().length===0)}function fc(e){return e.some(e=>bc(e.message)!==null||e.toolResults.length>0)}function pc(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];for(let e=r.toolResults.length-1;e>=0;e--){let n=r.toolResults[e];if(n.toolName===t&&n.content.trim().length>0)return n.content}}return``}function mc(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:hc(t.errorCode),statusCode:gc(t.statusCode),providerCode:hc(t.providerCode),providerType:hc(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function hc(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function gc(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function _c(e){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`runner`,phase:`llm_turn_retry_scheduled`,message:`retrying transient LLM turn failure`,details:{attempt:e.attempt,nextAttempt:e.attempt+1,maxAttempts:e.maxAttempts,delayMs:e.delayMs,error:e.message}})}function vc(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&yc(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function yc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function bc(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 xc(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Sc(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function Cc(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:wc(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function wc(e){let t=e.indexOf(`
97
100
  Preview:
98
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function vc(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function yc(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}function bc(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 xc(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Sc(e){let t=Cc(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 Cc(e){if(e instanceof G)return e;if(e&&typeof e==`object`&&!(e instanceof Error)){let t=e,n=typeof t.message==`string`&&t.message.trim()?t.message:void 0;return!n&&t.code===void 0&&t.statusCode===void 0?null:{message:n??`Unknown LLM error`,code:cc(t.code),statusCode:lc(t.statusCode),statusText:cc(t.statusText),providerMessage:cc(t.providerMessage)}}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 wc(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!c?.aborted&&n.needsAnnounce(r)&&d<10;){d++,W.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){W.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}W.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:d,completedCount:e.length,runIds:e.map(e=>e.runId).join(`,`),statuses:e.map(e=>e.status).join(`,`)});for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=Tc(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await rc({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,onTurnRecordProduced:async(e,t)=>{e&&await u(e);for(let e of t)await u(e)}});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),n.markAnnounced(e.map(e=>e.runId));let v={sessionId:r,announceRound:d,completedCount:e.length,inputTokens:_.inputTokens,outputTokens:_.outputTokens,hasError:!!_.error,error:_.error,responseTextLength:_.text.length};_.error?W.warn(`subagent announce round completed with error`,v):W.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&W.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function Tc(e){if(e.length===1){let t=e[0];return bo({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>bo({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
101
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Tc(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Ec(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}function Dc(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 Oc(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function kc(e){let t=Ac(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 Ac(e){if(e instanceof G)return e;if(e&&typeof e==`object`&&!(e instanceof Error)){let t=e,n=typeof t.message==`string`&&t.message.trim()?t.message:void 0;return!n&&t.code===void 0&&t.statusCode===void 0?null:{message:n??`Unknown LLM error`,code:hc(t.code),statusCode:gc(t.statusCode),statusText:hc(t.statusText),providerMessage:hc(t.providerMessage)}}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 jc(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!c?.aborted&&n.needsAnnounce(r)&&d<10;){d++,W.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){W.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}W.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:d,completedCount:e.length,runIds:e.map(e=>e.runId).join(`,`),statuses:e.map(e=>e.status).join(`,`)});for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=Mc(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await uc({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,onTurnRecordProduced:async(e,t)=>{e&&await u(e);for(let e of t)await u(e)}});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),n.markAnnounced(e.map(e=>e.runId));let v={sessionId:r,announceRound:d,completedCount:e.length,inputTokens:_.inputTokens,outputTokens:_.outputTokens,hasError:!!_.error,error:_.error,responseTextLength:_.text.length};_.error?W.warn(`subagent announce round completed with error`,v):W.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&W.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function Mc(e){if(e.length===1){let t=e[0];return Do({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Do({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
99
102
 
100
103
  ---
101
104
 
102
- `)}`}function Ec(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function Dc(e){let t=Ec(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=V.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function Oc(e){let t=e.watchFactory??((e,t,n)=>H.watch(e,t,n)),n=V.join(e.dataDir,`.aimax`),r=[{target:V.join(n,`MEMORY.md`),kind:`memory-file`},{target:V.join(n,`memory.md`),kind:`memory-file-lower`},{target:V.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=Dc({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}async function kc(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=V.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Mc(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??h.id})`:`memory_log routed to ${t} (provider=${p.providerId??h.id})`,details:{providerId:p.providerId??h.id,resolvedProviderId:m?.registration.id??h.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof h.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=V.join(t.dataDir,`.aimax`),m=I({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=m?.provider??D({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g=m?.registration.id??h.id,_=m?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:g,pluginId:_,providerSource:m?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!m}}).catch(()=>{});let v=Oc({dataDir:t.dataDir,sessionId:i,providerId:o??s??g,provider:h,onMemoryChanged:f});h.sync&&h.sync(`session-start`).catch(()=>{});let b=async e=>{await y(t.dataDir,i,e,jc({sessionOptions:q(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{v()}}}function Ac(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function jc(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function Mc(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}function Nc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pc(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Fc(){let e=He.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ic(e){let t=e.trim(),n=Fc();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?V.join(n,t.slice(2)):void 0:V.resolve(t)}const Lc=new qe({allErrors:!0,strict:!1}),Rc=new Map;function zc(e,t){let n=Rc.get(t);if(n)return n;let r=Lc.compile(e);return Rc.set(t,r),r}function Bc(e){let t=e.cacheKey??JSON.stringify(e.schema),n=zc(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Vc(e){let t=Pc(e?.allow),n=Pc(e?.deny),r=Pc(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 Hc(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=Bc({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 Uc(e){try{return H.realpathSync(e)}catch{return null}}function Wc(e){try{return H.statSync(e)}catch{return null}}function Gc(e,t){let n=V.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!V.isAbsolute(n)}function Kc(e){return`0o${e.toString(8).padStart(3,`0`)}`}const qc=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Jc=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Yc(e){let t=V.join(e,`package.json`);if(H.existsSync(t))try{let e=JSON.parse(H.readFileSync(t,`utf-8`));return Nc(e)?e:void 0}catch{return}}function Xc(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 Zc(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Qc(e){let t=Uc(e.source),n=Uc(e.rootDir);return!t||!n||Gc(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function $c(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=V.resolve(r);if(n.has(t))continue;n.add(t);let i=Wc(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 el(e){return Qc({source:e.source,rootDir:e.rootDir})||$c({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Zc(e.ownershipUid)})}function tl(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=${Kc(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function nl(e){let t=el({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:tl(t),source:e.source}),!0):!1}function rl(e){return V.basename(e,V.extname(e))}function il(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 al(e){for(let t of Jc){let n=V.join(e,t);if(H.existsSync(n))return n}return null}function ol(e){let t;try{t=H.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=V.join(e.rootDir,n.name);if(n.isFile()){if(!qc.has(V.extname(n.name)))continue;let r=V.dirname(t);if(nl({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(il({idHint:rl(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Yc(t),i=Xc(r);if(i.status===`ok`){for(let n of i.entries){let i=V.resolve(t,n);if(!Gc(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!H.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!qc.has(V.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(nl({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${rl(i)}`:rl(i);e.candidates.push(il({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=al(t);a&&(nl({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(il({idHint:V.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function sl(e){return e?e.map(Ic).filter(e=>typeof e==`string`&&e.length>0):[]}function cl(){let e=Fc();if(e)return V.join(e,`.aimax`,`extensions`)}function ll(e){return V.join(e,`.aimax`,`extensions`)}function ul(e){return V.join(e,`.aimax`,`extensions`)}function dl(e={}){let t=[],n=[],r=sl(e.extraPaths);for(let i of r){if(!H.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Wc(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!qc.has(V.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=V.dirname(i);if(nl({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(il({idHint:rl(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&ol({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?ol({rootDir:ll(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&ol({rootDir:ul(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=cl();return i?ol({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&ol({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function fl(e){let t=e.rejectHardlinks??!0,n=Uc(e.rootPath),r=Uc(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!Gc(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=H.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:H.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const pl=`aimax.plugin.json`,ml=[pl];function hl(e){for(let t of ml){let n=V.join(e,t);if(H.existsSync(n))return n}return V.join(e,pl)}function gl(e,t=!0){let n=hl(e),r=fl({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(H.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{H.closeSync(r.fd)}if(!Nc(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=Nc(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=Pc(i.skills),f;return Nc(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 _l(e){let t=new Map,n=[];for(let r of e){let e=gl(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let vl=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function yl(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===vl.ERROR){W.error(i);return}if(e===vl.WARN){W.warn(i);return}W.info(i)}function bl(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>yl(vl.INFO,e.pluginId,t,n),warn:n=>yl(vl.WARN,e.pluginId,t,n),error:n=>yl(vl.ERROR,e.pluginId,t,n)})}}}function xl(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 Sl(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 Cl(e){let t=[...e.registry.diagnostics],n=new fs,r=new ys,i=[],a=[],o=e.runtime?.llm?Qt({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=wl(e.runtime?.llmAllowlist),c=Je(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=xl({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Sl({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f;try{f=c(l.source)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let p=f&&typeof f==`object`&&`default`in f?f.default:f,m=typeof p==`function`?p:p&&typeof p==`object`&&typeof p.register==`function`?p.register:void 0;if(!m){d.status=`error`,d.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let h=bl({pluginId:l.id}),g=e.plugins.entries[l.id]?.config,_={id:l.id,source:l.source,rootDir:l.rootDir,config:g,runtime:h,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Tl(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);S({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);L({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=V.isAbsolute(e)?e:V.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>us(l.id)};try{m(_)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=V.isAbsolute(e)?e:V.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function wl(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Tl(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function El(e={}){let t=Vc(e.config),n=dl({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=_l(n.candidates),i=Hc({config:t,registry:r}),a=Cl({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 Dl(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?El({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new ys,pluginSkillDirs:o?.registry.skills??[],pluginTools:[...o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...o?.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function Ol(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=V.join(t.dataDir,`workspace`),a=n,o=!a,s=q(t);a?(await c(t.dataDir,a,s)||(o=!0),await M(t.dataDir,a,s)):a=await b(t.dataDir,t.channel,{...s});let l={sessionId:a,workspaceDir:i,channel:t.channel},u=Dl({runParams:t,hookContext:l,sessionId:a,eventDispatcher:r}),d=u.hookRegistry,f=await kc({runParams:t,sessionId:a,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:r,hookRegistry:d});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:l,hookRegistry:d,pluginContext:u,runContext:f,start:e=>Pn({sessionId:a,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:r,...e})}}function kl(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Al(e){if(!(e instanceof Error))return{errorValue:kl(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=kl(n[e]));return t}async function jl(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Al(e.error)}})}function Ml(e,t,n){return V.join(s(e,t,n),`pending-hitl.json`)}function Nl(e,t,n){return V.join(s(e,t,n),`hitl-history.jsonl`)}async function Pl(e,t,n,r){let i=s(e,t,r);await B.mkdir(i,{recursive:!0});let a=Ml(e,t,r);await B.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function Fl(e,t,n,r){let i=s(e,t,r);await B.mkdir(i,{recursive:!0});let a=Nl(e,t,r),o=JSON.stringify(n)+`
103
- `;await B.appendFile(a,o,`utf-8`)}async function Il(e,t,n){let r=Ml(e,t,n);try{let e=await B.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ll(e,t,n){let r=Nl(e,t,n);try{let e=await B.readFile(r,`utf-8`),t=[];for(let n of e.split(`
104
- `)){let e=n.trim();if(e)try{t.push(JSON.parse(e))}catch{}}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Rl(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await Pl(e,t,c,o),await Fl(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function zl(e,t,n,r,i,a){let o=await Il(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await Pl(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await Fl(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function Bl(e,t,n,r){let i=await Il(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function Vl(e,t,n){let r=Ml(e,t,n);try{await B.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function Hl(e,t,n){return V.join(s(e,t,n),`pending-ui-tool.json`)}async function Ul(e,t,n,r){let i=s(e,t,r);await B.mkdir(i,{recursive:!0}),await B.writeFile(Hl(e,t,r),JSON.stringify(n,null,2),`utf-8`)}async function Wl(e,t,n){try{let r=await B.readFile(Hl(e,t,n),`utf-8`);return JSON.parse(r)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Gl(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Ul(e,t,a,r),a}async function Kl(e,t,n,r,i){let a=await Wl(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await Ul(e,t,o,i),o}async function ql(e,t,n){try{await B.unlink(Hl(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const Jl=`crons`;function Yl(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:Gt(e.message)}}function Xl(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{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:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}function Zl(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!ye(t))}async function Ql(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=hs();if(i=await gs(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Y(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=$l(i),s=i&&typeof i==`object`?i.details:void 0,c=s&&typeof s==`object`?s.toolResultRef:void 0;return await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_end`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs,output:o,isError:a}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:o,isError:a,...c?{toolResultRef:c}:{},timestamp:new Date().toISOString()}),{text:o,error:a?o:void 0}}function $l(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}async function eu(e,t){Wt(e.dataDir),On();let n=Date.now(),r=new kn(e),i=br(e);W.info(`agent invocation prepared`,{requestedSessionId:i.requestedSessionId,previousSessionId:i.previousSessionId,inputMode:i.inputMode,hasSlashCommand:!!i.slashCommandSource,resetAction:i.resetCommand?.action,resetShortCircuit:i.resetShortCircuit,transcriptLength:i.transcriptMessage.length,messageForRunLength:i.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await Ol({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;W.info(`agent run started`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:u,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),W.info(u?`session created`:`session resumed`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await C(e.dataDir,Ac({sessionId:l,title:Nn(a),channel:e.channel}),q(e)),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(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 $e(e.dataDir),v=[],y=nt(_,{warn:e=>v.push(e)}),b=await at();await r.dispatchDiagnostic(l,{level:v.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length}}),W.info(`bootstrap context loaded`,{sessionId:l,bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length});let x=e.skillsLoadPaths??[],S=await dt(e.dataDir,m.pluginSkillDirs,x),w=e.agentPolicy?.availableAgents??await bt({dataDir:e.dataDir,projectDir:e.projectDir}),T=e.agentPolicy?.activeAgent??Ct(w,e.agentPolicy?.requestedAgentName);if(e.agentPolicy?.requestedAgentName&&!T)throw Error(`Unknown custom agent: ${e.agentPolicy.requestedAgentName}`);let E={availableAgents:w,...T?{activeAgent:T}:{},...e.agentPolicy?.requestedAgentName?{requestedAgentName:e.agentPolicy.requestedAgentName}:{}},D={...e,agentPolicy:E};await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:S.length,pluginSkillDirCount:m.pluginSkillDirs.length,skillsLoadPathCount:x.length,skills:S.map(e=>({name:e.name,description:e.description,location:e.location}))}}),W.info(`skills loaded`,{sessionId:l,skillCount:S.length,pluginSkillDirCount:m.pluginSkillDirs.length,skillsLoadPathCount:x.length}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:w.length,activeAgent:E.activeAgent?.name,agents:w.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),W.info(`custom agents loaded`,{sessionId:l,agentCount:w.length,activeAgent:E.activeAgent?.name,requestedAgentName:E.requestedAgentName});let O=e=>h.appendTranscriptEntry(e),k=await Sr({invocation:i,skills:S,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(k.kind===`completed`)return W.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!k.result.error,paused:!!k.result.paused,uiToolPending:!!k.result.uiToolPending,textLength:k.result.text.length}),k.result;let A=k.effectivePrompt;a=k.transcriptMessage;let ee=typeof A==`string`?A:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof A==`string`?`string`:`messages`,transcriptLength:a.length}}),W.info(`invocation resolved`,{sessionId:l,promptType:typeof A==`string`?`string`:`messages`,transcriptLength:a.length});let j=await Vs({session:{runParams:D,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:S,effectivePromptText:ee,pluginTools:m.pluginTools,pluginSkillDirs:m.pluginSkillDirs,skillsLoadPaths:x,presetSystemPrompt:b.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>eu(e,new Jt),createModel:Xl,abortSignal:g.signal}}),M=j.agent,N=j.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:N,historyMessageCount:j.historyMessages.length,pluginToolCount:m.pluginTools.length}}),W.info(`agent runtime created`,{sessionId:l,modelId:N,historyMessageCount:j.historyMessages.length,pluginToolCount:m.pluginTools.length}),g.signal.addEventListener(`abort`,()=>M.abort());let P=0,F=0,I=``,L,R=!1;try{if(Zl(e)){let t=await Ql({params:e,agent:M,sessionId:l,eventDispatcher:r,appendEntry:O,abortSignal:g.signal});return I=t.text,Ln({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:I,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await h.persistInitialUserEntry(a);R=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`}),W.info(`first agent turn started`,{sessionId:l,modelId:N});let i=await rc({agent:M,message:A,continueFromHistory:!!e.uiToolResume,sessionId:l,modelId:N,historyMessages:j.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:g.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await O(e);for(let e of t)await O(e)}});I=i.text,P+=i.inputTokens,F+=i.outputTokens,i.error&&(L=i.error),await r.dispatchDiagnostic(l,{level:i.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!i.error,error:i.error,inputTokens:i.inputTokens,outputTokens:i.outputTokens}});let s={sessionId:l,hasError:!!i.error,error:i.error,inputTokens:i.inputTokens,outputTokens:i.outputTokens};i.error?W.warn(`first agent turn completed with error`,s):W.info(`first agent turn completed`,s),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),W.info(`announce loop started`,{sessionId:l});let c=await wc({agent:M,registry:t,sessionId:l,resolvedModelId:N,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:g.signal,retry:e.llmRetry,appendEntry:O});c.text&&(I=c.text),P+=c.inputTokens,F+=c.outputTokens,c.error&&!L&&(L=c.error),await r.dispatchDiagnostic(l,{level:c.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let d={sessionId:l,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?W.warn(`announce loop completed with error`,d):W.info(`announce loop completed`,d)}catch(t){if(Y(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await Rl(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),W.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:P,output:F,total:P+F};return await tu({runtime:j,resolvedModelId:N,usage:c,currentUserEntryCoveredByUsage:R}),Ln({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:I||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Mo(t)){let i=t,o=i.request.outputSchema.properties??{};await Gl(e.dataDir,l,i.request,q(e)),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length}}),W.info(`agent paused for UI tool input`,{sessionId:l,requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length});let s={input:P,output:F,total:P+F};return await tu({runtime:j,resolvedModelId:N,usage:s,currentUserEntryCoveredByUsage:R}),Ln({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:I||``,usage:s,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}throw await jl({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),W.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{Zt(l),h.stop()}let z={input:P,output:F,total:P+F};await r.dispatchDiagnostic(l,{level:L?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:z.input,outputTokens:z.output,totalTokens:z.total,hasError:!!L,error:L}});let te={sessionId:l,durationMs:Date.now()-n,inputTokens:z.input,outputTokens:z.output,totalTokens:z.total,hasError:!!L,error:L};return L?W.warn(`agent run completed with error`,te):W.info(`agent run completed`,te),await tu({runtime:j,resolvedModelId:N,usage:z,currentUserEntryCoveredByUsage:R}),Ln({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:I,usage:z,error:L})}async function tu(e){let{runtime:t,resolvedModelId:n,usage:r,currentUserEntryCoveredByUsage:i}=e;r.input<=0&&r.total<=0||await t.contextManager.recordModelUsage({model:n,inputTokens:r.input,outputTokens:r.output,totalTokens:r.total,coveredTranscriptEntryCount:t.usageBaselineTranscriptEntryCount+(i?1:0)})}async function nu(t){Wt(t.dataDir);let n=Date.now(),r=new kn(t),i=br(t),o=i.transcriptMessage.trim()||`CRON task`,s=t.sessionStoreName;W.info(`cron run started`,{requestedSessionId:i.requestedSessionId,channel:t.channel,sessionStoreName:s,...Yl(t)});let l=i.requestedSessionId,u=!l;l?(await c(t.dataDir,l,{storeName:s})||(u=!0),await M(t.dataDir,l,{storeName:s})):l=await b(t.dataDir,t.channel,{storeName:s}),u&&await C(t.dataDir,Ac({sessionId:l,title:Nn(o),channel:t.channel}),{storeName:s});let f=await b(t.dataDir,t.channel,{storeName:Jl});await r.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:f,task:o}),W.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:f,taskLength:o.length,taskPreview:Gt(o)});let p={...t,sessionId:f,sessionStoreName:Jl,subagentContext:{depth:1,parentSessionId:l}},m,h=`done`;try{m=await eu(p,new Jt),m.error&&(h=`error`)}catch(e){let r=e instanceof Error?e.message:String(e);m={sessionId:f,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:x(t.dataDir,f,{storeName:Jl}),toolResultsDir:a(t.dataDir,f,{storeName:Jl})}},h=`error`,W.error(`cron child run failed`,{parentSessionId:l,childSessionId:f,error:r})}await r.dispatchProgress(l,{type:`subagent_complete`,childSessionId:f,task:o,status:h}),W.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:f,status:h,durationMs:Date.now()-n,hasError:!!m.error});let g=bo({task:o,status:h,result:m.text,error:m.error}),_=new Date().toISOString();await y(t.dataDir,l,{role:`assistant`,content:g,timestamp:_,source:`cron`},{storeName:s});let S={task:o,status:h,content:g,childSessionId:f,createdAt:_};return await v(t.dataDir,l,S,{storeName:s}),await e(t.dataDir,l,e=>ru(e,8),{storeName:s}),await d(t.dataDir,l,{},{storeName:s}),{...m,sessionId:l,context:{snapshotPath:x(t.dataDir,l,{storeName:s}),toolResultsDir:a(t.dataDir,l,{storeName:s})}}}function ru(e,t){if(t<=0)return e.filter(e=>!iu(e));let n=e.reduce((e,t,n)=>(iu(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!iu(e)||r.has(t))}function iu(e){return`source`in e&&e.source===`cron`}async function au(e,t){if(Wt(e.dataDir),W.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...Yl(e)}),e.channel===`CRON`&&!e.subagentContext)return nu(e);let n=t??new Jt;try{return await eu(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:Al(t)}),W.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}const ou={"AGENTS.md":`---
105
+ `)}`}function Nc(e){if(!e)return null;let t=(typeof e==`string`?e:e.toString(`utf-8`)).replace(/\\/g,`/`).replace(/^\.\//,``).trim();return t.length>0?t:null}function Pc(e){let t=Nc(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=V.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function Fc(e){let t=e.watchFactory??((e,t,n)=>H.watch(e,t,n)),n=V.join(e.dataDir,`.aimax`),r=[{target:V.join(n,`MEMORY.md`),kind:`memory-file`},{target:V.join(n,`memory.md`),kind:`memory-file-lower`},{target:V.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=Pc({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}async function Ic(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=V.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=zc(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??h.id})`:`memory_log routed to ${t} (provider=${p.providerId??h.id})`,details:{providerId:p.providerId??h.id,resolvedProviderId:m?.registration.id??h.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof h.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=V.join(t.dataDir,`.aimax`),m=ae({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=m?.provider??N({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g=m?.registration.id??h.id,_=m?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:g,pluginId:_,providerSource:m?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!m}}).catch(()=>{});let v=Fc({dataDir:t.dataDir,sessionId:i,providerId:o??s??g,provider:h,onMemoryChanged:f});h.sync&&h.sync(`session-start`).catch(()=>{});let y=async e=>{await E(t.dataDir,i,e,Rc({sessionOptions:q(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:y,persistInitialUserEntry:async e=>d?!1:(await y({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{v()}}}function Lc(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Rc(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function zc(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}function Bc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vc(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Hc(){let e=Xe.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Uc(e){let t=e.trim(),n=Hc();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?V.join(n,t.slice(2)):void 0:V.resolve(t)}const Wc=new et({allErrors:!0,strict:!1}),Gc=new Map;function Kc(e,t){let n=Gc.get(t);if(n)return n;let r=Wc.compile(e);return Gc.set(t,r),r}function qc(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Kc(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Jc(e){let t=Vc(e?.allow),n=Vc(e?.deny),r=Vc(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 Yc(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=qc({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 Xc(e){try{return H.realpathSync(e)}catch{return null}}function Zc(e){try{return H.statSync(e)}catch{return null}}function Qc(e,t){let n=V.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!V.isAbsolute(n)}function $c(e){return`0o${e.toString(8).padStart(3,`0`)}`}const el=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),tl=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function nl(e){let t=V.join(e,`package.json`);if(H.existsSync(t))try{let e=JSON.parse(H.readFileSync(t,`utf-8`));return Bc(e)?e:void 0}catch{return}}function rl(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 il(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function al(e){let t=Xc(e.source),n=Xc(e.rootDir);return!t||!n||Qc(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function ol(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=V.resolve(r);if(n.has(t))continue;n.add(t);let i=Zc(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 sl(e){return al({source:e.source,rootDir:e.rootDir})||ol({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:il(e.ownershipUid)})}function cl(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=${$c(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function ll(e){let t=sl({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:cl(t),source:e.source}),!0):!1}function ul(e){return V.basename(e,V.extname(e))}function dl(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 fl(e){for(let t of tl){let n=V.join(e,t);if(H.existsSync(n))return n}return null}function pl(e){let t;try{t=H.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=V.join(e.rootDir,n.name);if(n.isFile()){if(!el.has(V.extname(n.name)))continue;let r=V.dirname(t);if(ll({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(dl({idHint:ul(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=nl(t),i=rl(r);if(i.status===`ok`){for(let n of i.entries){let i=V.resolve(t,n);if(!Qc(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!H.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!el.has(V.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(ll({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${ul(i)}`:ul(i);e.candidates.push(dl({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=fl(t);a&&(ll({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(dl({idHint:V.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function ml(e){return e?e.map(Uc).filter(e=>typeof e==`string`&&e.length>0):[]}function hl(){let e=Hc();if(e)return V.join(e,`.aimax`,`extensions`)}function gl(e){return V.join(e,`.aimax`,`extensions`)}function _l(e){return V.join(e,`.aimax`,`extensions`)}function vl(e={}){let t=[],n=[],r=ml(e.extraPaths);for(let i of r){if(!H.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Zc(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!el.has(V.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=V.dirname(i);if(ll({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(dl({idHint:ul(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&pl({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?pl({rootDir:gl(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&pl({rootDir:_l(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=hl();return i?pl({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&pl({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function yl(e){let t=e.rejectHardlinks??!0,n=Xc(e.rootPath),r=Xc(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!Qc(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=H.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:H.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const bl=`aimax.plugin.json`,xl=[bl];function Sl(e){for(let t of xl){let n=V.join(e,t);if(H.existsSync(n))return n}return V.join(e,bl)}function Cl(e,t=!0){let n=Sl(e),r=yl({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(H.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{H.closeSync(r.fd)}if(!Bc(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=Bc(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=Vc(i.skills),f;return Bc(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 wl(e){let t=new Map,n=[];for(let r of e){let e=Cl(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let Tl=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function El(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Tl.ERROR){W.error(i);return}if(e===Tl.WARN){W.warn(i);return}W.info(i)}function Dl(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>El(Tl.INFO,e.pluginId,t,n),warn:n=>El(Tl.WARN,e.pluginId,t,n),error:n=>El(Tl.ERROR,e.pluginId,t,n)})}}}function Ol(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 kl(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 Al(e){let t=[...e.registry.diagnostics],n=new ys,r=new Es,i=[],a=[],o=e.runtime?.llm?on({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=jl(e.runtime?.llmAllowlist),c=tt(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Ol({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=kl({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f;try{f=c(l.source)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let p=f&&typeof f==`object`&&`default`in f?f.default:f,m=typeof p==`function`?p:p&&typeof p==`object`&&typeof p.register==`function`?p.register:void 0;if(!m){d.status=`error`,d.error=`plugin module does not export a register function`,t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let h=Dl({pluginId:l.id}),g=e.plugins.entries[l.id]?.config,_={id:l.id,source:l.source,rootDir:l.rootDir,config:g,runtime:h,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Ml(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);k({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);oe({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=V.isAbsolute(e)?e:V.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>_s(l.id)};try{m(_)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=V.isAbsolute(e)?e:V.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function jl(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Ml(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Nl(e={}){let t=Jc(e.config),n=vl({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=wl(n.candidates),i=Yc({config:t,registry:r}),a=Al({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 Pl(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Nl({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new Es,pluginSkillDirs:o?.registry.skills??[],pluginTools:[...o?.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...o?.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??o?.normalizedConfig.slots?.memory}}async function Fl(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=V.join(t.dataDir,`workspace`),a=n,o=!a,s=q(t);a?(await f(t.dataDir,a,s)||(o=!0),await z(t.dataDir,a,s)):a=await D(t.dataDir,t.channel,{...s});let c={sessionId:a,workspaceDir:i,channel:t.channel},l=Pl({runParams:t,hookContext:c,sessionId:a,eventDispatcher:r}),u=l.hookRegistry,d=await Ic({runParams:t,sessionId:a,hookContext:c,memoryProviderId:t.memory?.providerId,memoryPluginId:l.memoryPluginId,eventDispatcher:r,hookRegistry:u});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:c,hookRegistry:u,pluginContext:l,runContext:d,start:e=>Vn({sessionId:a,runParams:t,hookRegistry:u,hookContext:c,eventDispatcher:r,...e})}}function Il(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Ll(e){if(!(e instanceof Error))return{errorValue:Il(e)};let t={errorName:e.name,errorMessage:e.message};e.stack&&(t.stack=e.stack);let n=e;for(let e of[`code`,`statusCode`,`statusText`,`providerMessage`,`retryable`,`cause`])n[e]!==void 0&&(t[e]=Il(n[e]));return t}async function Rl(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Ll(e.error)}})}function zl(e,t,n){return V.join(d(e,t,n),`pending-hitl.json`)}function Bl(e,t,n){return V.join(d(e,t,n),`hitl-history.jsonl`)}async function Vl(e,t,n,r){let i=d(e,t,r);await B.mkdir(i,{recursive:!0});let a=zl(e,t,r),o=r?.encryptSessions??!1;await l(a,JSON.stringify(n,null,2),o)}async function Hl(e,t,n,r){let i=d(e,t,r);await B.mkdir(i,{recursive:!0}),await ie(Bl(e,t,r),JSON.stringify(n)+`
106
+ `,r?.encryptSessions??!1)}async function Ul(e,t,n){let r=await b(zl(e,t,n));if(r===null)return null;try{return JSON.parse(r)}catch{return null}}async function Wl(e,t,n){let r=await b(Bl(e,t,n));if(r===null)return[];let i=[];for(let e of r.split(`
107
+ `)){let t=e.trim();if(t)try{i.push(JSON.parse(t))}catch{}}return i}async function Gl(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await Vl(e,t,c,o),await Hl(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function Kl(e,t,n,r,i,a){let o=await Ul(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await Vl(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await Hl(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function ql(e,t,n,r){let i=await Ul(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function Jl(e,t,n){let r=zl(e,t,n);try{await B.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function Yl(e,t,n){return V.join(d(e,t,n),`pending-ui-tool.json`)}async function Xl(e,t,n,r){let i=d(e,t,r);await B.mkdir(i,{recursive:!0}),await l(Yl(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function Zl(e,t,n){let r=await b(Yl(e,t,n));return r===null?null:JSON.parse(r)}async function Ql(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Xl(e,t,a,r),a}async function $l(e,t,n,r,i){let a=await Zl(e,t,i);if(!a||a.request.requestId!==n||a.status!==`pending`)return null;let o={...a,status:`resolved`,result:r,updatedAt:new Date().toISOString()};return await Xl(e,t,o,i),o}async function eu(e,t,n){try{await B.unlink(Yl(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const tu=`crons`;function nu(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:Qt(e.message)}}function ru(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{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:e.maxTokens??32768,headers:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}function iu(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!De(t))}async function au(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=Ss();if(i=await Cs(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Y(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=ou(i),s=i&&typeof i==`object`?i.details:void 0,c=s&&typeof s==`object`?s.toolResultRef:void 0;return await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_end`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs,output:o,isError:a}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:o,isError:a,...c?{toolResultRef:c}:{},timestamp:new Date().toISOString()}),{text:o,error:a?o:void 0}}function ou(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}async function su(e,t){Zt(e.dataDir),Fn();let n=Date.now(),r=new In(e),i=Dr(e);W.info(`agent invocation prepared`,{requestedSessionId:i.requestedSessionId,previousSessionId:i.previousSessionId,inputMode:i.inputMode,hasSlashCommand:!!i.slashCommandSource,resetAction:i.resetCommand?.action,resetShortCircuit:i.resetShortCircuit,transcriptLength:i.transcriptMessage.length,messageForRunLength:i.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await Fl({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;W.info(`agent run started`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:u,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),W.info(u?`session created`:`session resumed`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await A(e.dataDir,Lc({sessionId:l,title:Bn(a),channel:e.channel}),q(e)),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(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 ot(e.dataDir),v=[],y=lt(_,{warn:e=>v.push(e)}),b=await ft();await r.dispatchDiagnostic(l,{level:v.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length}}),W.info(`bootstrap context loaded`,{sessionId:l,bootstrapFileCount:_.length,contextFileCount:y.length,warningCount:v.length});let x=e.skillsLoadPaths??[],S=await vt(e.dataDir,m.pluginSkillDirs,x),C=e.agentPolicy?.availableAgents??await Dt({dataDir:e.dataDir,projectDir:e.projectDir}),w=e.agentPolicy?.activeAgent??At(C,e.agentPolicy?.requestedAgentName);if(e.agentPolicy?.requestedAgentName&&!w)throw Error(`Unknown custom agent: ${e.agentPolicy.requestedAgentName}`);let T={availableAgents:C,...w?{activeAgent:w}:{},...e.agentPolicy?.requestedAgentName?{requestedAgentName:e.agentPolicy.requestedAgentName}:{}},E={...e,agentPolicy:T};await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:S.length,pluginSkillDirCount:m.pluginSkillDirs.length,skillsLoadPathCount:x.length,skills:S.map(e=>({name:e.name,description:e.description,location:e.location}))}}),W.info(`skills loaded`,{sessionId:l,skillCount:S.length,pluginSkillDirCount:m.pluginSkillDirs.length,skillsLoadPathCount:x.length}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:C.length,activeAgent:T.activeAgent?.name,agents:C.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),W.info(`custom agents loaded`,{sessionId:l,agentCount:C.length,activeAgent:T.activeAgent?.name,requestedAgentName:T.requestedAgentName});let D=e=>h.appendTranscriptEntry(e),O=await kr({invocation:i,skills:S,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(O.kind===`completed`)return W.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!O.result.error,paused:!!O.result.paused,uiToolPending:!!O.result.uiToolPending,textLength:O.result.text.length}),O.result;let k=O.effectivePrompt;a=O.transcriptMessage;let ee=typeof k==`string`?k:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof k==`string`?`string`:`messages`,transcriptLength:a.length}}),W.info(`invocation resolved`,{sessionId:l,promptType:typeof k==`string`?`string`:`messages`,transcriptLength:a.length});let j=await Js({session:{runParams:E,sessionId:l,hookRegistry:p,hookContext:f,runContext:h,eventDispatcher:r},runtimeInputs:{contextFiles:y,bootstrapWarnings:v,skills:S,effectivePromptText:ee,pluginTools:m.pluginTools,pluginSkillDirs:m.pluginSkillDirs,skillsLoadPaths:x,presetSystemPrompt:b.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>su(e,new tn),createModel:ru,abortSignal:g.signal}}),M=j.agent,N=j.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:N,historyMessageCount:j.historyMessages.length,pluginToolCount:m.pluginTools.length}}),W.info(`agent runtime created`,{sessionId:l,modelId:N,historyMessageCount:j.historyMessages.length,pluginToolCount:m.pluginTools.length}),g.signal.addEventListener(`abort`,()=>M.abort());let P=0,F=0,I=``,L,R=!1;try{if(iu(e)){let t=await au({params:e,agent:M,sessionId:l,eventDispatcher:r,appendEntry:D,abortSignal:g.signal});return I=t.text,Wn({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:I,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await h.persistInitialUserEntry(a);R=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`}),W.info(`first agent turn started`,{sessionId:l,modelId:N});let i=await uc({agent:M,message:k,continueFromHistory:!!e.uiToolResume,sessionId:l,modelId:N,historyMessages:j.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:g.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await D(e);for(let e of t)await D(e)}});I=i.text,P+=i.inputTokens,F+=i.outputTokens,i.error&&(L=i.error),await r.dispatchDiagnostic(l,{level:i.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!i.error,error:i.error,inputTokens:i.inputTokens,outputTokens:i.outputTokens}});let s={sessionId:l,hasError:!!i.error,error:i.error,inputTokens:i.inputTokens,outputTokens:i.outputTokens};i.error?W.warn(`first agent turn completed with error`,s):W.info(`first agent turn completed`,s),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),W.info(`announce loop started`,{sessionId:l});let c=await jc({agent:M,registry:t,sessionId:l,resolvedModelId:N,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:g.signal,retry:e.llmRetry,appendEntry:D});c.text&&(I=c.text),P+=c.inputTokens,F+=c.outputTokens,c.error&&!L&&(L=c.error),await r.dispatchDiagnostic(l,{level:c.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let d={sessionId:l,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?W.warn(`announce loop completed with error`,d):W.info(`announce loop completed`,d)}catch(t){if(Y(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await Gl(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),W.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:P,output:F,total:P+F};return await cu({runtime:j,resolvedModelId:N,usage:c,currentUserEntryCoveredByUsage:R}),Wn({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:I||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(zo(t)){let i=t,o=i.request.outputSchema.properties??{};await Ql(e.dataDir,l,i.request,q(e)),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length}}),W.info(`agent paused for UI tool input`,{sessionId:l,requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length});let s={input:P,output:F,total:P+F};return await cu({runtime:j,resolvedModelId:N,usage:s,currentUserEntryCoveredByUsage:R}),Wn({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:I||``,usage:s,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}throw await Rl({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),W.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{an(l),h.stop()}let z={input:P,output:F,total:P+F};await r.dispatchDiagnostic(l,{level:L?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:z.input,outputTokens:z.output,totalTokens:z.total,hasError:!!L,error:L}});let te={sessionId:l,durationMs:Date.now()-n,inputTokens:z.input,outputTokens:z.output,totalTokens:z.total,hasError:!!L,error:L};return L?W.warn(`agent run completed with error`,te):W.info(`agent run completed`,te),await cu({runtime:j,resolvedModelId:N,usage:z,currentUserEntryCoveredByUsage:R}),Wn({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:I,usage:z,error:L})}async function cu(e){let{runtime:t,resolvedModelId:n,usage:r,currentUserEntryCoveredByUsage:i}=e;r.input<=0&&r.total<=0||await t.contextManager.recordModelUsage({model:n,inputTokens:r.input,outputTokens:r.output,totalTokens:r.total,coveredTranscriptEntryCount:t.usageBaselineTranscriptEntryCount+(i?1:0)})}async function lu(t){Zt(t.dataDir);let n=Date.now(),r=new In(t),i=Dr(t),a=i.transcriptMessage.trim()||`CRON task`,o=t.sessionStoreName;W.info(`cron run started`,{requestedSessionId:i.requestedSessionId,channel:t.channel,sessionStoreName:o,...nu(t)});let s=i.requestedSessionId,l=!s;s?(await f(t.dataDir,s,{storeName:o})||(l=!0),await z(t.dataDir,s,{storeName:o})):s=await D(t.dataDir,t.channel,{storeName:o}),l&&await A(t.dataDir,Lc({sessionId:s,title:Bn(a),channel:t.channel}),{storeName:o});let u=await D(t.dataDir,t.channel,{storeName:tu});await r.dispatchProgress(s,{type:`subagent_spawn`,childSessionId:u,task:a}),W.info(`cron child subagent spawned`,{parentSessionId:s,childSessionId:u,taskLength:a.length,taskPreview:Qt(a)});let d={...t,sessionId:u,sessionStoreName:tu,subagentContext:{depth:1,parentSessionId:s}},p,m=`done`;try{p=await su(d,new tn),p.error&&(m=`error`)}catch(e){let r=e instanceof Error?e.message:String(e);p={sessionId:u,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:O(t.dataDir,u,{storeName:tu}),toolResultsDir:c(t.dataDir,u,{storeName:tu})}},m=`error`,W.error(`cron child run failed`,{parentSessionId:s,childSessionId:u,error:r})}await r.dispatchProgress(s,{type:`subagent_complete`,childSessionId:u,task:a,status:m}),W.info(`cron child subagent completed`,{parentSessionId:s,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!p.error});let g=Do({task:a,status:m,result:p.text,error:p.error}),_=new Date().toISOString();await E(t.dataDir,s,{role:`assistant`,content:g,timestamp:_,source:`cron`},{storeName:o});let v={task:a,status:m,content:g,childSessionId:u,createdAt:_};return await T(t.dataDir,s,v,{storeName:o}),await e(t.dataDir,s,e=>uu(e,8),{storeName:o}),await h(t.dataDir,s,{},{storeName:o}),{...p,sessionId:s,context:{snapshotPath:O(t.dataDir,s,{storeName:o}),toolResultsDir:c(t.dataDir,s,{storeName:o})}}}function uu(e,t){if(t<=0)return e.filter(e=>!du(e));let n=e.reduce((e,t,n)=>(du(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!du(e)||r.has(t))}function du(e){return`source`in e&&e.source===`cron`}async function fu(e,t){if(Zt(e.dataDir),W.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...nu(e)}),e.channel===`CRON`&&!e.subagentContext)return lu(e);let n=t??new tn;try{return await su(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:Ll(t)}),W.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}const pu={"AGENTS.md":`---
105
108
  title: "AGENTS.md Template"
106
109
  summary: ".aimax template for AGENTS.md"
107
110
  read_when:
@@ -394,7 +397,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
394
397
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
395
398
 
396
399
  Add whatever helps you do your job. This is your cheat sheet.
397
- `},su=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function cu(e,t){try{if(!(await B.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 B.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function lu(e,t,n){try{if(!(await B.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 B.mkdir(V.dirname(e),{recursive:!0});try{await B.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 uu(e){let t=Qe(e);return[e,t,V.join(t,`skills`),V.join(t,`sessions`),V.join(t,`memory`),V.join(e,`workspace`)]}function du(e){let t=Qe(e);return[...su.filter(e=>e!==`BOOTSTRAP.md`).map(e=>V.join(t,e)),V.join(t,`MEMORY.md`)]}function fu(e){return V.join(Qe(e),`.bootstrapped`)}async function pu(e){try{return(await B.stat(fu(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function mu(e){let t=fu(e);await B.mkdir(V.dirname(t),{recursive:!0}),await B.writeFile(t,``,{encoding:`utf-8`})}async function hu(e){let t=[],n=[];for(let n of uu(e))try{(await B.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of du(e))try{(await B.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 gu(e){return(await hu(e)).ready}async function _u(e){if(await pu(e))return{ready:!0,performedBootstrap:!1};if((await hu(e)).ready)return await mu(e),{ready:!0,performedBootstrap:!1};let t=await vu(e);return await mu(e),{ready:!0,performedBootstrap:!0,result:t}}async function vu(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=Qe(e),r=V.join(e,`workspace`),i=V.join(n,`skills`),a=V.join(n,`sessions`),o=V.join(n,`memory`);await cu(e,t),await cu(n,t),await cu(i,t),await cu(a,t),await cu(o,t),await cu(r,t);for(let e of su){let r=ou[e]??``;await lu(V.join(n,e),r,t)}return await lu(V.join(n,`MEMORY.md`),``,t),t}async function yu(e){let t=V.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await B.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 bu(e,t){let n=V.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 B.mkdir(V.dirname(n),{recursive:!0}),await B.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function xu(e,t){let n=await yu(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 Su(e,t=7){let n=await yu(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 bu(e,n),i}async function Cu(e,t,n,r){let i=await Il(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?ve(i.request)?(await zl(e,t,n,`expired`,void 0,{storeName:r}),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:i}:{valid:!1,reason:`HITL request is already "${i.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${i.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${i.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function wu(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await Bl(t,n,r,{storeName:a});if(o){let e=o.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:o,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${o.status}", cannot resume`)}let s=await Cu(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await zl(t,n,r,`resolved`,i,{storeName:a});if(!c)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:c,idempotentReplay:!1}}const Tu={clarify:{label:`澄清问题`,description:`当你需要更多信息才能继续时,向用户提出澄清问题。提供清晰的问题,并可选给出候选选项。任务会暂停,直到用户回复。`,title:`需要你补充信息`,placeholder:`请输入你的回复`},approval:{label:`请求授权`,description:"仅当用户或系统明确要求调用 `request_approval` 时使用。不要把它用于一般确认、澄清或推断式授权检查。说明要执行的动作,以及为什么必须显式授权。任务会暂停,直到用户同意或拒绝。",choices:{approve:{label:`同意`,description:`允许继续执行该操作`},deny:{label:`拒绝`,description:`不允许执行该操作`}},summary:{approved:`已授权。`,denied:`已拒绝。`,timeout:`由于超时,视为拒绝。`}},review:{label:`请求审阅`,description:`在继续之前,将草稿、文档或输出提交给用户审阅。包含需要审阅的内容,以及你希望获得的反馈类型。任务会暂停,直到用户完成审阅并回复。`,choices:{approve:{label:`通过`,description:`内容没有问题,继续执行`},revise:{label:`需要修改`,description:`提供反馈后再修改`},reject:{label:`拒绝`,description:`放弃当前草稿`}}}};function Eu(e){return e.action===`timeout`?Tu.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?Tu.approval.summary.approved:Tu.approval.summary.denied}function Du(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Eu(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Ou(e){let t=e.values?.text??e.values?.selectedChoiceIds?.join(`, `)??``;return JSON.stringify({action:e.action,answer:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function ku(e){let t=(e.values?.selectedChoiceIds??[])[0]??e.action,n=e.values?.text??``;return JSON.stringify({action:e.action,verdict:t,feedback:n,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function Au(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
400
+ `},mu=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function hu(e,t){try{if(!(await B.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 B.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function gu(e,t,n){try{if(!(await B.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 B.mkdir(V.dirname(e),{recursive:!0});try{await B.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function _u(e){let t=at(e);return[e,t,V.join(t,`skills`),V.join(t,`sessions`),V.join(t,`memory`),V.join(e,`workspace`)]}function vu(e){let t=at(e);return[...mu.filter(e=>e!==`BOOTSTRAP.md`).map(e=>V.join(t,e)),V.join(t,`MEMORY.md`)]}function yu(e){return V.join(at(e),`.bootstrapped`)}async function bu(e){try{return(await B.stat(yu(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function xu(e){let t=yu(e);await B.mkdir(V.dirname(t),{recursive:!0}),await B.writeFile(t,``,{encoding:`utf-8`})}async function Su(e){let t=[],n=[];for(let n of _u(e))try{(await B.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of vu(e))try{(await B.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 Cu(e){return(await Su(e)).ready}async function wu(e){if(await bu(e))return{ready:!0,performedBootstrap:!1};if((await Su(e)).ready)return await xu(e),{ready:!0,performedBootstrap:!1};let t=await Tu(e);return await xu(e),{ready:!0,performedBootstrap:!0,result:t}}async function Tu(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=at(e),r=V.join(e,`workspace`),i=V.join(n,`skills`),a=V.join(n,`sessions`),o=V.join(n,`memory`);await hu(e,t),await hu(n,t),await hu(i,t),await hu(a,t),await hu(o,t),await hu(r,t);for(let e of mu){let r=pu[e]??``;await gu(V.join(n,e),r,t)}return await gu(V.join(n,`MEMORY.md`),``,t),t}async function Eu(e){let t=V.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await B.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 Du(e,t){let n=V.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 B.mkdir(V.dirname(n),{recursive:!0}),await B.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Ou(e,t){let n=await Eu(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 ku(e,t=7){let n=await Eu(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 Du(e,n),i}async function Au(e,t,n,r){let i=await Ul(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ee(i.request)?(await Kl(e,t,n,`expired`,void 0,{storeName:r}),{valid:!1,reason:`HITL request has expired`}):{valid:!0,state:i}:{valid:!1,reason:`HITL request is already "${i.status}", cannot resume`}:{valid:!1,reason:`Session ID mismatch: expected "${i.sessionId}", got "${t}"`}:{valid:!1,reason:`Request ID mismatch: expected "${i.request.requestId}", got "${n}"`}:{valid:!1,reason:`No pending HITL request found for this session`}}async function ju(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ql(t,n,r,{storeName:a});if(o){let e=o.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:o,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${o.status}", cannot resume`)}let s=await Au(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await Kl(t,n,r,`resolved`,i,{storeName:a});if(!c)throw Error(`Failed to transition HITL state to resolved (concurrent modification?)`);return{state:c,idempotentReplay:!1}}const Mu={clarify:{label:`澄清问题`,description:`当你需要更多信息才能继续时,向用户提出澄清问题。提供清晰的问题,并可选给出候选选项。任务会暂停,直到用户回复。`,title:`需要你补充信息`,placeholder:`请输入你的回复`},approval:{label:`请求授权`,description:"仅当用户或系统明确要求调用 `request_approval` 时使用。不要把它用于一般确认、澄清或推断式授权检查。说明要执行的动作,以及为什么必须显式授权。任务会暂停,直到用户同意或拒绝。",choices:{approve:{label:`同意`,description:`允许继续执行该操作`},deny:{label:`拒绝`,description:`不允许执行该操作`}},summary:{approved:`已授权。`,denied:`已拒绝。`,timeout:`由于超时,视为拒绝。`}},review:{label:`请求审阅`,description:`在继续之前,将草稿、文档或输出提交给用户审阅。包含需要审阅的内容,以及你希望获得的反馈类型。任务会暂停,直到用户完成审阅并回复。`,choices:{approve:{label:`通过`,description:`内容没有问题,继续执行`},revise:{label:`需要修改`,description:`提供反馈后再修改`},reject:{label:`拒绝`,description:`放弃当前草稿`}}}};function Nu(e){return e.action===`timeout`?Mu.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?Mu.approval.summary.approved:Mu.approval.summary.denied}function Pu(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Nu(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Fu(e){let t=e.values?.text??e.values?.selectedChoiceIds?.join(`, `)??``;return JSON.stringify({action:e.action,answer:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function Iu(e){let t=(e.values?.selectedChoiceIds??[])[0]??e.action,n=e.values?.text??``;return JSON.stringify({action:e.action,verdict:t,feedback:n,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt})}function Lu(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
398
401
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
399
402
  `)):(n.push(`动作:用户已提交结果。`),e.values?.selectedChoiceIds&&e.values.selectedChoiceIds.length>0&&n.push(`已选项:${e.values.selectedChoiceIds.join(`, `)}`),e.values?.text&&n.push(`用户文本:${e.values.text}`),e.values?.form&&n.push(`表单数据:${JSON.stringify(e.values.form)}`),n.join(`
400
- `))}export{Ze as BOOTSTRAP_FILE_NAMES,Ye as BOOTSTRAP_MAX_CHARS,Xe as BOOTSTRAP_TOTAL_MAX_CHARS,_ as DEFAULT_SESSION_STORE_NAME,Tu as HITL_MESSAGES,di as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,qt as MAX_CHILDREN_PER_SESSION,Kt as MAX_SUBAGENT_DEPTH,A as MemoryIndexManager,pl as PLUGIN_MANIFEST_FILENAME,ml as PLUGIN_MANIFEST_FILENAMES,ys as PluginHookRegistry,fs as PluginToolRegistry,_t as SYSTEM_AGENTS_DIR,Jt as SubagentRegistry,jo as UiToolPauseSignal,me as addAgent,ue as addBinding,yt as agentDirCandidates,Qe as aimaxDir,j as appendArtifactOperation,v as appendCronExecutionRecord,Sa as appendRecentToMemory,xa as appendToMemory,y as appendTranscriptEntry,Eu as approvalSummaryFromResolution,k as artifactsPath,vu as bootstrapMountLayout,Et as buildAgentDelegationPrompt,Dt as buildAgentTaskPrompt,nt as buildBootstrapContextFiles,Au as buildResumeNarration,gt as buildSkillsPrompt,bo as buildSubagentAnnounceMessage,ss as buildSystemPrompt,Su as cleanupOldSubagentRecords,Vl as clearPendingHitl,ql as clearPendingUiTool,E as collapseLogPath,x as contextSnapshotPath,zo as createAgentTools,ta as createApplyPatchTool,Ii as createBashTool,wo as createBatchSubagentSpawnTool,D as createBuiltinMemoryProvider,li as createContextManager,Ki as createEditFileTool,xi as createExecTool,Ao as createImageTool,Ji as createListDirTool,ka as createMemoryAppendTool,Ua as createMemoryForgetTool,Da as createMemoryGetTool,Va as createMemoryListTool,za as createMemoryLogTool,Ta as createMemorySearchTool,Ga as createMemoryUpdateTool,ja as createMemoryWriteTool,Rl as createPendingHitl,Gl as createPendingUiTool,us as createPluginProgressEmitter,bl as createPluginRuntime,Ti as createProcessTool,Hi as createReadFileTool,b as createSession,Ir as createSessionContextStore,qa as createSessionSearchTool,ho as createSkillListTool,go as createSkillLoadTool,Co as createSubagentSpawnTool,Oo as createSubagentsTool,Ro as createUiTool,Wi as createWriteFileTool,m as cronExecutionsPath,Lo as defaultUiToolInputSchema,Ca as deleteMemoryFile,dl as discoverAIMaxPlugins,_u as ensureBootstrapMountLayout,M as ensureSession,F as exportSession,wt as filterSkillsForAgent,Tt as filterToolsForAgent,Ct as findAgentDefinition,pt as findSkillByName,Du as formatApprovalResolution,Ou as formatClarifyResolution,ku as formatReviewResolution,jn as generateSessionTitle,se as getAgentConfig,ba as getMemoryLines,pu as hasBootstrapSentinel,Nl as hitlHistoryPath,El as initializePluginSystem,hu as inspectBootstrapMountLayout,g as inspectSession,gu as isBootstrapMountLayoutReady,Y as isHitlPauseSignal,Mo as isUiToolPauseSignal,te as listAgents,Hn as listAvailableSlashCommands,de as listBindings,ga as listMemoryFiles,P as listSessionSummaries,f as listSessions,xu as listSubagentRunsFromDisk,xt as loadAgentDefinitionsFromDir,pe as loadAgentsConfig,t as loadArtifactOperations,$e as loadBootstrapFiles,N as loadCronExecutionRecords,Il as loadPendingHitl,Il as readPendingHitl,Wl as loadPendingUiTool,Wl as readPendingUiTool,gl as loadPluginManifest,_l as loadPluginManifestRegistry,Cl as loadPlugins,p as loadSessionContextSnapshot,r as loadSessionMetadata,ht as loadSkillView,ut as loadSkills,ft as loadSkillsFromDirs,dt as loadSkillsWithPluginDirs,yu as loadSubagentRegistryFromDisk,n as loadTranscript,pa as memoryDir,l as metadataPath,ne as normalizeAgentId,Vc as normalizePluginsConfig,w as normalizeSessionStoreName,St as parseAgentDefinition,Ml as pendingHitlPath,Hl as pendingUiToolPath,ma as primaryMemoryPath,Ll as readHitlHistory,_a as readMemoryFile,va as readPrimaryMemory,S as registerEmbeddingProvider,L as registerMemoryProvider,ce as removeAgent,he as removeBindings,Q as replaceMemoryFile,h as resetEmbeddingProviderRegistryForTests,R as resetMemoryProviderRegistryForTests,re as resolveAgentDir,ie as resolveAgentIdByBinding,fe as resolveAgentsConfigPath,le as resolveDefaultAgentId,O as resolveEmbeddingProvider,wu as resolveHitlRequest,wu as resolvePendingHitl,I as resolveMemoryProvider,oe as resolveModelFallbacks,ae as resolveModelString,Kl as resolvePendingUiTool,hl as resolvePluginManifestPath,e as rewriteTranscript,au as runAgent,z as saveAgentsConfig,C as saveSessionMetadata,bu as saveSubagentRegistryToDisk,bt as scanAgentDefinitions,ya as searchMemory,s as sessionDir,u as sessionMemoryPath,i as sessionsDir,ot as skillsDir,a as toolResultsDir,o as transcriptPath,zl as transitionHitlStatus,ge as updateAgentIdentity,d as updateSessionMetadata,Hc as validatePluginsConfig,Cu as validateResume,vs as wrapToolsWithHooks};
403
+ `))}export{it as BOOTSTRAP_FILE_NAMES,nt as BOOTSTRAP_MAX_CHARS,rt as BOOTSTRAP_TOTAL_MAX_CHARS,w as DEFAULT_SESSION_STORE_NAME,Mu as HITL_MESSAGES,vi as HitlPauseSignal,j as MAX_ARTIFACT_CONTENT_CHARS,en as MAX_CHILDREN_PER_SESSION,$t as MAX_SUBAGENT_DEPTH,I as MemoryIndexManager,bl as PLUGIN_MANIFEST_FILENAME,xl as PLUGIN_MANIFEST_FILENAMES,Es as PluginHookRegistry,ys as PluginToolRegistry,wt as SYSTEM_AGENTS_DIR,tn as SubagentRegistry,Ro as UiToolPauseSignal,Se as addAgent,ve as addBinding,Et as agentDirCandidates,at as aimaxDir,R as appendArtifactOperation,T as appendCronExecutionRecord,ka as appendRecentToMemory,ie as appendSessionFile,Oa as appendToMemory,E as appendTranscriptEntry,Nu as approvalSummaryFromResolution,F as artifactsPath,t as atomicWriteSessionFile,Tu as bootstrapMountLayout,Nt as buildAgentDelegationPrompt,Pt as buildAgentTaskPrompt,lt as buildBootstrapContextFiles,Lu as buildResumeNarration,Ct as buildSkillsPrompt,Do as buildSubagentAnnounceMessage,ms as buildSystemPrompt,ku as cleanupOldSubagentRecords,Jl as clearPendingHitl,eu as clearPendingUiTool,M as collapseLogPath,O as contextSnapshotPath,Ko as createAgentTools,ca as createApplyPatchTool,Ui as createBashTool,jo as createBatchSubagentSpawnTool,N as createBuiltinMemoryProvider,gi as createContextManager,$i as createEditFileTool,Oi as createExecTool,Lo as createImageTool,ta as createListDirTool,Ia as createMemoryAppendTool,Xa as createMemoryForgetTool,Pa as createMemoryGetTool,Ja as createMemoryListTool,Ka as createMemoryLogTool,Ma as createMemorySearchTool,Qa as createMemoryUpdateTool,Ra as createMemoryWriteTool,Gl as createPendingHitl,Ql as createPendingUiTool,_s as createPluginProgressEmitter,Dl as createPluginRuntime,Mi as createProcessTool,Yi as createReadFileTool,D as createSession,Ur as createSessionContextStore,eo as createSessionSearchTool,So as createSkillListTool,Co as createSkillLoadTool,Ao as createSubagentSpawnTool,Fo as createSubagentsTool,Go as createUiTool,Zi as createWriteFileTool,x as cronExecutionsPath,y as decryptContent,Wo as defaultUiToolInputSchema,Aa as deleteMemoryFile,vl as discoverAIMaxPlugins,s as encryptContent,wu as ensureBootstrapMountLayout,z as ensureSession,re as exportSession,jt as filterSkillsForAgent,Mt as filterToolsForAgent,At as findAgentDefinition,bt as findSkillByName,Pu as formatApprovalResolution,Fu as formatClarifyResolution,Iu as formatReviewResolution,Rn as generateSessionTitle,he as getAgentConfig,Da as getMemoryLines,bu as hasBootstrapSentinel,Bl as hitlHistoryPath,Nl as initializePluginSystem,Su as inspectBootstrapMountLayout,C as inspectSession,Cu as isBootstrapMountLayoutReady,v as isEncryptedContent,Y as isHitlPauseSignal,zo as isUiToolPauseSignal,le as listAgents,Yn as listAvailableSlashCommands,ye as listBindings,Ca as listMemoryFiles,ne as listSessionSummaries,g as listSessions,Ou as listSubagentRunsFromDisk,Ot as loadAgentDefinitionsFromDir,xe as loadAgentsConfig,n as loadArtifactOperations,ot as loadBootstrapFiles,te as loadCronExecutionRecords,Ul as loadPendingHitl,Ul as readPendingHitl,Zl as loadPendingUiTool,Zl as readPendingUiTool,Cl as loadPluginManifest,wl as loadPluginManifestRegistry,Al as loadPlugins,_ as loadSessionContextSnapshot,i as loadSessionMetadata,St as loadSkillView,_t as loadSkills,yt as loadSkillsFromDirs,vt as loadSkillsWithPluginDirs,Eu as loadSubagentRegistryFromDisk,r as loadTranscript,ba as memoryDir,p as metadataPath,ue as normalizeAgentId,Jc as normalizePluginsConfig,ee as normalizeSessionStoreName,kt as parseAgentDefinition,zl as pendingHitlPath,Yl as pendingUiToolPath,xa as primaryMemoryPath,Wl as readHitlHistory,wa as readMemoryFile,Ta as readPrimaryMemory,b as readSessionFile,o as readSessionFileContent,k as registerEmbeddingProvider,oe as registerMemoryProvider,ge as removeAgent,Ce as removeBindings,Q as replaceMemoryFile,S as resetEmbeddingProviderRegistryForTests,se as resetMemoryProviderRegistryForTests,de as resolveAgentDir,fe as resolveAgentIdByBinding,be as resolveAgentsConfigPath,_e as resolveDefaultAgentId,P as resolveEmbeddingProvider,ju as resolveHitlRequest,ju as resolvePendingHitl,ae as resolveMemoryProvider,me as resolveModelFallbacks,pe as resolveModelString,$l as resolvePendingUiTool,Sl as resolvePluginManifestPath,e as rewriteTranscript,fu as runAgent,ce as saveAgentsConfig,A as saveSessionMetadata,Du as saveSubagentRegistryToDisk,Dt as scanAgentDefinitions,Ea as searchMemory,d as sessionDir,m as sessionMemoryPath,a as sessionsDir,pt as skillsDir,c as toolResultsDir,u as transcriptPath,Kl as transitionHitlStatus,we as updateAgentIdentity,h as updateSessionMetadata,Yc as validatePluginsConfig,Au as validateResume,Ts as wrapToolsWithHooks,l as writeSessionFile};