@gencode/agents 0.2.3 → 0.3.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,103 +1,106 @@
1
- import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,P as s,S as c,T as l,_ as u,a as d,b as f,c as p,d as m,f as h,g,h as _,i as v,j as y,k as b,l as x,m as S,n as C,o as w,p as T,r as E,s as D,u as O,v as k,w as A,x as j,y as M}from"./builtin-provider-Bv7sulLa.js";import{i as N,n as P,r as F}from"./provider-registry-CxtHsHdk.js";import{_ as I,a as ee,c as te,d as ne,f as re,g as ie,h as ae,i as oe,l as se,m as ce,n as le,o as ue,p as de,s as fe,t as pe,u as me,v as he}from"./config-DG3Q1aJ6.js";import{formatTaskForDisplay as ge,isHitlExpired as _e,isHitlTool as ve,validateUiToolResult as ye}from"@gencode/shared";import L,{readFile as be}from"node:fs/promises";import R,{join as xe}from"node:path";import Se from"gray-matter";import{Type as z,calculateCost as Ce,getEnvApiKey as we,parseStreamingJson as Te,registerApiProvider as Ee,registerBuiltInApiProviders as De,supportsXhigh as Oe}from"@mariozechner/pi-ai";import ke from"openai";import{AssistantMessageEventStream as Ae}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as B}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as je,hasCopilotVisionInput as Me}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as Ne,clampReasoning as Pe}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as Fe}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import{createHash as Ie,randomUUID as Le}from"node:crypto";import{Agent as Re}from"@mariozechner/pi-agent-core";import ze from"node:os";import{spawn as Be}from"node:child_process";import{isBinaryFile as Ve}from"isbinaryfile";import V from"node:fs";import He from"node:readline";import{AsyncLocalStorage as Ue}from"node:async_hooks";import We from"ajv";import{createJiti as Ge}from"jiti";const Ke=2e4,qe=15e4,Je=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function H(e){return R.join(e,`.aimax`)}async function Ye(e){let t=H(e),n=[];for(let e of Je){let r=R.join(t,e);try{let t=await L.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await L.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 Xe(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,C as t,D as n,E as r,M as i,N as a,O as o,P as s,S as c,T as l,_ as u,a as d,b as f,c as p,d as m,f as h,g,h as _,i as v,j as y,k as b,l as x,m as S,n as C,o as w,p as T,r as E,s as D,u as O,v as k,w as A,x as ee,y as j}from"./builtin-provider-Zyp3W8uT.js";import{i as M,n as N,r as P}from"./provider-registry-CxtHsHdk.js";import{_ as F,a as I,c as L,d as te,f as R,g as ne,h as re,i as ie,l as ae,m as oe,n as se,o as ce,p as le,s as ue,t as de,u as fe,v as pe}from"./config-DG3Q1aJ6.js";import{formatTaskForDisplay as me,isHitlExpired as he,isHitlTool as ge,validateUiToolResult as _e}from"@gencode/shared";import z,{readFile as ve}from"node:fs/promises";import B,{join as ye}from"node:path";import be from"gray-matter";import V from"node:fs";import xe from"log4js";import{Type as H,calculateCost as Se,getEnvApiKey as Ce,parseStreamingJson as we,registerApiProvider as Te,registerBuiltInApiProviders as Ee,supportsXhigh as De}from"@mariozechner/pi-ai";import Oe from"openai";import{AssistantMessageEventStream as ke}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as Ae}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as je,hasCopilotVisionInput as Me}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as Ne,clampReasoning as Pe}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as Fe}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import{createHash as Ie,randomUUID as Le}from"node:crypto";import{Agent as Re}from"@mariozechner/pi-agent-core";import ze from"node:os";import{spawn as Be}from"node:child_process";import{isBinaryFile as Ve}from"isbinaryfile";import He from"node:readline";import{AsyncLocalStorage as Ue}from"node:async_hooks";import We from"ajv";import{createJiti as Ge}from"jiti";const Ke=2e4,qe=15e4,Je=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Ye(e){return B.join(e,`.aimax`)}async function Xe(e){let t=Ye(e),n=[];for(let e of Je){let r=B.join(t,e);try{let t=await z.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await z.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 Ze(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 Ze(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Qe(e,t){let n=t?.maxChars??Ke,r=Math.max(1,t?.totalMaxChars??Math.max(n,qe)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Ze(`[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}=Xe(a.content??``,a.name,e),l=Ze(o,r);l&&((s||l.length<o.length)&&t?.warn?.(`bootstrap file ${a.name} is ${c} chars (limit ${e}); truncating`),r=Math.max(0,r-l.length),i.push({path:a.path,content:l}))}return i}const $e=`You are a personal assistant running inside AiMax.`;async function et(e){try{return{presetSystemPrompt:Se(await L.readFile(e,`utf-8`)).content.trim()||$e}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:$e};throw e}}async function tt(){return et(`/aimax/system_prompt.md`)}function nt(e){return R.join(e,`.aimax`,`skills`)}function rt(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function it(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${rt(n)}\n`)}function at(e){let t=Se(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 ot(e){return ct([nt(e)])}async function st(e,t,n=[]){return ct([...n,...t,nt(e)])}async function ct(e){let t=new Map;for(let n of e){let e;try{e=await L.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=R.join(n,e,`SKILL.md`),i;try{i=await L.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a;try{a=at(i)}catch(t){it(e,r,t);continue}t.set(e,{name:e,description:a,location:r})}}return Array.from(t.values()).slice(0,50)}async function lt(e,t){let n=t.trim();if(!n)return;let r=(await ct(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:R.dirname(r.location)}}async function ut(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=R.resolve(r),a=R.basename(i)===`SKILL.md`?i:R.join(i,`SKILL.md`);if(R.basename(a)!==`SKILL.md`)return;let o;try{o=await L.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s;try{s=at(o)}catch(e){it(n,a,e);return}return{skill:{name:n,description:s,location:a},rootDir:R.dirname(a)}}async function dt(e,t,n){let r=n?.trim()?await ut(t,n):await lt(e,t);if(!r)return;let i=await L.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function ft(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 Qe(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function $e(e,t){let n=t?.maxChars??Ke,r=Math.max(1,t?.totalMaxChars??Math.max(n,qe)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Qe(`[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}=Ze(a.content??``,a.name,e),l=Qe(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 et=`You are a personal assistant running inside AiMax.`;async function tt(e){try{return{presetSystemPrompt:be(await z.readFile(e,`utf-8`)).content.trim()||et}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:et};throw e}}async function nt(){return tt(`/aimax/system_prompt.md`)}function rt(e){return B.join(e,`.aimax`,`skills`)}function it(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function at(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${it(n)}\n`)}function ot(e){let t=be(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 st(e){return lt([rt(e)])}async function ct(e,t,n=[]){return lt([...n,...t,rt(e)])}async function lt(e){let t=new Map;for(let n of e){let e;try{e=await z.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=B.join(n,e,`SKILL.md`),i;try{i=await z.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a;try{a=ot(i)}catch(t){at(e,r,t);continue}t.set(e,{name:e,description:a,location:r})}}return Array.from(t.values()).slice(0,50)}async function ut(e,t){let n=t.trim();if(!n)return;let r=(await lt(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:B.dirname(r.location)}}async function dt(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=B.resolve(r),a=B.basename(i)===`SKILL.md`?i:B.join(i,`SKILL.md`);if(B.basename(a)!==`SKILL.md`)return;let o;try{o=await z.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s;try{s=ot(o)}catch(e){at(n,a,e);return}return{skill:{name:n,description:s,location:a},rootDir:B.dirname(a)}}async function ft(e,t,n){let r=n?.trim()?await dt(t,n):await ut(e,t);if(!r)return;let i=await z.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function pt(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 pt=3,mt=5;var ht=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t})}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())}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())}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(),!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(),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)}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>3?{allowed:!1,reason:`Maximum subagent depth (3) 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}};const gt=new Map;function _t(e){let t=gt.get(e);return t||(t={},gt.set(e,t)),t}function vt(e){gt.delete(e)}var U=class extends Error{code;statusCode;statusText;providerMessage;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.retryable=e.retryable}};function yt(e){return{async chat(t){let n=bt(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await Ct(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:xt(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}=wt(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 Et(e,s())}if(!t.ok){let e=await Tt(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new U({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:Ot(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new U({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=St(o.usage),u=Math.max(0,Date.now()-n);return await Ct(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 bt(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 xt(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
7
- `)}function St(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 Ct(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function wt(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 Tt(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function Et(e,t){return e instanceof U?e:Dt(e)?t?new U({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new U({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function Dt(e){return e instanceof Error&&e.name===`AbortError`}function Ot(e){return e===408||e===409||e===425||e===429||e>=500}function kt(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function At(e){if(!kt(e))return null;let t=e,n=jt(t.message),r=W(n?.code)??W(t.code),i=W(n?.type)??W(t.type),a=W(n?.message)??Mt(t.error)??W(t.message)??`Unknown upstream error`;return{message:Nt(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Pt(r,i),raw:e}}function jt(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 Mt(e){if(!(!e||typeof e!=`object`))return W(e.message)}function W(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Nt(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Pt(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 Ft=(e,t,n)=>{let r=new Ae;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=Lt(e,t,n?.apiKey||we(e.provider)||``,n?.headers),o=Rt(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=Te(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=At(t);if(n)throw new U({message:`LLM upstream returned an error payload in a 200 stream: ${n.message}`,code:`stream_payload_error`,providerMessage:n.providerMessage,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}},Ce(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=Wt(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=Te(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);let t=e?.error?.metadata?.raw;t&&(i.errorMessage+=`\n${t}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},It=(e,t,n)=>{let r=n?.apiKey||we(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Ne(e,n,r),a=Oe(e)?n?.reasoning:Pe(n?.reasoning);return Ft(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function Lt(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=Me(t.messages);Object.assign(i,je({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new ke({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Rt(e,t,n){let r=Kt(e),i=Ht(e,t,r);Vt(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=Ut(t.tools,r):zt(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 zt(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 Bt(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 Vt(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 Ht(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Bt(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=Fe(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:B(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:B(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:B(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=>B(e.text)).join(``):a.map(e=>({type:`text`,text:B(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 mt=`/aimax/agents`,ht=/^[a-z]+(?:-[a-z]+)*$/;function gt(e){let t=[{dir:e.systemAgentsDir??mt,source:`system`},{dir:B.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:B.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function _t(e){let t=new Map;for(let n of gt(e)){let e=await vt(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}async function vt(e,t){let n;try{n=await z.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=B.join(e,i.name),a=yt(await z.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function yt(e,t){let n=be(e),r=Tt(n.data.name)?.trim(),i=Tt(n.data.description)?.trim();if(!r||!ht.test(r)||!i)return;let a=Tt(n.data.model)?.trim(),o=Tt(n.data.initPrompt)?.trim()??Tt(n.data.initialPrompt)?.trim(),s=Et(n.data.maxTurns),c=Dt(n.data.tools),l=Dt(n.data.disallowedTools),u=Dt(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 bt(e,t){let n=t?.trim();if(n)return e.find(e=>e.name===n)}function xt(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function St(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Ot)):void 0,r=new Set((t.disallowedTools??[]).map(Ot));return e.filter(e=>{let t=typeof e.name==`string`?Ot(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Ct(e){return e.length===0?``:[`## Custom Agents`,"The following custom agents are currently effective. Use `subagent_spawn` with the agent name when one clearly matches the delegated task.",e.map(e=>`- ${e.name}: ${e.description}`).join(`
7
+ `),``].join(`
8
+ `)}function wt(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Tt(e){return typeof e==`string`?e:void 0}function Et(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Dt(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 Ot(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 kt(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 At(e=new Date){let t=kt(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let jt=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Mt=null;function Nt(){return At()}function Pt(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 Ft(e){return B.join(e,`.aimax`)}function It(e){return{appLogPath:B.join(e,`app.log`),errorLogPath:B.join(e,`errors.log`)}}function Lt(e){let{appLogPath:t,errorLogPath:n}=It(e);xe.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 Rt(e,t,n){return`[${Nt()}] [${e}] ${t}${Pt(n)}`}function zt(e,t,n){process.stderr.write(`${Rt(e,t,n)}\n`)}function Bt(e,t,n){if(!Mt){zt(e,t,n);return}let r=Rt(e,t,n),i=xe.getLogger();if(e===jt.ERROR){i.error(r);return}if(e===jt.WARN){i.warn(r);return}i.info(r)}function Vt(e){let t=Ft(e);Mt?.dataDir!==e&&(V.mkdirSync(t,{recursive:!0}),Lt(t),Mt={dataDir:e,logDir:t})}const U={info:(e,t)=>Bt(jt.INFO,e,t),warn:(e,t)=>Bt(jt.WARN,e,t),error:(e,t)=>Bt(jt.ERROR,e,t)};function Ht(e,t=240){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}const Ut=3,Wt=5;var Gt=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),U.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:Ht(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&&U.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>3?{allowed:!1,reason:`Maximum subagent depth (3) 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`){U.info(`subagent status changed`,t);return}if(e.status===`killed`){U.warn(`subagent status changed`,t);return}U.error(`subagent status changed`,t)}};const Kt=new Map;function qt(e){let t=Kt.get(e);return t||(t={},Kt.set(e,t)),t}function Jt(e){Kt.delete(e)}var W=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 Yt(e){return{async chat(t){let n=Xt(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await $t(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:Zt(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}=en(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 nn(e,s())}if(!t.ok){let e=await tn(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new W({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:an(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new W({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=Qt(o.usage),u=Math.max(0,Date.now()-n);return await $t(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 Xt(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 Zt(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
9
+ `)}function Qt(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 $t(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function en(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 tn(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function nn(e,t){return e instanceof W?e:rn(e)?t?new W({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new W({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function rn(e){return e instanceof Error&&e.name===`AbortError`}function an(e){return e===408||e===409||e===425||e===429||e>=500}function on(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function sn(e){if(!on(e))return null;let t=e,n=cn(t.message),r=G(n?.code)??G(t.code),i=G(n?.type)??G(t.type),a=G(n?.message)??ln(t.error)??G(t.message)??`Unknown upstream error`;return{message:un(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:dn(r,i),raw:e}}function cn(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 ln(e){if(!(!e||typeof e!=`object`))return G(e.message)}function G(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function un(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function dn(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 fn=(e,t,n)=>{let r=new ke;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=mn(e,t,n?.apiKey||Ce(e.provider)||``,n?.headers),o=hn(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=we(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=sn(t);if(n)throw new W({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}},Se(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=xn(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=we(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 W&&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},pn=(e,t,n)=>{let r=n?.apiKey||Ce(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Ne(e,n,r),a=De(e)?n?.reasoning:Pe(n?.reasoning);return fn(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function mn(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=Me(t.messages);Object.assign(i,je({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new Oe({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function hn(e,t,n){let r=Cn(e),i=yn(e,t,r);vn(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=bn(t.tools,r):gn(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 gn(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 _n(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 vn(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 yn(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return _n(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=Fe(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Ae(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:Ae(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Ae(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=>Ae(e.text)).join(``):a.map(e=>({type:`text`,text:Ae(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:B(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 Ut(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function Wt(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 Gt(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 Kt(e){let t=Gt(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 qt=!1;function Jt(){qt||=(De(),Ee({api:`openai-completions`,stream:Ft,streamSimple:It}),!0)}var Yt=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 Xt=[`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 Zt(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 $t(s);let c=r.flashModel,l=yt({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:Xt,user:JSON.stringify(u),temperature:0,maxTokens:100,signal:i});console.log(`🚀 ~ generateSessionTitle ~ result:`,e);let t=e.text.trim();if(!t)throw Error(`LLM title generation returned empty content`);return t.length>80?t.slice(0,79)+`…`:t}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;e<3&&await Qt(500*e)}return $t(s)}function Qt(e){return new Promise(t=>setTimeout(t,e))}function $t(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)+`…`}async function en(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 tn(e){let{sessionId:n,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 t(i.dataDir,n,{storeName:i.sessionStoreName});await a.dispatch(`session_end`,{sessionId:n,messageCount:s.length,durationMs:r.durationMs},o,{eventDispatcher:e.eventDispatcher})}async function nn(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:a,initialUserEntryPersisted:o=!1,runParams:c,hookRegistry:l,hookContext:u,startTime:d,compactionEntry:f,eventDispatcher:p}=e;if(o||await O(c.dataDir,n,{role:`user`,content:a,timestamp:new Date().toISOString()}),f&&await O(c.dataDir,n,f),await O(c.dataDir,n,{role:`assistant`,content:t,timestamp:new Date().toISOString()}),r){let t=await Zt({message:a.trim()?a:`New session`,llm:c.llm,text:e.replyText,hooks:l,hookCtx:u});await s(c.dataDir,n,{title:t},{storeName:c.sessionStoreName}),await p.dispatchProgress(n,{type:`title_updated`,title:t})}let m={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:Date.now()-d,context:{snapshotPath:h(c.dataDir,n,{storeName:c.sessionStoreName}),toolResultsDir:i(c.dataDir,n,{storeName:c.sessionStoreName})}};return await tn({sessionId:n,result:m,runParams:c,hookRegistry:l,hookContext:u,eventDispatcher:p}),m}async function rn(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:a,hookRegistry:o,hookContext:c,startTime:l,text:u,usage:d,error:f,paused:p,uiToolPending:m,eventDispatcher:g}=e;if(n){let n=await Zt({message:r,llm:a.llm,text:e.text,hooks:o,hookCtx:c});await s(a.dataDir,t,{title:n},{storeName:a.sessionStoreName}),await g.dispatchProgress(t,{type:`title_updated`,title:n})}let _={sessionId:t,text:u,usage:d,durationMs:Date.now()-l,error:f,paused:p,uiToolPending:m,context:{snapshotPath:h(a.dataDir,t,{storeName:a.sessionStoreName}),toolResultsDir:i(a.dataDir,t,{storeName:a.sessionStoreName})}};return await tn({sessionId:t,result:_,runParams:a,hookRegistry:o,hookContext:c,eventDispatcher:g}),_}const an=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`}];function on(){return an.map(e=>({...e}))}function sn(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function cn(e){let t=new Set,n=[];for(let r of e){let e=sn(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function ln(e){let t=on(),n=cn(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 dn(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 fn(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 pn(e,t){let n=dn(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:sn(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(cn(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 mn=new Set([`/new`,`/reset`,`/compact`]),hn=new Set([`/help`]);function gn(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function _n(e){if(e.length===0)return[];let t=e.map(gn),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function vn(e){let t=ln(e.skills),n=t.builtin.filter(e=>mn.has(e.name)),r=t.builtin.filter(e=>e.name===`/skill`),i=t.builtin.filter(e=>hn.has(e.name)),a=t.skillCommands.slice(0,4),o=[];return o.push(`帮助`),o.push(``),o.push(`会话命令`),o.push(..._n(n)),o.push(``),o.push(`技能命令`),o.push(..._n(r)),a.length>0?(o.push(..._n(a)),t.skillCommands.length>a.length&&o.push(` ... 还有 ${t.skillCommands.length-a.length} 个`)):o.push(` 未安装技能命令`),o.push(``),o.push(`其他命令`),o.push(..._n(i)),{kind:`reply`,text:o.join(`
13
- `)}}function yn(e,t){let n=t.trim().toLowerCase();return n&&cn(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function bn(e){let t=yn(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:Ae(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 bn(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function xn(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 Sn(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 Cn(e){let t=Sn(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 wn=!1;function Tn(){wn||=(Ee(),Te({api:`openai-completions`,stream:fn,streamSimple:pn}),!0)}var En=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 Dn=[`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 On(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 An(s);let c=r.flashModel,l=Yt({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:Dn,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 kn(500*e)}return An(s)}function kn(e){return new Promise(t=>setTimeout(t,e))}function An(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)+`…`}async function jn(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 Mn(e){let{sessionId:n,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 t(i.dataDir,n,{storeName:i.sessionStoreName});await a.dispatch(`session_end`,{sessionId:n,messageCount:s.length,durationMs:r.durationMs},o,{eventDispatcher:e.eventDispatcher})}async function Nn(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:a,initialUserEntryPersisted:o=!1,runParams:c,hookRegistry:l,hookContext:u,startTime:d,compactionEntry:f,eventDispatcher:p}=e;if(o||await O(c.dataDir,n,{role:`user`,content:a,timestamp:new Date().toISOString()}),f&&await O(c.dataDir,n,f),await O(c.dataDir,n,{role:`assistant`,content:t,timestamp:new Date().toISOString()}),r){let t=await On({message:a.trim()?a:`New session`,llm:c.llm,text:e.replyText,hooks:l,hookCtx:u});await s(c.dataDir,n,{title:t},{storeName:c.sessionStoreName}),await p.dispatchProgress(n,{type:`title_updated`,title:t})}let m=Date.now()-d,g={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:m,context:{snapshotPath:h(c.dataDir,n,{storeName:c.sessionStoreName}),toolResultsDir:i(c.dataDir,n,{storeName:c.sessionStoreName})}};return U.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:m,isNewSession:r,textLength:t.length,hasCompactionEntry:!!f,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir}),await Mn({sessionId:n,result:g,runParams:c,hookRegistry:l,hookContext:u,eventDispatcher:p}),g}async function Pn(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:a,hookRegistry:o,hookContext:c,startTime:l,text:u,usage:d,error:f,paused:p,uiToolPending:m,eventDispatcher:g}=e;if(n){let n=await On({message:r,llm:a.llm,text:e.text,hooks:o,hookCtx:c});await s(a.dataDir,t,{title:n},{storeName:a.sessionStoreName}),await g.dispatchProgress(t,{type:`title_updated`,title:n})}let _={sessionId:t,text:u,usage:d,durationMs:Date.now()-l,error:f,paused:p,uiToolPending:m,context:{snapshotPath:h(a.dataDir,t,{storeName:a.sessionStoreName}),toolResultsDir:i(a.dataDir,t,{storeName:a.sessionStoreName})}},v={sessionId:t,kind:`completed`,durationMs:_.durationMs,isNewSession:n,inputTokens:d.input,outputTokens:d.output,totalTokens:d.total,hasError:!!f,error:f,paused:!!p,uiToolPending:!!m,textLength:u.length,snapshotPath:_.context.snapshotPath,toolResultsDir:_.context.toolResultsDir};return f?U.warn(`agent run finalized with error`,v):U.info(`agent run finalized`,v),await Mn({sessionId:t,result:_,runParams:a,hookRegistry:o,hookContext:c,eventDispatcher:g}),_}const Fn=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`}];function In(){return Fn.map(e=>({...e}))}function Ln(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Rn(e){let t=new Set,n=[];for(let r of e){let e=Ln(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function zn(e){let t=In(),n=Rn(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function Bn(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 Vn(e){let t=Bn(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 Hn(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 Un(e,t){let n=Vn(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:Ln(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Rn(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 Wn=new Set([`/new`,`/reset`,`/compact`]),Gn=new Set([`/help`]);function Kn(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function qn(e){if(e.length===0)return[];let t=e.map(Kn),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Jn(e){let t=zn(e.skills),n=t.builtin.filter(e=>Wn.has(e.name)),r=t.builtin.filter(e=>e.name===`/skill`),i=t.builtin.filter(e=>Gn.has(e.name)),a=t.skillCommands.slice(0,4),o=[];return o.push(`帮助`),o.push(``),o.push(`会话命令`),o.push(...qn(n)),o.push(``),o.push(`技能命令`),o.push(...qn(r)),a.length>0?(o.push(...qn(a)),t.skillCommands.length>a.length&&o.push(` ... 还有 ${t.skillCommands.length-a.length} 个`)):o.push(` 未安装技能命令`),o.push(``),o.push(`其他命令`),o.push(...qn(i)),{kind:`reply`,text:o.join(`
15
+ `)}}function Yn(e,t){let n=t.trim().toLowerCase();return n&&Rn(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function Xn(e){let t=Yn(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 xn(e){let t=pn(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?vn(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?bn({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 G(e){return Math.ceil(e.length/4*1.2)}function Sn(e){if(e.role===`user`)return G(e.content);if(e.role===`assistant`){let t=G(e.content);for(let n of e.toolCalls??[])t+=G(n.name)+G(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 G(e.toolName)+G(t)}function K(e){return e.reduce((e,t)=>e+Sn(t),0)}const Cn=[`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 wn(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=En(t,r,i),l,u=yt({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:Cn,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 Tn(500*e)}throw l}function Tn(e){return new Promise(t=>setTimeout(t,e))}function En(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`?Dn(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 Zn(e){let t=Un(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Jn(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?Xn({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 Qn(e){return Math.ceil(e.length/4*1.2)}function $n(e){if(e.role===`user`)return Qn(e.content);if(e.role===`assistant`){let t=Qn(e.content);for(let n of e.toolCalls??[])t+=Qn(n.name)+Qn(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 Qn(e.toolName)+Qn(t)}function K(e){return e.reduce((e,t)=>e+$n(t),0)}const er=[`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 tr(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=rr(t,r,i),l,u=Yt({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:er,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 nr(500*e)}throw l}function nr(e){return new Promise(t=>setTimeout(t,e))}function rr(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`?ir(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 Dn(e){let t=On(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 On(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=kn(t);if(e.name||e.path)return e}return{}}function kn(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 An(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Sn(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function jn(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 Mn(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Nn(t),l=c>=0?t[c].content:void 0,u=jn(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}=An(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:K(u)}:{status:`compacted`,entry:{role:`compaction`,content:await wn({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:K(d)}}function Nn(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Pn=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
21
- `),Fn=[`.aimax/new.txt`];async function In(e){try{return(await be(e,`utf-8`)).trim()||null}catch{return null}}async function Ln(e){for(let t of Fn){let n=await In(xe(e,t));if(n)return n}return await In(`/aimax/new.txt`)||Pn}async function Rn(e){return{kind:`reply`,text:await Ln(e)}}function zn(){return{kind:`reply`,text:`✅ Session reset.`}}function Bn(e){let t=Un(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Wn(r):null,a=n??i?.text,o=a?fn(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Gn(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Kn(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Vn(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=xn({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:Gn(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Kn(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Hn(e){let n=Vn(e.invocation,e.skills);if(n.kind===`run`)return{kind:`continue`,effectivePrompt:n.effectivePrompt,transcriptMessage:n.transcriptMessage};if(n.kind===`reset_reply`)return{kind:`completed`,result:await nn({replyText:(n.action===`reset`?zn():await Rn(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(n.kind===`reply`)return{kind:`completed`,result:await nn({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};let r=await Mn({entries:e.runParams.channel===`CRON`?[]:await t(e.runParams.dataDir,e.sessionId),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:n.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await nn({replyText:r.status===`compacted`?`⚙️ Compacted (kept ${r.keptCount}, dropped ${r.droppedCount}).`:`⚙️ Compaction skipped: ${r.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.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 Un(e){return typeof e.message==`string`}function Wn(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 Gn(e,t){let n=Wn(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 Kn(e){return typeof e==`string`?e:JSON.stringify(e)}function qn(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 Jn=[`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.`],Yn={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Xn(e,t){return e.map(e=>Zn(e,t))}function Zn(e,t){let n=new Date(e.timestamp).getTime();if(Qn(e))return{role:`user`,content:e.content,timestamp:n};if($n(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:Yn,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:er(r)}],isError:r.isError,timestamp:n}}function Qn(e){return e.role===`user`}function $n(e){return e.role===`assistant`}function er(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:`,...Jn];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
22
- `)}const tr=[`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 nr(e){let t=h(e.dataDir,e.sessionId,e),n=new Map,r=new Map,a=[],o=[],s=[],c,l,u=0,d,f,p=await sr(t);for(let e of p.readStates)n.set(rr(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);a.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:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await L.mkdir(R.dirname(t),{recursive:!0}),await L.writeFile(t,JSON.stringify(e,null,2),`utf-8`)};return{async findReusableRead(e,t,r){let i=rr(e,t,r),a=n.get(i);if(!a)return null;let o=await ar(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:or(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await ar(e.path)??Date.now()};return n.set(rr(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())ir(i.path)===ir(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=i(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=R.join(s,c);await L.mkdir(s,{recursive:!0}),await L.writeFile(l,t.content,`utf-8`);let u=R.relative(e.dataDir,l).split(R.sep).join(`/`),p=dr(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),a.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:ur(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 fr(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:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function rr(e,t,n){return`${ir(e)}::${t??``}::${n??``}`}function ir(e){return R.normalize(e)}async function ar(e){try{return(await L.stat(e)).mtimeMs}catch{return null}}function or(e){return Ie(`sha1`).update(e).digest(`hex`)}async function sr(e){try{let t=await L.readFile(e,`utf-8`),n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?cr():{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:lr(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 cr()}}function cr(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function lr(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 ur(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:`,...tr,`Preview:`,e.preview+t].join(`
24
- `)}function dr(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 fr(t,n,r,i){let a=e(t,n,i);await L.mkdir(R.dirname(a),{recursive:!0}),await L.writeFile(a,JSON.stringify(r,null,2),`utf-8`)}const pr=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function mr(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}=e,h,g=Er(t),_=g>=0?t.slice(g+1):t;g>=0&&(h=t[g].content);let v=t.length,y=jn(qn(_,a)),b=[];d&&(h=await hr({entries:y,existingSummary:h,llm:i,contextStore:d,signal:c,hooks:l,hookCtx:u}));let x=y;if(x=await gr({entries:x,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:d,compactionEvents:b}),x=await _r({entries:x,contextStore:d,compactionEvents:b}),x=await vr({entries:x,contextStore:d,compactionEvents:b,dataDir:f,sessionId:p,sessionStoreName:m}),!o)return{messages:Xn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let S=d?.getSnapshot(),C=Math.max(1e3,Math.floor(r*.7)),w=Dr({entries:t,workingEntries:x,pendingUserMessage:s,checkpoint:S?.compaction.modelUsage}).projectedInputTokens>=C,T=S?.compaction.consecutiveAutocompactFailures??0;if(!w||T>=3)return{messages:Xn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let{toKeep:E,toSummarise:D}=An(x,r);if(D.length===0)return{messages:Xn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let O=new Date().toISOString();try{let e=S?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await wn({entries:D,llm:i,previousSummary:h,signal:c,hooks:l,hookCtx:u}),r={role:`compaction`,content:t,keptCount:E.length,droppedCount:D.length,timestamp:O};return await d?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:O}),b.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${D.length} entries with session memory`:`Autocompact summarised ${D.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,K(D)),affectedEntries:D.length,snapshotVersion:2}),{messages:Xn(jn(E),n),priorSummary:t,compactionEntry:r,stats:{originalCount:v,keptCount:E.length,estimatedTokens:K(E),compacted:!0},compactionEvents:b}}catch{return await d?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:O}),{messages:Xn(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:[...b,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function hr(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=K(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&Tr(t)>=3;if(!u&&!d)return n??l?.summary;let f=await wn({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 gr(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(br).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(!br(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=xr(n)?Sr(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}),jn(l.reverse())}async function _r(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-36e5,a=0,o=0,s=[];for(let e of t){if(!br(e)){s.push(e);continue}let t=Date.parse(e.timestamp);if(!(t>0&&t<i)){s.push(e);continue}let r=xr(e)?Sr(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}),gr({entries:s,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function vr(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o}=e,s=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(s.length<=2)return t;let c=s[s.length-2]??t.length,l=[],u=0,d=0,f=0;for(;u<t.length;){if(u>=c||t[u]?.role===`user`){l.push(t[u]),u+=1;continue}let e=u;for(;u<c&&t[u]?.role!==`user`;)u+=1;let r=t.slice(e,u),s=r.filter(br).filter(e=>pr.has(e.toolName)),p=s.reduce((e,t)=>e+t.content.length,0);if(s.length<3||p<1500){l.push(...r);continue}let m=yr(r,s),h=new Date().toISOString(),g={role:`assistant`,content:m,timestamp:h};l.push(g),d+=r.length,f+=Math.max(0,Math.floor(K(r)-K([g])));let _={id:Le(),layer:`L5`,startEntryIndex:e,endEntryIndex:u-1,toolNames:[...new Set(s.map(e=>e.toolName))],summary:m,sourceCount:r.length,estimatedTokensFreed:f,createdAt:h};await n?.recordCollapse(_),i&&a&&await Or(i,a,_,o)}return d>0&&r.push({type:`compaction`,reason:`Collapsed ${d} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:f,affectedEntries:d,snapshotVersion:2}),l}function yr(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 ir(e){let t=ar(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 ar(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=or(t);if(e.name||e.path)return e}return{}}function or(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 sr(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=$n(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function cr(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 lr(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=ur(t),l=c>=0?t[c].content:void 0,u=cr(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}=sr(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:K(u)}:{status:`compacted`,entry:{role:`compaction`,content:await tr({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:K(d)}}function ur(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const dr=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
23
+ `),fr=[`.aimax/new.txt`];async function pr(e){try{return(await ve(e,`utf-8`)).trim()||null}catch{return null}}async function mr(e){for(let t of fr){let n=await pr(ye(e,t));if(n)return n}return await pr(`/aimax/new.txt`)||dr}async function hr(e){return{kind:`reply`,text:await mr(e)}}function gr(){return{kind:`reply`,text:`✅ Session reset.`}}function _r(e){let t=br(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?xr(r):null,a=n??i?.text,o=a?Hn(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Sr(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Cr(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function vr(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=Zn({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:Sr(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Cr(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function yr(e){let n=vr(e.invocation,e.skills);if(n.kind===`run`)return{kind:`continue`,effectivePrompt:n.effectivePrompt,transcriptMessage:n.transcriptMessage};if(n.kind===`reset_reply`)return{kind:`completed`,result:await Nn({replyText:(n.action===`reset`?gr():await hr(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(n.kind===`reply`)return{kind:`completed`,result:await Nn({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};let r=await lr({entries:e.runParams.channel===`CRON`?[]:await t(e.runParams.dataDir,e.sessionId),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:n.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await Nn({replyText:r.status===`compacted`?`⚙️ Compacted (kept ${r.keptCount}, dropped ${r.droppedCount}).`:`⚙️ Compaction skipped: ${r.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:n.transcriptMessage,initialUserEntryPersisted:n.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 br(e){return typeof e.message==`string`}function xr(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 Sr(e,t){let n=xr(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 Cr(e){return typeof e==`string`?e:JSON.stringify(e)}function wr(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 Tr=[`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.`],Er={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Dr(e,t){return e.map(e=>Or(e,t))}function Or(e,t){let n=new Date(e.timestamp).getTime();if(kr(e))return{role:`user`,content:e.content,timestamp:n};if(Ar(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:Er,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:jr(r)}],isError:r.isError,timestamp:n}}function kr(e){return e.role===`user`}function Ar(e){return e.role===`assistant`}function jr(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:`,...Tr];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
24
+ `)}const Mr=[`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 Nr(e){let t=h(e.dataDir,e.sessionId,e),n=new Map,r=new Map,a=[],o=[],s=[],c,l,u=0,d,f,p=await Rr(t);for(let e of p.readStates)n.set(Pr(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);a.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:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await z.mkdir(B.dirname(t),{recursive:!0}),await z.writeFile(t,JSON.stringify(e,null,2),`utf-8`)};return{async findReusableRead(e,t,r){let i=Pr(e,t,r),a=n.get(i);if(!a)return null;let o=await Ir(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:Lr(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await Ir(e.path)??Date.now()};return n.set(Pr(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())Fr(i.path)===Fr(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=i(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=B.join(s,c);await z.mkdir(s,{recursive:!0}),await z.writeFile(l,t.content,`utf-8`);let u=B.relative(e.dataDir,l).split(B.sep).join(`/`),p=Hr(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),a.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:Vr(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 Ur(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:a.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function Pr(e,t,n){return`${Fr(e)}::${t??``}::${n??``}`}function Fr(e){return B.normalize(e)}async function Ir(e){try{return(await z.stat(e)).mtimeMs}catch{return null}}function Lr(e){return Ie(`sha1`).update(e).digest(`hex`)}async function Rr(e){try{let t=await z.readFile(e,`utf-8`),n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?zr():{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:Br(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 zr()}}function zr(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Br(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 Vr(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:`,...Mr,`Preview:`,e.preview+t].join(`
26
+ `)}function Hr(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 Ur(t,n,r,i){let a=e(t,n,i);await z.mkdir(B.dirname(a),{recursive:!0}),await z.writeFile(a,JSON.stringify(r,null,2),`utf-8`)}const Wr=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Gr(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}=e,h,g=ri(t),_=g>=0?t.slice(g+1):t;g>=0&&(h=t[g].content);let v=t.length,y=cr(wr(_,a)),b=[];d&&(h=await Kr({entries:y,existingSummary:h,llm:i,contextStore:d,signal:c,hooks:l,hookCtx:u}));let x=y;if(x=await qr({entries:x,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:d,compactionEvents:b}),x=await Jr({entries:x,contextStore:d,compactionEvents:b}),x=await Yr({entries:x,contextStore:d,compactionEvents:b,dataDir:f,sessionId:p,sessionStoreName:m}),!o)return{messages:Dr(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let S=d?.getSnapshot(),C=Math.max(1e3,Math.floor(r*.7)),w=ii({entries:t,workingEntries:x,pendingUserMessage:s,checkpoint:S?.compaction.modelUsage}).projectedInputTokens>=C,T=S?.compaction.consecutiveAutocompactFailures??0;if(!w||T>=3)return{messages:Dr(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let{toKeep:E,toSummarise:D}=sr(x,r);if(D.length===0)return{messages:Dr(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:b};let O=new Date().toISOString();try{let e=S?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await tr({entries:D,llm:i,previousSummary:h,signal:c,hooks:l,hookCtx:u}),r={role:`compaction`,content:t,keptCount:E.length,droppedCount:D.length,timestamp:O};return await d?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:O}),b.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${D.length} entries with session memory`:`Autocompact summarised ${D.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,K(D)),affectedEntries:D.length,snapshotVersion:2}),{messages:Dr(cr(E),n),priorSummary:t,compactionEntry:r,stats:{originalCount:v,keptCount:E.length,estimatedTokens:K(E),compacted:!0},compactionEvents:b}}catch{return await d?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:O}),{messages:Dr(x,n),priorSummary:h,compactionEntry:void 0,stats:{originalCount:v,keptCount:x.length,estimatedTokens:K(x),compacted:!1},compactionEvents:[...b,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function Kr(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=K(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&ni(t)>=3;if(!u&&!d)return n??l?.summary;let f=await tr({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 qr(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Zr).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(!Zr(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=Qr(n)?$r(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}),cr(l.reverse())}async function Jr(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-36e5,a=0,o=0,s=[];for(let e of t){if(!Zr(e)){s.push(e);continue}let t=Date.parse(e.timestamp);if(!(t>0&&t<i)){s.push(e);continue}let r=Qr(e)?$r(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}),qr({entries:s,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Yr(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o}=e,s=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(s.length<=2)return t;let c=s[s.length-2]??t.length,l=[],u=0,d=0,f=0;for(;u<t.length;){if(u>=c||t[u]?.role===`user`){l.push(t[u]),u+=1;continue}let e=u;for(;u<c&&t[u]?.role!==`user`;)u+=1;let r=t.slice(e,u),s=r.filter(Zr).filter(e=>Wr.has(e.toolName)),p=s.reduce((e,t)=>e+t.content.length,0);if(s.length<3||p<1500){l.push(...r);continue}let m=Xr(r,s),h=new Date().toISOString(),g={role:`assistant`,content:m,timestamp:h};l.push(g),d+=r.length,f+=Math.max(0,Math.floor(K(r)-K([g])));let _={id:Le(),layer:`L5`,startEntryIndex:e,endEntryIndex:u-1,toolNames:[...new Set(s.map(e=>e.toolName))],summary:m,sourceCount:r.length,estimatedTokensFreed:f,createdAt:h};await n?.recordCollapse(_),i&&a&&await ai(i,a,_,o)}return d>0&&r.push({type:`compaction`,reason:`Collapsed ${d} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:f,affectedEntries:d,snapshotVersion:2}),l}function Xr(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 br(e){return e.role===`tool_result`}function xr(e){return e.toolName===`skill_load`}function Sr(e){let t=Cr(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 Cr(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=wr(t);if(e.name||e.path)return e}return{}}function wr(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 Tr(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Er(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Dr(e){let t=e.pendingUserMessage?.trim()?K([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=K(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=K(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 Or(e,t,n,r){let i=m(e,t,{storeName:r});await L.mkdir(R.dirname(i),{recursive:!0}),await L.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function kr(e){let t=await nr({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName});return{async getReusableRead(e,n,r){let i=await t.findReusableRead(e,n,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await t.recordRead(e)},async invalidateReadPath(e){await t.invalidatePath(e)},persistToolResult(e){return t.persistToolResult(e)},async recordModelUsage(e){await t.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(n){return mr({...n,contextStore:t,sessionStoreName:e.sessionStoreName})},getSnapshot:t.getSnapshot}}async function Ar(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}):mr({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 jr=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 q(e){return!!(e instanceof jr||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const Mr=z.Object({command:z.String({description:`Shell command to execute`}),workdir:z.Optional(z.String({description:`Working directory (relative to workspace root)`})),env:z.Optional(z.Record(z.String(),z.String())),timeout:z.Optional(z.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:z.Optional(z.Number({description:`Wait this many milliseconds before returning running state`})),background:z.Optional(z.Boolean({description:`Return immediately with running session`}))});function Nr(e,t,n){return Math.max(t,Math.min(n,e))}function Pr(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Fr(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:Nr(Math.floor(e),0,12e4)}function Ir(e,t){if(!t?.trim())return e;let n=R.isAbsolute(t)?R.normalize(t):R.normalize(R.join(e,t));if(!n.startsWith(e+R.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Lr(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 Rr(e){return Br({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
33
- `)}function zr(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Br(e){let t=zr(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 Vr(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:Mr,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=Ir(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Pr(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,Fr(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Lr(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?Br({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[Rr(l)],p=zr(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 Hr=z.Object({action:z.String({description:`Process action: list | poll | log | kill`}),sessionId:z.Optional(z.String({description:`Session id for non-list actions`})),offset:z.Optional(z.Number({description:`Log line offset (0-based)`})),limit:z.Optional(z.Number({description:`Maximum lines to return`})),timeout:z.Optional(z.Number({description:`Poll wait time in milliseconds`}))});function Ur(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Wr(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Gr(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:Hr,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
35
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Wr(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Ur(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`}}:Wr(`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}}:Wr(`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}}:Wr(`No session found for ${i}`)}return Wr(`Unsupported action: ${n.action}`)}}}const Kr=2e5;function qr(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Jr(e,t){let n=e+t;return n.length<=Kr?{text:n,truncated:!1}:{text:n.slice(-Kr),truncated:!0}}function Yr(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Jr(e.output,r);e.output=i.text;let a=Jr(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function J(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:qr(e.output),stdoutTail:qr(e.stdout),stderrTail:qr(e.stderr),outputTruncated:e.outputTruncated}}function Y(e,t){return t?e.scopeKey===t:!0}function Xr(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Zr(e){return e?e.split(/\r?\n/):[]}function Qr(e){let t=Zr(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Xr(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 $r(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function ei(){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),$r(e))};return{start(t){let n=Be(`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:Le(),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=>Yr(o,`stdout`,e)),n.stderr.on(`data`,e=>Yr(o,`stderr`,e));let s=Xr(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Yr(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`),Yr(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),J(o)},get(e,t){let n=r(e);return!n||!Y(n,t)?null:J(n)},list(n){return[...e.values(),...t.values()].filter(e=>Y(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>J(e))},async wait(e,t,n){let i=r(e);if(!i||!Y(i,t))return null;if(i.status!==`running`)return J(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!Y(a,t)?null:J(a)},readLog(e){let t=r(e.sessionId);return!t||!Y(t,e.scopeKey)?null:Qr({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Y(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!Y(n,t))return null;if(n.status!==`running`)return J(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?J(i):null}}}function ti(e){return Vr({workspaceDir:e,registry:ei(),scopeKey:e})}const ni=5*1024*1024,ri=2e3;function ii(e,t){return R.isAbsolute(e)?R.normalize(e):R.normalize(R.join(t,e))}const ai=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),offset:z.Optional(z.Number({description:`Line offset (1-based, default: 1)`})),limit:z.Optional(z.Number({description:`Maximum lines to read (default: 2000)`}))});function oi(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:ai,async execute(n,r){let i;try{i=ii(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 L.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 Ve(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>ni){let e=o.slice(0,ni).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${ni} 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(`
33
+ `)}function Zr(e){return e.role===`tool_result`}function Qr(e){return e.toolName===`skill_load`}function $r(e){let t=ei(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 ei(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=ti(t);if(e.name||e.path)return e}return{}}function ti(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 ni(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function ri(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function ii(e){let t=e.pendingUserMessage?.trim()?K([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=K(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=K(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 ai(e,t,n,r){let i=m(e,t,{storeName:r});await z.mkdir(B.dirname(i),{recursive:!0}),await z.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function oi(e){let t=await Nr({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName});return{async getReusableRead(e,n,r){let i=await t.findReusableRead(e,n,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await t.recordRead(e)},async invalidateReadPath(e){await t.invalidatePath(e)},persistToolResult(e){return t.persistToolResult(e)},async recordModelUsage(e){await t.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(n){return Gr({...n,contextStore:t,sessionStoreName:e.sessionStoreName})},getSnapshot:t.getSnapshot}}async function si(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}):Gr({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 ci=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 q(e){return!!(e instanceof ci||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const li=H.Object({command:H.String({description:`Shell command to execute`}),workdir:H.Optional(H.String({description:`Working directory (relative to workspace root)`})),env:H.Optional(H.Record(H.String(),H.String())),timeout:H.Optional(H.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:H.Optional(H.Number({description:`Wait this many milliseconds before returning running state`})),background:H.Optional(H.Boolean({description:`Return immediately with running session`}))});function ui(e,t,n){return Math.max(t,Math.min(n,e))}function di(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function fi(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:ui(Math.floor(e),0,12e4)}function pi(e,t){if(!t?.trim())return e;let n=B.isAbsolute(t)?B.normalize(t):B.normalize(B.join(e,t));if(!n.startsWith(e+B.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function mi(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 hi(e){return _i({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
35
+ `)}function gi(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function _i(e){let t=gi(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 vi(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:li,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=pi(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=di(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,fi(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:mi(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?_i({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[hi(l)],p=gi(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 yi=H.Object({action:H.String({description:`Process action: list | poll | log | kill`}),sessionId:H.Optional(H.String({description:`Session id for non-list actions`})),offset:H.Optional(H.Number({description:`Log line offset (0-based)`})),limit:H.Optional(H.Number({description:`Maximum lines to return`})),timeout:H.Optional(H.Number({description:`Poll wait time in milliseconds`}))});function bi(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function xi(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Si(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:yi,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 xi(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,bi(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`}}:xi(`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}}:xi(`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}}:xi(`No session found for ${i}`)}return xi(`Unsupported action: ${n.action}`)}}}const Ci=2e5;function wi(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Ti(e,t){let n=e+t;return n.length<=Ci?{text:n,truncated:!1}:{text:n.slice(-Ci),truncated:!0}}function Ei(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Ti(e.output,r);e.output=i.text;let a=Ti(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function J(e){return{sessionId:e.sessionId,scopeKey:e.scopeKey,command:e.command,cwd:e.cwd,pid:typeof e.child.pid==`number`?e.child.pid:void 0,startedAt:e.startedAt,endedAt:e.endedAt,status:e.status,exitCode:e.exitCode,exitSignal:e.exitSignal,outputTail:wi(e.output),stdoutTail:wi(e.stdout),stderrTail:wi(e.stderr),outputTruncated:e.outputTruncated}}function Y(e,t){return t?e.scopeKey===t:!0}function Di(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Oi(e){return e?e.split(/\r?\n/):[]}function ki(e){let t=Oi(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Di(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 Ai(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function ji(){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),Ai(e))};return{start(t){let n=Be(`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:Le(),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=>Ei(o,`stdout`,e)),n.stderr.on(`data`,e=>Ei(o,`stderr`,e));let s=Di(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Ei(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`),Ei(o,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),n.on(`close`,(e,t)=>{i(o,()=>{o.exitCode=e,o.exitSignal=t,o.status===`running`?o.status=e===0?`completed`:`failed`:o.status===`killed`&&e===0&&(o.status=`completed`)})}),J(o)},get(e,t){let n=r(e);return!n||!Y(n,t)?null:J(n)},list(n){return[...e.values(),...t.values()].filter(e=>Y(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>J(e))},async wait(e,t,n){let i=r(e);if(!i||!Y(i,t))return null;if(i.status!==`running`)return J(i);typeof n==`number`&&Number.isFinite(n)&&n>=0?await Promise.race([i.donePromise,new Promise(e=>{setTimeout(e,n)})]):await i.donePromise;let a=r(e);return!a||!Y(a,t)?null:J(a)},readLog(e){let t=r(e.sessionId);return!t||!Y(t,e.scopeKey)?null:ki({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Y(n,t)?null:{sessionId:n.sessionId,status:n.status,stdout:n.stdout,stderr:n.stderr,combined:n.output,truncated:n.outputTruncated,exitCode:n.exitCode,exitSignal:n.exitSignal}},async terminate(e,t){let n=r(e);if(!n||!Y(n,t))return null;if(n.status!==`running`)return J(n);n.status=`killed`,n.child.kill(`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&n.child.kill(`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?J(i):null}}}function Mi(e){return vi({workspaceDir:e,registry:ji(),scopeKey:e})}const Ni=5*1024*1024,Pi=2e3;function Fi(e,t){return B.isAbsolute(e)?B.normalize(e):B.normalize(B.join(t,e))}const Ii=H.Object({path:H.String({description:`File path (relative to workspace or absolute)`}),offset:H.Optional(H.Number({description:`Line offset (1-based, default: 1)`})),limit:H.Optional(H.Number({description:`Maximum lines to read (default: 2000)`}))});function Li(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Ii,async execute(n,r){let i;try{i=Fi(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 z.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 Ve(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>Ni){let e=o.slice(0,Ni).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Ni} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
39
+ `),l=Math.max(1,r.offset??1),u=Math.min(Pi,r.limit??Pi),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
40
  `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
39
41
  `),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 si=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),content:z.String({description:`File content to write`})});function ci(e,t){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:si,async execute(n,r){let i;try{i=ii(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path}}}try{await L.mkdir(R.dirname(i),{recursive:!0}),await L.writeFile(i,r.content,`utf-8`),await t?.invalidateReadPath(i)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:i}}}return{content:[{type:`text`,text:`File written: ${r.path}`}],details:{path:i}}}}}const li=z.Object({path:z.String({description:`File path (relative to workspace or absolute)`}),old_string:z.String({description:`Exact text to replace`}),new_string:z.String({description:`Replacement text`})});function ui(e,t){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:li,async execute(n,r){let i;try{i=ii(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path,occurrences:0}}}let a;try{a=await L.readFile(i,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{path:i,occurrences:0}}}if(!a.includes(r.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${r.path}`}],details:{path:i,occurrences:0}};let o=a.replace(r.old_string,r.new_string);return await L.writeFile(i,o,`utf-8`),await t?.invalidateReadPath(i),{content:[{type:`text`,text:`File edited: ${r.path}`}],details:{path:i,occurrences:1}}}}}const di=z.Object({path:z.Optional(z.String({description:`Directory path (default: workspace root)`}))});function fi(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:di,async execute(t,n){let r=n.path??`.`,i;try{i=ii(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await L.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 pi=z.Object({input:z.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function mi(e,t){let n=R.isAbsolute(e)?R.normalize(e):R.normalize(R.join(t,e));if(!n.startsWith(t+R.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function hi(e,t){let n=R.relative(t,e);return!n||n===``?R.basename(e):n.startsWith(`..`)||R.isAbsolute(n)?e:n}async function gi(e){await L.mkdir(R.dirname(e),{recursive:!0})}function _i(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 vi(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:pi,async execute(t,n){try{let t=n.input?.trim();if(!t)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let r=bi(t);if(r.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let i={added:[],modified:[],deleted:[]},a={added:new Set,modified:new Set,deleted:new Set};for(let t of r.hunks){if(t.kind===`add`){let n=mi(t.path,e);await gi(n),await L.writeFile(n,t.contents,`utf-8`),yi(i,a,`added`,hi(n,e));continue}if(t.kind===`delete`){let n=mi(t.path,e);await L.rm(n,{force:!0,recursive:!1}),yi(i,a,`deleted`,hi(n,e));continue}let n=mi(t.path,e),r=await wi(n,t.chunks);if(t.movePath){let o=mi(t.movePath,e);await gi(o),await L.writeFile(o,r,`utf-8`),await L.rm(n,{force:!0,recursive:!1}),yi(i,a,`modified`,hi(o,e))}else await L.writeFile(n,r,`utf-8`),yi(i,a,`modified`,hi(n,e))}return{content:[{type:`text`,text:_i(i)}],details:{summary:i}}}catch(e){if(q(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function yi(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function bi(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);xi(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Si(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function xi(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 Si(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}=Ci(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 Ci(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 wi(e,t){let n=(await L.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=Ei(n,Ti(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
44
- `)}function Ti(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Di(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=Di(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=Di(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 Ei(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 Di(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(Oi(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Oi(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Oi(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Oi(e,t,n,e=>ki(e.trim())))return n;return null}function Oi(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 ki(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 Ai(e){return R.join(e,`.aimax`)}function ji(e){return R.join(Ai(e),`MEMORY.md`)}async function Mi(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function X(e,t){let n=Ai(e),r=N({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?r.provider:C({dataDir:e,memoryDir:n,sessionId:t?.sessionId})}async function Ni(e){return D(Ai(e))}async function Pi(e){try{return await L.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Fi(e){return Pi(ji(e))}async function Ii(e,t,n){return await X(e,n).search(t)}async function Z(e,t,n,r,i){try{return await X(e,i).getLines(t,n,r)}catch{return null}}async function Li(e,t,n){let r=X(e,n);await r.append(t),await Mi(r,n?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}async function Ri(e,t,n,r){let i=X(e,r);if(i.appendRecent){await i.appendRecent(t,n),await Mi(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[n===`session`&&r?.sessionId?`session-${r.sessionId}.md`:`${new Date().toISOString().slice(0,10)}.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()});return}let a=new Date().toISOString().slice(0,10);await Li(e,`${n===`session`&&r?.sessionId?`[session:${r.sessionId}]`:`[${a}]`} ${t}\n`,r)}async function Q(e,t,n,r){let i=X(e,r);await i.updateFile(t,n),await Mi(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId,timestamp:new Date().toISOString()})}async function zi(e,t,n){let r=X(e,n);await r.deleteFile(t),await Mi(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId,timestamp:new Date().toISOString()})}const Bi=z.Object({query:z.String({description:`Search query (case-insensitive substring match)`})});function Vi(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:Bi,async execute(n,r){let i=(await Ii(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 Hi=z.Object({file:z.String({description:`Memory file path (from memory_search results)`}),start_line:z.Number({description:`Start line number (1-based)`}),end_line:z.Number({description:`End line number (1-based)`})});function Ui(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:Hi,async execute(n,r){let i=await Z(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 Wi=z.Object({content:z.String({description:`Content to write to memory`})});function Gi(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:Wi,async execute(n,r){try{return await Li(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 Ki=z.Object({section:z.Optional(z.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:z.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:z.Union([z.Literal(`append`),z.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function qi(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:Ki,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Li(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`,Ji(await Fi(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Li(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 Ji(e,t,n){let r=e.split(`
42
+ `),lines:d.length,truncated:f}}}}}const Ri=H.Object({path:H.String({description:`File path (relative to workspace or absolute)`}),content:H.String({description:`File content to write`})});function zi(e,t){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Ri,async execute(n,r){let i;try{i=Fi(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path}}}try{await z.mkdir(B.dirname(i),{recursive:!0}),await z.writeFile(i,r.content,`utf-8`),await t?.invalidateReadPath(i)}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:i}}}return{content:[{type:`text`,text:`File written: ${r.path}`}],details:{path:i}}}}}const Bi=H.Object({path:H.String({description:`File path (relative to workspace or absolute)`}),old_string:H.String({description:`Exact text to replace`}),new_string:H.String({description:`Replacement text`})});function Vi(e,t){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Bi,async execute(n,r){let i;try{i=Fi(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:r.path,occurrences:0}}}let a;try{a=await z.readFile(i,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{path:i,occurrences:0}}}if(!a.includes(r.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${r.path}`}],details:{path:i,occurrences:0}};let o=a.replace(r.old_string,r.new_string);return await z.writeFile(i,o,`utf-8`),await t?.invalidateReadPath(i),{content:[{type:`text`,text:`File edited: ${r.path}`}],details:{path:i,occurrences:1}}}}}const Hi=H.Object({path:H.Optional(H.String({description:`Directory path (default: workspace root)`}))});function Ui(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Hi,async execute(t,n){let r=n.path??`.`,i;try{i=Fi(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await z.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 Wi=H.Object({input:H.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Gi(e,t){let n=B.isAbsolute(e)?B.normalize(e):B.normalize(B.join(t,e));if(!n.startsWith(t+B.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Ki(e,t){let n=B.relative(t,e);return!n||n===``?B.basename(e):n.startsWith(`..`)||B.isAbsolute(n)?e:n}async function qi(e){await z.mkdir(B.dirname(e),{recursive:!0})}function Ji(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 Yi(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:Wi,async execute(t,n){try{let t=n.input?.trim();if(!t)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let r=Zi(t);if(r.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let i={added:[],modified:[],deleted:[]},a={added:new Set,modified:new Set,deleted:new Set};for(let t of r.hunks){if(t.kind===`add`){let n=Gi(t.path,e);await qi(n),await z.writeFile(n,t.contents,`utf-8`),Xi(i,a,`added`,Ki(n,e));continue}if(t.kind===`delete`){let n=Gi(t.path,e);await z.rm(n,{force:!0,recursive:!1}),Xi(i,a,`deleted`,Ki(n,e));continue}let n=Gi(t.path,e),r=await ta(n,t.chunks);if(t.movePath){let o=Gi(t.movePath,e);await qi(o),await z.writeFile(o,r,`utf-8`),await z.rm(n,{force:!0,recursive:!1}),Xi(i,a,`modified`,Ki(o,e))}else await z.writeFile(n,r,`utf-8`),Xi(i,a,`modified`,Ki(n,e))}return{content:[{type:`text`,text:Ji(i)}],details:{summary:i}}}catch(e){if(q(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Xi(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Zi(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Qi(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=$i(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Qi(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 $i(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}=ea(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 ea(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 ta(e,t){let n=(await z.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=ra(n,na(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
46
+ `)}function na(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=ia(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=ia(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=ia(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 ra(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 ia(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(aa(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(aa(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(aa(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(aa(e,t,n,e=>oa(e.trim())))return n;return null}function aa(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 oa(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 sa(e){return B.join(e,`.aimax`)}function ca(e){return B.join(sa(e),`MEMORY.md`)}async function X(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function la(e,t){let n=sa(e),r=M({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:C({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function ua(e){return D(sa(e))}async function da(e){try{return await z.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function fa(e){return da(ca(e))}async function pa(e,t,n){let{provider:r}=la(e,n);return await r.search(t)}async function ma(e,t,n,r,i){try{let{provider:a}=la(e,i);return await a.getLines(t,n,r)}catch{return null}}async function ha(e,t,n){let{provider:r,resolvedProviderId:i}=la(e,n);await r.append(t),await X(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 ga(e,t,n,r){let{provider:i,resolvedProviderId:a}=la(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 X(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await X(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 X(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 X(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await X(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 Z(e,t,n,r){let{provider:i,resolvedProviderId:a}=la(e,r);await i.updateFile(t,n),await X(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function _a(e,t,n){let{provider:r,resolvedProviderId:i}=la(e,n);await r.deleteFile(t),await X(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const va=H.Object({query:H.String({description:`Search query (case-insensitive substring match)`})});function ya(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:va,async execute(n,r){let i=(await pa(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 ba=H.Object({file:H.String({description:`Memory file path (from memory_search results)`}),start_line:H.Number({description:`Start line number (1-based)`}),end_line:H.Number({description:`End line number (1-based)`})});function xa(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:ba,async execute(n,r){let i=await ma(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 Sa=H.Object({content:H.String({description:`Content to write to memory`})});function Ca(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:Sa,async execute(n,r){try{return await ha(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 wa=H.Object({section:H.Optional(H.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:H.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:H.Union([H.Literal(`append`),H.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Ta(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:wa,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await ha(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 Z(e,`MEMORY.md`,Ea(await fa(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await ha(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 Ea(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 Yi(e,t){let n=e.split(`
53
+ `)}\n`}function Da(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 Xi(e,t){let n=e.split(`
57
+ `)}\n`:``}function Oa(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 Zi(e,t,n){let r=e.split(`
59
+ `)}\n`:``)}function ka(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 Qi(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 $i(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 ea=z.Object({content:z.String({description:`Note to append to today's daily log`}),scope:z.Optional(z.Union([z.Literal(`daily`),z.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function ta(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:ea,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Ri(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 na=z.Object({scope:z.Optional(z.Union([z.Literal(`long-term`),z.Literal(`recent`),z.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function ra(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:na,async execute(n,r){try{let n=r.scope??`all`,i=await Ni(e),a=[];for(let n of i.slice(0,30)){let r=await Z(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
61
- `),t=$i(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 Aa(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 ja(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 Ma=H.Object({content:H.String({description:`Note to append to today's daily log`}),scope:H.Optional(H.Union([H.Literal(`daily`),H.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Na(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:Ma,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await ga(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 Pa=H.Object({scope:H.Optional(H.Union([H.Literal(`long-term`),H.Literal(`recent`),H.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Fa(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:Pa,async execute(n,r){try{let n=r.scope??`all`,i=await ua(e),a=[];for(let n of i.slice(0,30)){let r=await ma(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
63
+ `),t=ja(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 ia=z.Object({id:z.Optional(z.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:z.Optional(z.String({description:`Search query used to find memories to delete`})),limit:z.Optional(z.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:z.Optional(z.Union([z.Literal(`long-term`),z.Literal(`recent`),z.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function aa(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:ia,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Qi(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Yi(await Fi(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 Z(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=Yi(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 Z(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=Xi(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 zi(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 Ii(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await zi(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 oa=z.Object({id:z.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:z.String({description:`New content to replace the existing memory with`})});function sa(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:oa,async execute(n,r){try{let n=Qi(r.id);if(n.section){let i=Ji(await Fi(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 Z(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=Zi(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 ca=z.Object({query:z.Optional(z.String({description:`Search query; omit to browse recent sessions.`})),role_filter:z.Optional(z.Union([z.Literal(`user`),z.Literal(`assistant`),z.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:z.Optional(z.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:z.Optional(z.Union([z.Literal(`llm`),z.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function la(e,n){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:ca,async execute(r,i){let a=ua(i.limit),o=i.summary_mode??`llm`,s=i.query?.trim(),c=i.role_filter;if(!s){let t=await da(e,a,n),r={mode:`recent`,count:t.length,results:t};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let l=await fa({dataDir:e,query:s,roleFilter:c,messageLimit:50,sessionLimit:a,currentSessionId:n?.sessionId,sessionStoreName:n?.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=Ta(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(!n?.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 wn({entries:Sa(xa(await t(e,r.sessionId,{storeName:n?.sessionStoreName})),s,1e5),llm:n.llm,instructions:wa({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 ua(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function da(e,t,n){let r=await M(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await c(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function fa(e){let t=e.messageLimit??50,n=(await M(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=ga(e.query),i=(await Ea(n,6,async t=>pa({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(ba).slice(0,t);if(i.length===0)return[];let a=new Map;for(let e of i){let t=a.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),a.set(e.sessionId,t)}let o=Array.from(a.values());for(let t of o){let n=await c(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return o.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),o.slice(0,e.sessionLimit)}async function pa(e){let t=a(e.dataDir,e.sessionId,{storeName:e.storeName});if(!V.existsSync(t))return[];let n=[],r=V.createReadStream(t,{encoding:`utf-8`}),i=He.createInterface({input:r,crlfDelay:1/0});try{for await(let t of i){let r=t.trim();if(!r||!ma(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!ha(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=va(i.content,e.terms,i.role);if(a<=0)continue;let o=ya(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(ba),n.length=20)}}finally{i.close(),r.destroy()}return n.sort(ba),n}function ma(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function ha(e){return e===`user`||e===`assistant`||e===`tool_result`}function ga(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=>_a(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 _a(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 va(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 ya(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function ba(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function xa(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function Sa(e,t,n){if(e.length===0)return e;let r=ga(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 Ca(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 Ca(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 wa(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 Ta(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 Ea(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 Da=z.Object({category:z.Optional(z.String({description:`Reserved category filter field. Not used yet.`}))}),Oa=z.Object({name:z.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:z.Optional(z.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function ka(e,t,n=[]){return[...n,...t,nt(e)]}function Aa(e,t,n=[]){let r=ka(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Da,async execute(e,t){let n=await ct(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 ja(e){let t=ka(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:Oa,async execute(r,i){let a=await dt(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 Ma=z.Object({task:z.String({description:`The task description for the subagent to execute`}),label:z.Optional(z.String({description:`Optional short label to identify this subagent`}))});function Na(e){let t=e.label?`"${e.label}"`:`task: ${ge(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${e.result??`(no output)`}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function Pa(e,t,n,r,i,a,o,s,c){return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. 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. Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:Ma,async execute(l,u){let d=u.task.trim(),f=u.label?.trim();if(!d){let e={status:`error`,error:`task must not be empty`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let p=e.checkSpawnAllowed(t,n+1);if(!p.allowed){let e={status:`forbidden`,error:p.reason};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=Le(),h=new AbortController,g;try{g=await T(r,i,{storeName:s.sessionStoreName})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}let _={runId:m,childSessionId:g,parentSessionId:t,task:d,label:f,depth:n+1,status:`running`,startedAt:Date.now(),abortController:h};await s.onProgress?.({type:`subagent_spawn`,childSessionId:g,task:d,label:f,sessionId:t,messageId:s.messageId,depth:n+1});let v=c({dataDir:r,sessionId:g,message:d,channel:i,llm:a,...s,loopDetection:o,abortSignal:h.signal,subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(m,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(m,n)});e.register(_,v),await v,e.markAnnounced(m),await s.onProgress?.({type:`subagent_complete`,childSessionId:g,task:d,status:_.status,sessionId:t,messageId:s.messageId,depth:n+1});let y=Na({task:d,label:f,status:_.status,result:_.result,error:_.error});if(_.status===`done`){let e={status:`done`,childSessionId:g,runId:m,result:_.result??``};return{content:[{type:`text`,text:y}],details:e}}let b=_.status===`killed`?{status:`killed`,childSessionId:g,runId:m,error:`subagent killed`}:{status:`error`,childSessionId:g,runId:m,error:_.error??`unknown error`};return{content:[{type:`text`,text:y}],details:b}}}}const Fa=z.Object({action:z.Union([`list`,`kill`].map(e=>z.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:z.Optional(z.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Ia(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 La(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 Ra(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:Fa,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} (${Ia(e.runtimeMs)})${n}`})).join(`
70
- `)};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=La(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 za=z.Object({image:z.String({description:`Image path or URL`}),prompt:z.Optional(z.String({description:`Prompt for image analysis`})),model:z.Optional(z.String({description:`Optional model override`})),maxBytesMb:z.Optional(z.Number({description:`Optional size cap in MB`}))});function Ba(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:za,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 Va=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 Ha(e){return!!(e instanceof Va||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Ua=new Ue;function Wa(){return{}}async function Ga(e,t){return await Ua.run(e,t)}function Ka(e){let t=Ua.getStore();!t||t.signal||(t.signal=e)}const qa=z.Object({reason:z.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Ja(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??qa,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=ye(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 Va(e,i,t,e,o,s,n);throw Ka(r),r}}}function Ya(e,t){let n=R.join(e,`workspace`),r=t?.memoryOptions,i=ei(),a=[Vr({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Gr({registry:i,scopeKey:n}),oi(n,t?.contextManager),ci(n,t?.contextManager),ui(n,t?.contextManager),fi(n),vi(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),Vi(e,r),la(e,r),Ui(e,r),qi(e,r),ta(e,r),ra(e,r),aa(e,r),sa(e,r),Aa(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),ja({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return t&&a.push(Pa(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Ra(t.registry,t.parentSessionId)),a}const Xa={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`},Za=[`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 Qa(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:[...Za.filter(e=>t.has(e)),...n.filter(e=>!Za.includes(e)).sort()],displayName:t}}function $a(e){let{ordered:t,displayName:n}=Qa(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)??Xa[e];return i?`- ${t}: ${i}`:`- ${t}`}).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 Ia=H.Object({id:H.Optional(H.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:H.Optional(H.String({description:`Search query used to find memories to delete`})),limit:H.Optional(H.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:H.Optional(H.Union([H.Literal(`long-term`),H.Literal(`recent`),H.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function La(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:Ia,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Aa(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Da(await fa(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 Z(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 ma(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=Da(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 Z(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 ma(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=Oa(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 Z(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 _a(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 pa(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await _a(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 Ra=H.Object({id:H.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:H.String({description:`New content to replace the existing memory with`})});function za(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:Ra,async execute(n,r){try{let n=Aa(r.id);if(n.section){let i=Ea(await fa(e)??``,n.section,r.content);return await Z(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 ma(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=ka(i.join(`
69
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Z(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 Z(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 Ba=H.Object({query:H.Optional(H.String({description:`Search query; omit to browse recent sessions.`})),role_filter:H.Optional(H.Union([H.Literal(`user`),H.Literal(`assistant`),H.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:H.Optional(H.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:H.Optional(H.Union([H.Literal(`llm`),H.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Va(e,n){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:Ba,async execute(r,i){let a=Ha(i.limit),o=i.summary_mode??`llm`,s=i.query?.trim(),c=i.role_filter;if(!s){let t=await Ua(e,a,n),r={mode:`recent`,count:t.length,results:t};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let l=await Wa({dataDir:e,query:s,roleFilter:c,messageLimit:50,sessionLimit:a,currentSessionId:n?.sessionId,sessionStoreName:n?.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=ro(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(!n?.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 tr({entries:eo($a(await t(e,r.sessionId,{storeName:n?.sessionStoreName})),s,1e5),llm:n.llm,instructions:no({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 Ha(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Ua(e,t,n){let r=await j(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await c(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function Wa(e){let t=e.messageLimit??50,n=(await j(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Ja(e.query),i=(await io(n,6,async t=>Ga({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Qa).slice(0,t);if(i.length===0)return[];let a=new Map;for(let e of i){let t=a.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),a.set(e.sessionId,t)}let o=Array.from(a.values());for(let t of o){let n=await c(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return o.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),o.slice(0,e.sessionLimit)}async function Ga(e){let t=a(e.dataDir,e.sessionId,{storeName:e.storeName});if(!V.existsSync(t))return[];let n=[],r=V.createReadStream(t,{encoding:`utf-8`}),i=He.createInterface({input:r,crlfDelay:1/0});try{for await(let t of i){let r=t.trim();if(!r||!Ka(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!qa(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Xa(i.content,e.terms,i.role);if(a<=0)continue;let o=Za(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(Qa),n.length=20)}}finally{i.close(),r.destroy()}return n.sort(Qa),n}function Ka(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function qa(e){return e===`user`||e===`assistant`||e===`tool_result`}function Ja(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=>Ya(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 Ya(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 Xa(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 Za(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Qa(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function $a(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function eo(e,t,n){if(e.length===0)return e;let r=Ja(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 to(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 to(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 no(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(`
70
+ `)}function ro(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(`
71
+ `)}`}async function io(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 ao=H.Object({category:H.Optional(H.String({description:`Reserved category filter field. Not used yet.`}))}),oo=H.Object({name:H.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:H.Optional(H.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function so(e,t,n=[]){return[...n,...t,rt(e)]}function co(e,t,n=[]){let r=so(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:ao,async execute(e,t){let n=await lt(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 lo(e){let t=so(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:oo,async execute(r,i){let a=await ft(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 uo=H.Object({task:H.String({description:`The task description for the subagent to execute`}),label:H.Optional(H.String({description:`Optional short label to identify this subagent`})),agent:H.Optional(H.String({description:`Optional custom agent name to use for this subagent`}))});function fo(e){let t=e.label?`"${e.label}"`:`task: ${me(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${po(e.result??`(no output)`)}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function po(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}function mo(e,t,n,r,i,a,o,s,c){return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. 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. Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:uo,async execute(l,u){let d=u.task.trim(),f=u.label?.trim(),p=u.agent?.trim();if(U.info(`subagent spawn requested`,{parentSessionId:t,depth:n+1,label:f,requestedAgentName:p,taskLength:d.length,taskPreview:Ht(d)}),!d){let e={status:`error`,error:`task must not be empty`};return U.warn(`subagent spawn rejected`,{parentSessionId:t,depth:n+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let m=e.checkSpawnAllowed(t,n+1);if(!m.allowed){let e={status:`forbidden`,error:m.reason};return U.warn(`subagent spawn rejected`,{parentSessionId:t,depth:n+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let h=Le(),g=new AbortController,_,v=bt(s.agentPolicy?.availableAgents??[],p);if(p&&!v){let e={status:`error`,error:`Unknown custom agent: ${p}`};return U.warn(`subagent spawn rejected`,{parentSessionId:t,depth:n+1,requestedAgentName:p,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}try{_=await T(r,i,{storeName:s.sessionStoreName})}catch(e){let r={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return U.error(`subagent session creation failed`,{parentSessionId:t,depth:n+1,error:r.error}),{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}U.info(`subagent session created`,{parentSessionId:t,childSessionId:_,depth:n+1,runId:h,requestedAgentName:p,selectedAgent:v?.name});let y={runId:h,childSessionId:_,parentSessionId:t,task:d,label:f,depth:n+1,status:`running`,startedAt:Date.now(),abortController:g};await s.onProgress?.({type:`subagent_spawn`,childSessionId:_,task:d,label:f,sessionId:t,messageId:s.messageId,depth:n+1});let b=c({dataDir:r,sessionId:_,message:v?wt(v,d):d,channel:i,llm:v?.model?{...a,model:v.model}:a,...s,agentPolicy:{availableAgents:s.agentPolicy?.availableAgents??[],...v?{activeAgent:v}:{}},loopDetection:o,abortSignal:g.signal,subagentContext:{depth:n+1,parentSessionId:t}}).then(t=>{e.complete(h,t.text||t.error||`(no output)`)}).catch(t=>{let n=t instanceof Error?t.message:String(t);e.fail(h,n)});e.register(y,b),U.info(`subagent run registered`,{runId:h,parentSessionId:t,childSessionId:_,depth:n+1,selectedAgent:v?.name}),await b,U.info(`subagent run settled`,{runId:h,parentSessionId:t,childSessionId:_,status:y.status,durationMs:y.endedAt?y.endedAt-y.startedAt:void 0,hasError:!!y.error}),e.markAnnounced(h),await s.onProgress?.({type:`subagent_complete`,childSessionId:_,task:d,status:y.status,sessionId:t,messageId:s.messageId,depth:n+1});let x=fo({task:d,label:f,status:y.status,result:y.result,error:y.error});if(y.status===`done`){let e={status:`done`,childSessionId:_,runId:h,result:y.result??``};return U.info(`subagent spawn completed`,{runId:h,parentSessionId:t,childSessionId:_,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:x}],details:e}}let S=y.status===`killed`?{status:`killed`,childSessionId:_,runId:h,error:`subagent killed`}:{status:`error`,childSessionId:_,runId:h,error:y.error??`unknown error`};return U.warn(`subagent spawn completed with non-success status`,{runId:h,parentSessionId:t,childSessionId:_,status:S.status,error:S.error}),{content:[{type:`text`,text:x}],details:S}}}}const ho=H.Object({action:H.Union([`list`,`kill`].map(e=>H.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:H.Optional(H.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function go(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 _o(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 vo(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:ho,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} (${go(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=_o(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 yo=H.Object({image:H.String({description:`Image path or URL`}),prompt:H.Optional(H.String({description:`Prompt for image analysis`})),model:H.Optional(H.String({description:`Optional model override`})),maxBytesMb:H.Optional(H.Number({description:`Optional size cap in MB`}))});function bo(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:yo,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 xo=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 So(e){return!!(e instanceof xo||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Co=new Ue;function wo(){return{}}async function To(e,t){return await Co.run(e,t)}function Eo(e){let t=Co.getStore();!t||t.signal||(t.signal=e)}const Do=H.Object({reason:H.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Oo(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??Do,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=_e(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 xo(e,i,t,e,o,s,n);throw Eo(r),r}}}function ko(e,t){let n=B.join(e,`workspace`),r=t?.memoryOptions,i=ji(),a=[vi({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Si({registry:i,scopeKey:n}),Li(n,t?.contextManager),zi(n,t?.contextManager),Vi(n,t?.contextManager),Ui(n),Yi(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume}),ya(e,r),Va(e,r),xa(e,r),Ta(e,r),Na(e,r),Fa(e,r),La(e,r),za(e,r),co(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),lo({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return t&&a.push(mo(t.registry,t.parentSessionId,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),vo(t.registry,t.parentSessionId)),a}const Ao={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 Mo(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 No(e){let{ordered:t,displayName:n}=Mo(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)??Ao[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
71
73
  `),``].join(`
72
- `)}function eo(){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(`
73
- `)}function to(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(`
74
- `)}function no(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(`
74
+ `)}function Po(){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 Fo(){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 Io(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 Lo(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(`
75
78
  `)).join(`
76
79
  `)}\n</available_skills>`,``].join(`
77
- `)}function ro(){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(`
78
- `)}function io(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: add or replace structured long-term memory (omit section for flat append).`,`- memory_log: append a daily or session note.`,`- 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(`
79
- `)}function ao(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` / `memory_log`, not `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(`
80
- `)}function oo(e){let t=`${e.dataDir}/.aimax`,n=`${e.dataDir}/workspace`,r=e.sandboxInfo?.hostWorkspaceDir?.trim()||n,i=e.sandboxInfo?.containerWorkspaceDir?.trim(),a=e.sandboxInfo?.enabled&&i?`For file tools, paths resolve against the cloud workspace mount ${r}. For exec commands, use paths under ${i} (or relative paths from there). Prefer relative paths whenever possible.`:`This cloud workspace is mounted user storage. Prefer relative paths to keep file tools and shell commands aligned.`;return[`## Workspace`,`Your cloud working directory is: ${r}`,a,`User identity, memory, and agent state live under ${t}, not inside the cloud workspace.`,`Files such as AGENTS.md, SOUL.md, TOOLS.md, IDENTITY.md, USER.md, 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(`
81
- `)}function so(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(`
82
- `)}function co(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=lo(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
83
- `)}function lo(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 uo(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(`
84
- `)}function fo(e){if(!e)return``;let t=[e.hostname?`host=${e.hostname}`:``,e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
85
- `)}function po(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(`
86
- `)}function mo(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(`
87
- `)}function ho(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(`
88
- `):``}function go(e){let t=e.promptMode??`full`,n=t===`minimal`,r=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:[...Za],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,$a({toolNames:i,toolSummaries:e.toolSummaries}),to(n),eo(),no(a),ro(),io(),ao(e.memoryCitationsMode??`off`),oo({dataDir:e.dataDir,sandboxInfo:e.sandboxInfo}),so(e.sandboxInfo),co({currentDate:e.currentDate,timezone:e.timezone}),uo({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),po({isMinimal:n}),fo(e.runtimeInfo),mo({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),ho(e.priorConversationSummary)].filter(Boolean).join(`
89
- `)}const _o=new Ue;async function vo(e,t){return await _o.run(e,t)}function yo(e){return{async emit(t){let n=_o.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 bo=Symbol(`pluginToolOwner`);var xo=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,bo,{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=Ja({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,bo,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function So(e){return e[bo]}const Co=new Ue;function wo(){return{}}async function To(e,t){return await Co.run(e,t)}function Eo(e){let t=Co.getStore();!t||t.signal||(t.signal=e)}function Do(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=So(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await vo({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(q(e))return Eo(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(q(i)){Eo(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 Oo=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 vo({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 ko(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Ao(e){let t=ko(e?.warningThreshold,$.warningThreshold),n=ko(e?.criticalThreshold,$.criticalThreshold),r=ko(e?.globalCircuitBreakerThreshold,$.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??$.enabled,historySize:ko(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 jo(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Mo(e,t){return`${e}:${Fo(t)}`}function No(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(No).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${No(t[e])}`).join(`,`)}}`}function Po(e){try{return No(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 Fo(e){let t=Po(e);return Ie(`sha256`).update(t).digest(`hex`)}function Io(e,t){if(e===`command_status`)return!0;if(e!==`process`||!jo(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Lo(e){return!jo(e)||!Array.isArray(e.content)?``:e.content.filter(e=>jo(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
90
- `).trim()}function Ro(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:No(e)}function zo(e,t,n,r){if(r!==void 0)return`error:${Fo(Ro(r))}`;if(!jo(n))return n===void 0?void 0:Fo(n);let i=jo(n.details)?n.details:{},a=Lo(n);if(Io(e,t)&&e===`process`&&jo(t)){let e=t.action;if(e===`poll`)return Fo({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Fo({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 Fo({details:i,text:a})}function Bo(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 Vo(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 Ho(e,t){return[e,t].toSorted().join(`|`)}function Uo(e,t,n,r){let i=Ao(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Mo(t,n),s=Bo(a,t,o),c=s.count,l=Io(t,n),u=Vo(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:${Ho(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 Wo(e,t,n,r,i){let a=Ao(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Mo(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Go(e,t){let n=Ao(t.config),r=zo(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Mo(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 Ko(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 qo(e){return e&&e.trim()||`tool`}function Jo(e,t,n){if(!e.execute)return e;let r=qo(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Uo(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ko(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Wo(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Go(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Go(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Yo(e,t,n){return e.map(e=>Jo(e,t,n))}async function Xo(e){let{session:{runParams:n,sessionId:r,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:s},runtimeInputs:{contextFiles:c,bootstrapWarnings:l,skills:u,effectivePromptText:d,pluginTools:f,pluginSkillDirs:p,skillsLoadPaths:m,presetSystemPrompt:h},dependencies:{registry:g,spawnFn:_,createModel:v,abortSignal:y}}=e,b=n.channel===`CRON`,x=b?[]:await t(n.dataDir,r,{storeName:n.sessionStoreName}),S={model:n.llm.model,api:`openai-completions`},C=await kr({dataDir:n.dataDir,sessionId:r,sessionStoreName:n.sessionStoreName}),w=b?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Ar({entries:x,modelInfo:S,contextWindowTokens:n.llm.contextWindow??2e5,llm:{baseUrl:n.llm.baseUrl,apiKey:n.llm.apiKey,model:n.llm.model},historyLimit:n.historyLimit,compactionEnabled:!0,pendingUserMessage:d,signal:y,hooks:i,hookCtx:a,contextManager:C,dataDir:n.dataDir,sessionId:r});await Qo({sessionId:r,historyResult:w,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let T=n.subagentContext?.depth??0,E=[...Ya(n.dataDir,{sessionId:n.subagentContext?.parentSessionId??r,registry:g,parentSessionId:r,depth:T,channel:n.channel,llm:n.llm,inheritedRunParams:{sessionStoreName:n.sessionStoreName,plugins:n.plugins,skillsLoadPaths:m,memory:n.memory,messaging:n.messaging,historyLimit:n.historyLimit,onProgress:n.onProgress,messageId:n.messageId},loopDetection:n.loopDetection,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:r,sessionStoreName:n.sessionStoreName,llm:{baseUrl:n.llm.baseUrl,apiKey:n.llm.apiKey,model:n.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:p,skillsLoadPaths:m,reportSkillUsed:async e=>{await s.dispatchProgress(r,e)},contextManager:C,hitlResume:n.hitlResume,spawnFn:_}),...f],D=E.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),O={};for(let e of E){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||O[t]||(O[t]=n)}let k=n.messaging?.enabled??n.channel!==`CRON`,A=n.messaging?.channels&&n.messaging.channels.length>0?n.messaging.channels:[n.channel],j=go({dataDir:n.dataDir,skills:u,contextFiles:c,toolNames:D,toolSummaries:O,promptMode:T>0?`minimal`:`full`,bootstrapWarnings:l,memoryCitationsMode:n.memory?.citationsMode??`off`,messaging:{enabled:k,channels:A},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:n.llm.model,hostname:ze.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:h,priorConversationSummary:w.priorSummary});j=await Zo({systemPrompt:j,dataDir:n.dataDir,sessionId:r,sessionStoreName:n.sessionStoreName});let M=await i.dispatch(`before_prompt_build`,{prompt:d},a,{eventDispatcher:s});for(let e of M)e&&(e.systemPrompt&&(j=e.systemPrompt),e.prependContext&&(j=`${e.prependContext}\n\n${j}`));await i.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:j},a,{eventDispatcher:s});let N=Yo(Do(E,i,a,{eventDispatcher:s}),{sessionId:r,config:n.loopDetection},_t),P=n.llm.model,F=await i.dispatch(`before_model_resolve`,{prompt:d},a,{eventDispatcher:s});for(let e of F)e&&e.modelOverride&&(P=e.modelOverride);let I=v({...n.llm,model:P},r,n.messageId,n.channel),ee=new Re({initialState:{systemPrompt:j,model:I,tools:N,messages:[]},getApiKey:e=>n.llm.apiKey});return w.messages.length>0&&ee.replaceMessages(w.messages),{agent:ee,resolvedModelId:P,historyMessages:w.messages,historyResult:w,contextManager:C,usageBaselineTranscriptEntryCount:x.length,workspaceDir:o.workspaceDir}}async function Zo(e){if((await f(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})).length<=8)return e.systemPrompt;let t=`Older CRON execution records for this session are stored outside the main transcript at ${S(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 Qo(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=$o(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 $o(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(`
91
-
92
- `):void 0}}async function es(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,onTurnRecordProduced:d}=e,f=``,p=``,m=``,h=0,g=0,_,v,y=0,b=0,x=[],S=new Map,C=new Set,w=!1,T=``,E=wo(),D=Wa(),O=t.subscribe(async e=>{let n=()=>!!D.signal||E.signal?.transparentPause===!0||w;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(b===0&&(t.type===`text_delta`||t.type===`done`)&&(b=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=cs(`partial`in t?t.partial:void 0)??cs(`message`in t?t.message:void 0)??cs(`message`in e?e.message:void 0),a=ls(t.delta,r,p);r?(p=r,m=r):a&&(m+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){f=``,p=``,m=``,e.usage&&(h=e.usage.input,g=e.usage.output);return}f=ss(e);let r=ls(``,f,m||p);p=f,m=f,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(h=e.usage.input,g=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(h=t.usage.input,g=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=ss(e);await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:y>0?Math.max(0,Date.now()-y):void 0,usage:t.usage?{input:h,output:g,total:h+g}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(v=t.errorMessage??(t.stopReason===`aborted`?`aborted`:`Unknown LLM error`));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:as(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),r=n.find(e=>e.toolName===`subagent_spawn`);if(r&&(w=!0,T=r.content),x.push({message:t,toolResults:n}),d){let e=!!E.signal,r=!!D.signal;if(!(e&&E.signal.transparentPause)){let i=ns(ts(t),e||r);await d(is(i,w)?null:i,r?[]:n.map(rs))}if(e||r)return}return}if(e.type===`tool_execution_start`){m=``,S.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=S.get(e.toolCallId);if(S.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){C.has(e.toolCallId)||(C.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:r}));return}C.has(e.toolCallId)||(C.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:r})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:r,output:n,isError:e.isError}),e.toolName===`subagent_spawn`&&(w=!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`);y=Date.now(),await To(E,async()=>{await Ga(D,async()=>{r?await t.continue():await t.prompt(n)})});let e=E.signal;if(e)throw e;let d=D.signal;if(d)throw d;if(!_){let e=typeof t.state.error==`string`?t.state.error:void 0,n=v??e;n&&(_=us(n),await s.dispatchProgress(i,{type:`error`,message:_}))}}catch(e){if(q(e)||Ha(e))throw e;_=us(e),await s.dispatchProgress(i,{type:`error`,message:_})}finally{O()}let k=x.length>0?x[x.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:f?[f]:[],lastAssistant:k,durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:{input:h,output:g,total:h+g}},l);let A=D.signal?``:x.length>0?ss(x[x.length-1].message):``,j=T||(w?``:A||f);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return d&&x.length===0&&!w&&f.trim().length>0&&await d({role:`assistant`,content:f,timestamp:new Date().toISOString()},[]),{text:j,inputTokens:h,outputTokens:g,error:_,turnRecords:x}}function ts(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 ns(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function rs(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 is(e,t){return!e||e.toolCalls&&e.toolCalls.length>0?!1:t}function as(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:os(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function os(e){let t=e.indexOf(`
80
+ `)}function Ro(){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 zo(){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 Bo(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 Vo(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 Ho(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 Uo(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Wo(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
86
+ `)}function Wo(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 Go(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 Ko(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 qo(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 Jo(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 Yo(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(`
91
+ `):``}function Xo(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`,No({toolNames:i,toolSummaries:e.toolSummaries}),Io(n),Po(),Ct(e.availableAgents??[]),Lo(a),Ro(),zo(),Bo(e.memoryCitationsMode??`off`),Vo({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Ho(e.sandboxInfo),Uo({currentDate:e.currentDate,timezone:e.timezone}),Fo(),Go({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),qo({isMinimal:n}),Ko(e.runtimeInfo),Jo({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Yo(e.priorConversationSummary)].filter(Boolean).join(`
92
+ `)}const Zo=new Ue;async function Qo(e,t){return await Zo.run(e,t)}function $o(e){return{async emit(t){let n=Zo.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 es=Symbol(`pluginToolOwner`);var ts=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,es,{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=Oo({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,es,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function ns(e){return e[es]}const rs=new Ue;function is(){return{}}async function as(e,t){return await rs.run(e,t)}function os(e){let t=rs.getStore();!t||t.signal||(t.signal=e)}function ss(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=ns(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Qo({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(q(e))return os(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(q(i)){os(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 cs=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 Qo({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};const Q={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function ls(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function us(e){let t=ls(e?.warningThreshold,Q.warningThreshold),n=ls(e?.criticalThreshold,Q.criticalThreshold),r=ls(e?.globalCircuitBreakerThreshold,Q.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Q.enabled,historySize:ls(e?.historySize,Q.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Q.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Q.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Q.detectors.pingPong}}}function $(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ds(e,t){return`${e}:${ms(t)}`}function fs(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(fs).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${fs(t[e])}`).join(`,`)}}`}function ps(e){try{return fs(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 ms(e){let t=ps(e);return Ie(`sha256`).update(t).digest(`hex`)}function hs(e,t){if(e===`command_status`)return!0;if(e!==`process`||!$(t))return!1;let n=t.action;return n===`poll`||n===`log`}function gs(e){return!$(e)||!Array.isArray(e.content)?``:e.content.filter(e=>$(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
93
+ `).trim()}function _s(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:fs(e)}function vs(e,t,n,r){if(r!==void 0)return`error:${ms(_s(r))}`;if(!$(n))return n===void 0?void 0:ms(n);let i=$(n.details)?n.details:{},a=gs(n);if(hs(e,t)&&e===`process`&&$(t)){let e=t.action;if(e===`poll`)return ms({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return ms({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 ms({details:i,text:a})}function ys(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 bs(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 xs(e,t){return[e,t].toSorted().join(`|`)}function Ss(e,t,n,r){let i=us(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=ds(t,n),s=ys(a,t,o),c=s.count,l=hs(t,n),u=bs(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:${xs(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 Cs(e,t,n,r,i){let a=us(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:ds(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function ws(e,t){let n=us(t.config),r=vs(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=ds(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 Ts(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 Es(e){return e&&e.trim()||`tool`}function Ds(e,t,n){if(!e.execute)return e;let r=Es(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Ss(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ts(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Cs(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return ws(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw ws(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Os(e,t,n){return e.map(e=>Ds(e,t,n))}async function ks(e){let{session:{runParams:n,sessionId:r,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:s},runtimeInputs:{contextFiles:c,bootstrapWarnings:l,skills:u,effectivePromptText:d,pluginTools:f,pluginSkillDirs:p,skillsLoadPaths:m,presetSystemPrompt:h},dependencies:{registry:g,spawnFn:_,createModel:v,abortSignal:y}}=e,b=n.agentPolicy?.activeAgent,x=n.channel===`CRON`,S=x?[]:await t(n.dataDir,r,{storeName:n.sessionStoreName}),C={model:n.llm.model,api:`openai-completions`},w=await oi({dataDir:n.dataDir,sessionId:r,sessionStoreName:n.sessionStoreName}),T=x?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await si({entries:S,modelInfo:C,contextWindowTokens:n.llm.contextWindow??2e5,llm:{baseUrl:n.llm.baseUrl,apiKey:n.llm.apiKey,model:n.llm.model},historyLimit:n.historyLimit,compactionEnabled:!0,pendingUserMessage:d,signal:y,hooks:i,hookCtx:a,contextManager:w,dataDir:n.dataDir,sessionId:r});await js({sessionId:r,historyResult:T,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let E=n.subagentContext?.depth??0,D=St([...ko(n.dataDir,{sessionId:n.subagentContext?.parentSessionId??r,registry:g,parentSessionId:r,depth:E,channel:n.channel,llm:n.llm,inheritedRunParams:{sessionStoreName:n.sessionStoreName,plugins:n.plugins,skillsLoadPaths:m,memory:n.memory,messaging:n.messaging,historyLimit:n.historyLimit,onProgress:n.onProgress,messageId:n.messageId,agentPolicy:n.agentPolicy},loopDetection:n.loopDetection,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:r,sessionStoreName:n.sessionStoreName,llm:{baseUrl:n.llm.baseUrl,apiKey:n.llm.apiKey,model:n.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:p,skillsLoadPaths:m,reportSkillUsed:async e=>{await s.dispatchProgress(r,e)},contextManager:w,hitlResume:n.hitlResume,spawnFn:_}),...f],b),O=D.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),k={};for(let e of D){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||k[t]||(k[t]=n)}let A=n.messaging?.enabled??n.channel!==`CRON`,ee=n.messaging?.channels&&n.messaging.channels.length>0?n.messaging.channels:[n.channel],j=Xo({dataDir:n.dataDir,projectDir:n.projectDir,skills:xt(u,b),contextFiles:c,toolNames:O,toolSummaries:k,promptMode:E>0?`minimal`:`full`,bootstrapWarnings:l,memoryCitationsMode:n.memory?.citationsMode??`off`,messaging:{enabled:A,channels:ee},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:n.llm.model,hostname:ze.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:h,activeAgentSystemPrompt:b?.systemPrompt,availableAgents:n.subagentContext?[]:n.agentPolicy?.availableAgents??[],priorConversationSummary:T.priorSummary});j=await As({systemPrompt:j,dataDir:n.dataDir,sessionId:r,sessionStoreName:n.sessionStoreName});let M=await i.dispatch(`before_prompt_build`,{prompt:d},a,{eventDispatcher:s});for(let e of M)e&&(e.systemPrompt&&(j=e.systemPrompt),e.prependContext&&(j=`${e.prependContext}\n\n${j}`));await i.dispatch(`after_prompt_build`,{prompt:d,systemPrompt:j},a,{eventDispatcher:s});let N=Os(ss(D,i,a,{eventDispatcher:s}),{sessionId:r,config:n.loopDetection},qt),P=b?.model??n.llm.model,F=await i.dispatch(`before_model_resolve`,{prompt:d},a,{eventDispatcher:s});for(let e of F)e&&e.modelOverride&&(P=e.modelOverride);let I=v({...n.llm,model:P},r,n.messageId,n.channel),L=new Re({initialState:{systemPrompt:j,model:I,tools:N,messages:[]},getApiKey:e=>n.llm.apiKey});return T.messages.length>0&&L.replaceMessages(T.messages),{agent:L,resolvedModelId:P,historyMessages:T.messages,historyResult:T,contextManager:w,usageBaselineTranscriptEntryCount:S.length,workspaceDir:o.workspaceDir}}async function As(e){if((await f(e.dataDir,e.sessionId,{storeName:e.sessionStoreName})).length<=8)return e.systemPrompt;let t=`Older CRON execution records for this session are stored outside the main transcript at ${S(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 js(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=Ms(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 Ms(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(`
94
+
95
+ `):void 0}}const Ns=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Ps=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]);function Fs(e){let t=zs(e?.maxAttempts,3),n=Bs(e?.initialDelayMs,250),r=Bs(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Is(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Ls(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 Rs(e){if(Hs(e))return!1;let t=Vs(e);if(t?.statusCode!==void 0)return Ws(t.statusCode);if(t?.providerCode!==void 0)return Us(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Ns.has(e))return!0;if(Ps.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 Bs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Vs(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 Hs(e){return Vs(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function Us(e){return/^\d+$/.test(e)?Ws(Number(e)):!1}function Ws(e){return e===408||e===409||e===425||e===429||e>=500}async function Gs(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=is(),D=wo(),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=cc(`partial`in t?t.partial:void 0)??cc(`message`in t?t.message:void 0)??cc(`message`in e?e.message:void 0),a=lc(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=oc(e);let r=lc(``,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=oc(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=Ys(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:ic(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(nc(tc(t),e||r),r?[]:n.map(rc)),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=sc(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:ic(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=Fs(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`);U.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 as(E,async()=>{await To(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=uc(x),U.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||U.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(),q(t)||So(t))throw t;if(v=uc(t),U.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(!Ks({error:e,attempt:r,maxAttempts:F,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=Is(r,P);return U.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:F,delayMs:o,error:n}),await Qs({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:F,message:n,delayMs:o}),S.length=a,I(),$s(t),await Ls(o,u),!0}let te=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:te,durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:{input:g,output:_,total:g+_}},l);let R=(D.signal?``:S.length>0?oc(S[S.length-1].message):``)||p||Js(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return f&&!qs(S)&&!v&&p.trim().length>0&&await f({role:`assistant`,content:p,timestamp:new Date().toISOString()},[]),{text:R,inputTokens:g,outputTokens:_,error:v,turnRecords:S}}function Ks(e){return e.attempt>=e.maxAttempts||!Rs(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&&oc(e.message).trim().length===0)}function qs(e){return e.some(e=>tc(e.message)!==null||e.toolResults.length>0)}function Js(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 Ys(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:Xs(t.errorCode),statusCode:Zs(t.statusCode),providerCode:Xs(t.providerCode),providerType:Xs(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function Xs(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Zs(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Qs(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 $s(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&ec(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function ec(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function tc(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 nc(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function rc(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 ic(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:ac(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function ac(e){let t=e.indexOf(`
93
96
  Preview:
94
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function ss(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function cs(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 ls(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function us(e){let t=ds(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 ds(e){if(e instanceof U)return e;if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function fs(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,appendEntry:l}=e,u=0,d=``,f=0,p=0,m;for(;!c?.aborted&&n.needsAnnounce(r)&&u<10;){u++,await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0)break;for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let h=ps(e);await l({role:`assistant`,content:h,timestamp:new Date().toISOString()});let g=await es({agent:t,message:h,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,onTurnRecordProduced:async(e,t)=>{e&&await l(e);for(let e of t)await l(e)}});d=g.text,f+=g.inputTokens,p+=g.outputTokens,g.error&&!m&&(m=g.error),n.markAnnounced(e.map(e=>e.runId))}return{text:d,inputTokens:f,outputTokens:p,error:m}}function ps(e){if(e.length===1){let t=e[0];return Na({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Na({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
97
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function oc(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function sc(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 cc(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 lc(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function uc(e){let t=dc(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 dc(e){if(e instanceof W)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:Xs(t.code),statusCode:Zs(t.statusCode),statusText:Xs(t.statusText),providerMessage:Xs(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 fc(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++,U.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){U.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}U.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=pc(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Gs({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?U.warn(`subagent announce round completed with error`,v):U.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&U.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function pc(e){if(e.length===1){let t=e[0];return fo({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>fo({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
95
98
 
96
99
  ---
97
100
 
98
- `)}`}function ms(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 hs(e){let t=ms(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=R.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 gs(e){let t=e.watchFactory??((e,t,n)=>V.watch(e,t,n)),n=R.join(e.dataDir,`.aimax`),r=[{target:R.join(n,`MEMORY.md`),kind:`memory-file`},{target:R.join(n,`memory.md`),kind:`memory-file-lower`},{target:R.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=hs({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 _s(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=R.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),o=bs(e.files);if(o.length===0)return;let s=e.reason===`external-watch`&&e.source===`memory`?o.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):o;if(s.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of s)l.set(e.toLowerCase(),t);let c=`${e.reason}|${e.source}|${s.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(c)??0)<1e3)return;u.set(c,t);let d={...e,files:s};await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:d.reason,files:d.files,source:d.source,providerId:d.providerId,timestamp:d.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,d,{...a,sessionId:d.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=R.join(t.dataDir,`.aimax`),m=N({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName})?.provider??C({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=gs({dataDir:t.dataDir,sessionId:i,providerId:o??s??m.id,provider:m,onMemoryChanged:f});m.sync&&m.sync(`session-start`).catch(()=>{});let g=async e=>{await O(t.dataDir,i,e,ys({sessionStoreName:t.sessionStoreName,providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:g,persistInitialUserEntry:async e=>d?!1:(await g({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{h()}}}function vs(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function ys(e){return e.sessionStoreName||e.providerId||e.pluginId?{storeName:e.sessionStoreName,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function bs(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 xs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ss(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Cs(){let e=ze.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function ws(e){let t=e.trim(),n=Cs();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?R.join(n,t.slice(2)):void 0:R.resolve(t)}const Ts=new We({allErrors:!0,strict:!1}),Es=new Map;function Ds(e,t){let n=Es.get(t);if(n)return n;let r=Ts.compile(e);return Es.set(t,r),r}function Os(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Ds(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function ks(e){let t=Ss(e?.allow),n=Ss(e?.deny),r=Ss(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 As(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=Os({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 js(e){try{return V.realpathSync(e)}catch{return null}}function Ms(e){try{return V.statSync(e)}catch{return null}}function Ns(e,t){let n=R.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!R.isAbsolute(n)}function Ps(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Fs=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Is=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Ls(e){let t=R.join(e,`package.json`);if(V.existsSync(t))try{let e=JSON.parse(V.readFileSync(t,`utf-8`));return xs(e)?e:void 0}catch{return}}function Rs(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 zs(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Bs(e){let t=js(e.source),n=js(e.rootDir);return!t||!n||Ns(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Vs(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=R.resolve(r);if(n.has(t))continue;n.add(t);let i=Ms(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 Hs(e){return Bs({source:e.source,rootDir:e.rootDir})||Vs({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:zs(e.ownershipUid)})}function Us(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=${Ps(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Ws(e){let t=Hs({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Us(t),source:e.source}),!0):!1}function Gs(e){return R.basename(e,R.extname(e))}function Ks(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 qs(e){for(let t of Is){let n=R.join(e,t);if(V.existsSync(n))return n}return null}function Js(e){let t;try{t=V.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=R.join(e.rootDir,n.name);if(n.isFile()){if(!Fs.has(R.extname(n.name)))continue;let r=R.dirname(t);if(Ws({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Ks({idHint:Gs(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Ls(t),i=Rs(r);if(i.status===`ok`){for(let n of i.entries){let i=R.resolve(t,n);if(!Ns(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!V.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Fs.has(R.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Ws({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Gs(i)}`:Gs(i);e.candidates.push(Ks({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=qs(t);a&&(Ws({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Ks({idHint:R.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Ys(e){return e?e.map(ws).filter(e=>typeof e==`string`&&e.length>0):[]}function Xs(){let e=Cs();if(e)return R.join(e,`.aimax`,`extensions`)}function Zs(e){return R.join(e,`.aimax`,`extensions`)}function Qs(e){return R.join(e,`.aimax`,`extensions`)}function $s(e={}){let t=[],n=[],r=Ys(e.extraPaths);for(let i of r){if(!V.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Ms(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Fs.has(R.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=R.dirname(i);if(Ws({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Ks({idHint:Gs(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Js({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Js({rootDir:Zs(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Js({rootDir:Qs(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Xs();return i?Js({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&&Js({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function ec(e){let t=e.rejectHardlinks??!0,n=js(e.rootPath),r=js(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!Ns(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=V.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:V.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const tc=`aimax.plugin.json`,nc=[tc];function rc(e){for(let t of nc){let n=R.join(e,t);if(V.existsSync(n))return n}return R.join(e,tc)}function ic(e,t=!0){let n=rc(e),r=ec({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(V.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{V.closeSync(r.fd)}if(!xs(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=xs(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=Ss(i.skills),f;return xs(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 ac(e){let t=new Map,n=[];for(let r of e){let e=ic(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 oc=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function sc(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)} ${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function cc(e,t,n,r){process.stderr.write(`[${sc()}] [${e}] [plugin:${t}][logger:${n}] ${r}\n`)}function lc(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>cc(oc.INFO,e.pluginId,t,n),warn:n=>cc(oc.WARN,e.pluginId,t,n),error:n=>cc(oc.ERROR,e.pluginId,t,n)})}}}function uc(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 dc(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 fc(e){let t=[...e.registry.diagnostics],n=new xo,r=new Oo,i=[],a=[],o=e.runtime?.llm?yt({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=pc(e.runtime?.llmAllowlist),c=Ge(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=uc({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=dc({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=lc({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(!mc(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`);v({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`);P({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=R.isAbsolute(e)?e:R.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>yo(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=R.isAbsolute(e)?e:R.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function pc(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function mc(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function hc(e={}){let t=ks(e.config),n=$s({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=ac(n.candidates),i=As({config:t,registry:r}),a=fc({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 gc(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?hc({...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 Oo,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 _c(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=R.join(t.dataDir,`workspace`),a=n,o=!a;a?(await b(t.dataDir,a,{storeName:t.sessionStoreName})||(o=!0),await _(t.dataDir,a,{storeName:t.sessionStoreName})):a=await T(t.dataDir,t.channel,{storeName:t.sessionStoreName});let s={sessionId:a,workspaceDir:i,channel:t.channel},c=gc({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),l=c.hookRegistry,u=await _s({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:l});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:l,pluginContext:c,runContext:u,start:e=>en({sessionId:a,runParams:t,hookRegistry:l,hookContext:s,eventDispatcher:r,...e})}}function vc(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function yc(e){if(!(e instanceof Error))return{errorValue:vc(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]=vc(n[e]));return t}async function bc(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...yc(e.error)}})}function xc(e,t,n){return R.join(o(e,t,n),`pending-hitl.json`)}function Sc(e,t,n){return R.join(o(e,t,n),`hitl-history.jsonl`)}async function Cc(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0});let a=xc(e,t,r);await L.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function wc(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0});let a=Sc(e,t,r),s=JSON.stringify(n)+`
99
- `;await L.appendFile(a,s,`utf-8`)}async function Tc(e,t,n){let r=xc(e,t,n);try{let e=await L.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ec(e,t,n){let r=Sc(e,t,n);try{let e=await L.readFile(r,`utf-8`),t=[];for(let n of e.split(`
100
- `)){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 Dc(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 Cc(e,t,c,o),await wc(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function Oc(e,t,n,r,i,a){let o=await Tc(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 Cc(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await wc(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function kc(e,t,n,r){let i=await Tc(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function Ac(e,t,n){let r=xc(e,t,n);try{await L.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function jc(e,t,n){return R.join(o(e,t,n),`pending-ui-tool.json`)}async function Mc(e,t,n,r){let i=o(e,t,r);await L.mkdir(i,{recursive:!0}),await L.writeFile(jc(e,t,r),JSON.stringify(n,null,2),`utf-8`)}async function Nc(e,t,n){try{let r=await L.readFile(jc(e,t,n),`utf-8`);return JSON.parse(r)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Pc(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Mc(e,t,a,r),a}async function Fc(e,t,n,r,i){let a=await Nc(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 Mc(e,t,o,i),o}async function Ic(e,t,n){try{await L.unlink(jc(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const Lc=`crons`;function Rc(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 zc(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!ve(t))}async function Bc(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=wo();if(i=await To(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(q(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Vc(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 Vc(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 Hc(e,t){Jt();let r=Date.now(),i=new Yt(e),a=Bn(e),o=a.transcriptMessage,s=!1,c=a.previousSessionId,l=await _c({runParams:e,requestedSessionId:a.requestedSessionId,eventDispatcher:i}),u=l.sessionId,d=l.isNewSession,f=l.workspaceDir,p=l.hookContext,m=l.hookRegistry,h=l.pluginContext,g=l.runContext;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:d,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:d?`session_created`:`session_resumed`,message:d?`session created`:`session resumed`,details:{requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}}),d&&await n(e.dataDir,vs({sessionId:u,title:$t(o),channel:e.channel}),{storeName:e.sessionStoreName}),a.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(s=await g.persistInitialUserEntry(o)),await l.start({resetCommand:a.resetCommand,previousSessionId:c,resetMessage:a.slashCommandSource,startMessage:typeof a.promptInput==`string`?a.promptInput:o});let _=new AbortController;e.abortSignal?.aborted?_.abort():e.abortSignal?.addEventListener(`abort`,()=>_.abort());let v=await Ye(e.dataDir),y=[],b=Qe(v,{warn:e=>y.push(e)}),x=await tt();await i.dispatchDiagnostic(u,{level:y.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:v.length,contextFileCount:b.length,warningCount:y.length}});let S=e.skillsLoadPaths??[],C=await st(e.dataDir,h.pluginSkillDirs,S);await i.dispatchDiagnostic(u,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:C.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:S.length,skills:C.map(e=>({name:e.name,description:e.description,location:e.location}))}});let w=e=>g.appendTranscriptEntry(e),T=await Hn({invocation:a,skills:C,sessionId:u,isNewSession:d,initialUserEntryPersisted:s,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i});if(T.kind===`completed`)return T.result;let E=T.effectivePrompt;o=T.transcriptMessage;let D=typeof E==`string`?E:o;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof E==`string`?`string`:`messages`,transcriptLength:o.length}});let O=await Xo({session:{runParams:e,sessionId:u,hookRegistry:m,hookContext:p,runContext:g,eventDispatcher:i},runtimeInputs:{contextFiles:b,bootstrapWarnings:y,skills:C,effectivePromptText:D,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:S,presetSystemPrompt:x.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>Hc(e,new ht),createModel:Rc,abortSignal:_.signal}}),k=O.agent,A=O.resolvedModelId;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:A,historyMessageCount:O.historyMessages.length,pluginToolCount:h.pluginTools.length}}),_.signal.addEventListener(`abort`,()=>k.abort());let j=0,M=0,N=``,P,F=!1;try{if(zc(e)){let t=await Bc({params:e,agent:k,sessionId:u,eventDispatcher:i,appendEntry:w,abortSignal:_.signal});return N=t.text,rn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(o);F=e,s=e||s}await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let n=await es({agent:k,message:E,continueFromHistory:!!e.uiToolResume,sessionId:u,modelId:A,historyMessages:O.historyMessages,eventDispatcher:i,hooks:m,hookCtx:p,abortSignal:_.signal,onTurnRecordProduced:async(e,t)=>{e&&await w(e);for(let e of t)await w(e)}});N=n.text,j+=n.inputTokens,M+=n.outputTokens,n.error&&(P=n.error),await i.dispatchDiagnostic(u,{level:n.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`});let a=await fs({agent:k,registry:t,sessionId:u,resolvedModelId:A,eventDispatcher:i,hookRegistry:m,hookContext:p,abortSignal:_.signal,appendEntry:w});a.text&&(N=a.text),j+=a.inputTokens,M+=a.outputTokens,a.error&&!P&&(P=a.error),await i.dispatchDiagnostic(u,{level:a.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!a.error,error:a.error,inputTokens:a.inputTokens,outputTokens:a.outputTokens}})}catch(t){if(q(t)){let n=t,a=e.subagentContext?.parentSessionId??u,s=a===n.request.sessionId?n.request:{...n.request,sessionId:a};await Dc(e.dataDir,a,s,n.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},n.toolContext),await i.dispatchProgress(a,{type:`hitl_requested`,request:s}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${n.request.kind} — ${n.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:n.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}});let c={input:j,output:M,total:j+M};return await Uc({runtime:O,resolvedModelId:A,usage:c,currentUserEntryCoveredByUsage:F}),rn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N||`[HITL paused] ${n.request.title}: ${n.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Ha(t)){let n=t,a=n.request.outputSchema.properties??{};await Pc(e.dataDir,u,n.request,{storeName:e.sessionStoreName}),await i.dispatchProgress(u,{type:`ui_tool_request`,request:n.request}),await i.dispatchDiagnostic(u,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${n.request.toolName}`,details:{requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchemaTitle:n.request.outputSchema.title,propertyCount:Object.keys(a).length}});let s={input:j,output:M,total:j+M};return await Uc({runtime:O,resolvedModelId:A,usage:s,currentUserEntryCoveredByUsage:F}),rn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N||`[UI Tool] Waiting for user input: ${n.request.outputSchema.title}`,usage:s,error:void 0,uiToolPending:{requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchema:n.request.outputSchema,extra:n.request.extra}})}throw await bc({dispatcher:i,sessionId:u,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:d}}),t}finally{vt(u),g.stop()}let I={input:j,output:M,total:j+M};return await i.dispatchDiagnostic(u,{level:P?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-r,inputTokens:I.input,outputTokens:I.output,totalTokens:I.total,hasError:!!P,error:P}}),await Uc({runtime:O,resolvedModelId:A,usage:I,currentUserEntryCoveredByUsage:F}),rn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:N,usage:I,error:P})}async function Uc(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 Wc(e){let t=Date.now(),a=new Yt(e),o=Bn(e),c=o.transcriptMessage.trim()||`CRON task`,l=e.sessionStoreName,u=o.requestedSessionId,d=!u;u?(await b(e.dataDir,u,{storeName:l})||(d=!0),await _(e.dataDir,u,{storeName:l})):u=await T(e.dataDir,e.channel,{storeName:l}),d&&await n(e.dataDir,vs({sessionId:u,title:$t(c),channel:e.channel}),{storeName:l});let f=await T(e.dataDir,e.channel,{storeName:Lc});await a.dispatchProgress(u,{type:`subagent_spawn`,childSessionId:f,task:c});let p={...e,sessionId:f,sessionStoreName:Lc,subagentContext:{depth:1,parentSessionId:u}},m,g=`done`;try{m=await Hc(p,new ht),m.error&&(g=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);m={sessionId:f,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:h(e.dataDir,f,{storeName:Lc}),toolResultsDir:i(e.dataDir,f,{storeName:Lc})}},g=`error`}await a.dispatchProgress(u,{type:`subagent_complete`,childSessionId:f,task:c,status:g});let v=Na({task:c,status:g,result:m.text,error:m.error}),y=new Date().toISOString();await O(e.dataDir,u,{role:`assistant`,content:v,timestamp:y,source:`cron`},{storeName:l});let S={task:c,status:g,content:v,childSessionId:f,createdAt:y};return await x(e.dataDir,u,S,{storeName:l}),await r(e.dataDir,u,e=>Gc(e,8),{storeName:l}),await s(e.dataDir,u,{},{storeName:l}),{...m,sessionId:u,context:{snapshotPath:h(e.dataDir,u,{storeName:l}),toolResultsDir:i(e.dataDir,u,{storeName:l})}}}function Gc(e,t){if(t<=0)return e.filter(e=>!Kc(e));let n=e.reduce((e,t,n)=>(Kc(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Kc(e)||r.has(t))}function Kc(e){return`source`in e&&e.source===`cron`}async function qc(e,t){if(e.channel===`CRON`&&!e.subagentContext)return Wc(e);let n=t??new ht;try{return await Hc(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:yc(t)}),t}}const Jc={"AGENTS.md":`---
101
+ `)}`}function mc(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 hc(e){let t=mc(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=B.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 gc(e){let t=e.watchFactory??((e,t,n)=>V.watch(e,t,n)),n=B.join(e.dataDir,`.aimax`),r=[{target:B.join(n,`MEMORY.md`),kind:`memory-file`},{target:B.join(n,`memory.md`),kind:`memory-file-lower`},{target:B.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=hc({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 _c(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=B.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=bc(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=B.join(t.dataDir,`.aimax`),m=M({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=m?.provider??C({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=gc({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 O(t.dataDir,i,e,yc({sessionStoreName:t.sessionStoreName,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 vc(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function yc(e){return e.sessionStoreName||e.providerId||e.pluginId?{storeName:e.sessionStoreName,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function bc(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 xc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sc(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Cc(){let e=ze.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function wc(e){let t=e.trim(),n=Cc();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?B.join(n,t.slice(2)):void 0:B.resolve(t)}const Tc=new We({allErrors:!0,strict:!1}),Ec=new Map;function Dc(e,t){let n=Ec.get(t);if(n)return n;let r=Tc.compile(e);return Ec.set(t,r),r}function Oc(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Dc(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function kc(e){let t=Sc(e?.allow),n=Sc(e?.deny),r=Sc(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 Ac(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=Oc({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 jc(e){try{return V.realpathSync(e)}catch{return null}}function Mc(e){try{return V.statSync(e)}catch{return null}}function Nc(e,t){let n=B.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!B.isAbsolute(n)}function Pc(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Fc=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Ic=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Lc(e){let t=B.join(e,`package.json`);if(V.existsSync(t))try{let e=JSON.parse(V.readFileSync(t,`utf-8`));return xc(e)?e:void 0}catch{return}}function Rc(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 Bc(e){let t=jc(e.source),n=jc(e.rootDir);return!t||!n||Nc(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Vc(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=B.resolve(r);if(n.has(t))continue;n.add(t);let i=Mc(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 Hc(e){return Bc({source:e.source,rootDir:e.rootDir})||Vc({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:zc(e.ownershipUid)})}function Uc(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=${Pc(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Wc(e){let t=Hc({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Uc(t),source:e.source}),!0):!1}function Gc(e){return B.basename(e,B.extname(e))}function Kc(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 qc(e){for(let t of Ic){let n=B.join(e,t);if(V.existsSync(n))return n}return null}function Jc(e){let t;try{t=V.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=B.join(e.rootDir,n.name);if(n.isFile()){if(!Fc.has(B.extname(n.name)))continue;let r=B.dirname(t);if(Wc({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Kc({idHint:Gc(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Lc(t),i=Rc(r);if(i.status===`ok`){for(let n of i.entries){let i=B.resolve(t,n);if(!Nc(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!V.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Fc.has(B.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Wc({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Gc(i)}`:Gc(i);e.candidates.push(Kc({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=qc(t);a&&(Wc({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Kc({idHint:B.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Yc(e){return e?e.map(wc).filter(e=>typeof e==`string`&&e.length>0):[]}function Xc(){let e=Cc();if(e)return B.join(e,`.aimax`,`extensions`)}function Zc(e){return B.join(e,`.aimax`,`extensions`)}function Qc(e){return B.join(e,`.aimax`,`extensions`)}function $c(e={}){let t=[],n=[],r=Yc(e.extraPaths);for(let i of r){if(!V.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Mc(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Fc.has(B.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=B.dirname(i);if(Wc({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Kc({idHint:Gc(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Jc({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Jc({rootDir:Zc(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Jc({rootDir:Qc(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Xc();return i?Jc({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&&Jc({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function el(e){let t=e.rejectHardlinks??!0,n=jc(e.rootPath),r=jc(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!Nc(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=V.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:V.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const tl=`aimax.plugin.json`,nl=[tl];function rl(e){for(let t of nl){let n=B.join(e,t);if(V.existsSync(n))return n}return B.join(e,tl)}function il(e,t=!0){let n=rl(e),r=el({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(V.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{V.closeSync(r.fd)}if(!xc(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=xc(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=Sc(i.skills),f;return xc(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 al(e){let t=new Map,n=[];for(let r of e){let e=il(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 ol=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function sl(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===ol.ERROR){U.error(i);return}if(e===ol.WARN){U.warn(i);return}U.info(i)}function cl(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>sl(ol.INFO,e.pluginId,t,n),warn:n=>sl(ol.WARN,e.pluginId,t,n),error:n=>sl(ol.ERROR,e.pluginId,t,n)})}}}function ll(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 ul(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 dl(e){let t=[...e.registry.diagnostics],n=new ts,r=new cs,i=[],a=[],o=e.runtime?.llm?Yt({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=fl(e.runtime?.llmAllowlist),c=Ge(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=ll({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=ul({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=cl({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(!pl(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`);v({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`);N({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=B.isAbsolute(e)?e:B.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>$o(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=B.isAbsolute(e)?e:B.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function fl(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function pl(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function ml(e={}){let t=kc(e.config),n=$c({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=al(n.candidates),i=Ac({config:t,registry:r}),a=dl({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 hl(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?ml({...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 cs,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 gl(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=B.join(t.dataDir,`workspace`),a=n,o=!a;a?(await b(t.dataDir,a,{storeName:t.sessionStoreName})||(o=!0),await _(t.dataDir,a,{storeName:t.sessionStoreName})):a=await T(t.dataDir,t.channel,{storeName:t.sessionStoreName});let s={sessionId:a,workspaceDir:i,channel:t.channel},c=hl({runParams:t,hookContext:s,sessionId:a,eventDispatcher:r}),l=c.hookRegistry,u=await _c({runParams:t,sessionId:a,hookContext:s,memoryProviderId:t.memory?.providerId,memoryPluginId:c.memoryPluginId,eventDispatcher:r,hookRegistry:l});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:s,hookRegistry:l,pluginContext:c,runContext:u,start:e=>jn({sessionId:a,runParams:t,hookRegistry:l,hookContext:s,eventDispatcher:r,...e})}}function _l(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function vl(e){if(!(e instanceof Error))return{errorValue:_l(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]=_l(n[e]));return t}async function yl(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...vl(e.error)}})}function bl(e,t,n){return B.join(o(e,t,n),`pending-hitl.json`)}function xl(e,t,n){return B.join(o(e,t,n),`hitl-history.jsonl`)}async function Sl(e,t,n,r){let i=o(e,t,r);await z.mkdir(i,{recursive:!0});let a=bl(e,t,r);await z.writeFile(a,JSON.stringify(n,null,2),`utf-8`)}async function Cl(e,t,n,r){let i=o(e,t,r);await z.mkdir(i,{recursive:!0});let a=xl(e,t,r),s=JSON.stringify(n)+`
102
+ `;await z.appendFile(a,s,`utf-8`)}async function wl(e,t,n){let r=bl(e,t,n);try{let e=await z.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Tl(e,t,n){let r=xl(e,t,n);try{let e=await z.readFile(r,`utf-8`),t=[];for(let n of e.split(`
103
+ `)){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 El(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 Sl(e,t,c,o),await Cl(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function Dl(e,t,n,r,i,a){let o=await wl(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 Sl(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await Cl(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function Ol(e,t,n,r){let i=await wl(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function kl(e,t,n){let r=bl(e,t,n);try{await z.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function Al(e,t,n){return B.join(o(e,t,n),`pending-ui-tool.json`)}async function jl(e,t,n,r){let i=o(e,t,r);await z.mkdir(i,{recursive:!0}),await z.writeFile(Al(e,t,r),JSON.stringify(n,null,2),`utf-8`)}async function Ml(e,t,n){try{let r=await z.readFile(Al(e,t,n),`utf-8`);return JSON.parse(r)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Nl(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await jl(e,t,a,r),a}async function Pl(e,t,n,r,i){let a=await Ml(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 jl(e,t,o,i),o}async function Fl(e,t,n){try{await z.unlink(Al(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const Il=`crons`;function Ll(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:Ht(e.message)}}function Rl(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&&!ge(t))}async function Bl(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=is();if(i=await as(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(q(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Vl(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 Vl(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 Hl(e,t){Vt(e.dataDir),Tn();let r=Date.now(),i=new En(e),a=_r(e);U.info(`agent invocation prepared`,{requestedSessionId:a.requestedSessionId,previousSessionId:a.previousSessionId,inputMode:a.inputMode,hasSlashCommand:!!a.slashCommandSource,resetAction:a.resetCommand?.action,resetShortCircuit:a.resetShortCircuit,transcriptLength:a.transcriptMessage.length,messageForRunLength:a.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let o=a.transcriptMessage,s=!1,c=a.previousSessionId,l=await gl({runParams:e,requestedSessionId:a.requestedSessionId,eventDispatcher:i}),u=l.sessionId,d=l.isNewSession,f=l.workspaceDir,p=l.hookContext,m=l.hookRegistry,h=l.pluginContext,g=l.runContext;U.info(`agent run started`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:d,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:d,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),U.info(d?`session created`:`session resumed`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}),await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:d?`session_created`:`session_resumed`,message:d?`session created`:`session resumed`,details:{requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}}),d&&await n(e.dataDir,vc({sessionId:u,title:An(o),channel:e.channel}),{storeName:e.sessionStoreName}),a.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(s=await g.persistInitialUserEntry(o)),await l.start({resetCommand:a.resetCommand,previousSessionId:c,resetMessage:a.slashCommandSource,startMessage:typeof a.promptInput==`string`?a.promptInput:o});let _=new AbortController;e.abortSignal?.aborted?_.abort():e.abortSignal?.addEventListener(`abort`,()=>_.abort());let v=await Xe(e.dataDir),y=[],b=$e(v,{warn:e=>y.push(e)}),x=await nt();await i.dispatchDiagnostic(u,{level:y.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:v.length,contextFileCount:b.length,warningCount:y.length}}),U.info(`bootstrap context loaded`,{sessionId:u,bootstrapFileCount:v.length,contextFileCount:b.length,warningCount:y.length});let S=e.skillsLoadPaths??[],C=await ct(e.dataDir,h.pluginSkillDirs,S),w=e.agentPolicy?.availableAgents??await _t({dataDir:e.dataDir,projectDir:e.projectDir}),T=e.agentPolicy?.activeAgent??bt(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 i.dispatchDiagnostic(u,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:C.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:S.length,skills:C.map(e=>({name:e.name,description:e.description,location:e.location}))}}),U.info(`skills loaded`,{sessionId:u,skillCount:C.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:S.length}),await i.dispatchDiagnostic(u,{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}))}}),U.info(`custom agents loaded`,{sessionId:u,agentCount:w.length,activeAgent:E.activeAgent?.name,requestedAgentName:E.requestedAgentName});let O=e=>g.appendTranscriptEntry(e),k=await yr({invocation:a,skills:C,sessionId:u,isNewSession:d,initialUserEntryPersisted:s,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i});if(k.kind===`completed`)return U.info(`agent run short-circuited`,{sessionId:u,durationMs:Date.now()-r,hasError:!!k.result.error,paused:!!k.result.paused,uiToolPending:!!k.result.uiToolPending,textLength:k.result.text.length}),k.result;let A=k.effectivePrompt;o=k.transcriptMessage;let ee=typeof A==`string`?A:o;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof A==`string`?`string`:`messages`,transcriptLength:o.length}}),U.info(`invocation resolved`,{sessionId:u,promptType:typeof A==`string`?`string`:`messages`,transcriptLength:o.length});let j=await ks({session:{runParams:D,sessionId:u,hookRegistry:m,hookContext:p,runContext:g,eventDispatcher:i},runtimeInputs:{contextFiles:b,bootstrapWarnings:y,skills:C,effectivePromptText:ee,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:S,presetSystemPrompt:x.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>Hl(e,new Gt),createModel:Rl,abortSignal:_.signal}}),M=j.agent,N=j.resolvedModelId;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:N,historyMessageCount:j.historyMessages.length,pluginToolCount:h.pluginTools.length}}),U.info(`agent runtime created`,{sessionId:u,modelId:N,historyMessageCount:j.historyMessages.length,pluginToolCount:h.pluginTools.length}),_.signal.addEventListener(`abort`,()=>M.abort());let P=0,F=0,I=``,L,te=!1;try{if(zl(e)){let t=await Bl({params:e,agent:M,sessionId:u,eventDispatcher:i,appendEntry:O,abortSignal:_.signal});return I=t.text,Pn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:I,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(o);te=e,s=e||s}await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`}),U.info(`first agent turn started`,{sessionId:u,modelId:N});let n=await Gs({agent:M,message:A,continueFromHistory:!!e.uiToolResume,sessionId:u,modelId:N,historyMessages:j.historyMessages,eventDispatcher:i,hooks:m,hookCtx:p,abortSignal:_.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await O(e);for(let e of t)await O(e)}});I=n.text,P+=n.inputTokens,F+=n.outputTokens,n.error&&(L=n.error),await i.dispatchDiagnostic(u,{level:n.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens}});let a={sessionId:u,hasError:!!n.error,error:n.error,inputTokens:n.inputTokens,outputTokens:n.outputTokens};n.error?U.warn(`first agent turn completed with error`,a):U.info(`first agent turn completed`,a),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),U.info(`announce loop started`,{sessionId:u});let c=await fc({agent:M,registry:t,sessionId:u,resolvedModelId:N,eventDispatcher:i,hookRegistry:m,hookContext:p,abortSignal:_.signal,retry:e.llmRetry,appendEntry:O});c.text&&(I=c.text),P+=c.inputTokens,F+=c.outputTokens,c.error&&!L&&(L=c.error),await i.dispatchDiagnostic(u,{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 l={sessionId:u,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?U.warn(`announce loop completed with error`,l):U.info(`announce loop completed`,l)}catch(t){if(q(t)){let n=t,a=e.subagentContext?.parentSessionId??u,s=a===n.request.sessionId?n.request:{...n.request,sessionId:a};await El(e.dataDir,a,s,n.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},n.toolContext),await i.dispatchProgress(a,{type:`hitl_requested`,request:s}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${n.request.kind} — ${n.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:n.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),U.info(`agent paused for HITL`,{sessionId:u,requestId:s.requestId,kind:s.kind,checkpointPhase:n.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:P,output:F,total:P+F};return await Ul({runtime:j,resolvedModelId:N,usage:c,currentUserEntryCoveredByUsage:te}),Pn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:I||`[HITL paused] ${n.request.title}: ${n.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(So(t)){let n=t,a=n.request.outputSchema.properties??{};await Nl(e.dataDir,u,n.request,{storeName:e.sessionStoreName}),await i.dispatchProgress(u,{type:`ui_tool_request`,request:n.request}),await i.dispatchDiagnostic(u,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${n.request.toolName}`,details:{requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchemaTitle:n.request.outputSchema.title,propertyCount:Object.keys(a).length}}),U.info(`agent paused for UI tool input`,{sessionId:u,requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchemaTitle:n.request.outputSchema.title,propertyCount:Object.keys(a).length});let s={input:P,output:F,total:P+F};return await Ul({runtime:j,resolvedModelId:N,usage:s,currentUserEntryCoveredByUsage:te}),Pn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:I||``,usage:s,error:void 0,uiToolPending:{requestId:n.request.requestId,toolName:n.request.toolName,toolCallId:n.request.toolCallId,outputSchema:n.request.outputSchema,extra:n.request.extra}})}throw await yl({dispatcher:i,sessionId:u,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:d}}),U.error(`agent run failed`,{sessionId:u,channel:e.channel,isNewSession:d,error:t instanceof Error?t.message:String(t)}),t}finally{Jt(u),g.stop()}let R={input:P,output:F,total:P+F};await i.dispatchDiagnostic(u,{level:L?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-r,inputTokens:R.input,outputTokens:R.output,totalTokens:R.total,hasError:!!L,error:L}});let ne={sessionId:u,durationMs:Date.now()-r,inputTokens:R.input,outputTokens:R.output,totalTokens:R.total,hasError:!!L,error:L};return L?U.warn(`agent run completed with error`,ne):U.info(`agent run completed`,ne),await Ul({runtime:j,resolvedModelId:N,usage:R,currentUserEntryCoveredByUsage:te}),Pn({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:r,eventDispatcher:i,text:I,usage:R,error:L})}async function Ul(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 Wl(e){Vt(e.dataDir);let t=Date.now(),a=new En(e),o=_r(e),c=o.transcriptMessage.trim()||`CRON task`,l=e.sessionStoreName;U.info(`cron run started`,{requestedSessionId:o.requestedSessionId,channel:e.channel,sessionStoreName:l,...Ll(e)});let u=o.requestedSessionId,d=!u;u?(await b(e.dataDir,u,{storeName:l})||(d=!0),await _(e.dataDir,u,{storeName:l})):u=await T(e.dataDir,e.channel,{storeName:l}),d&&await n(e.dataDir,vc({sessionId:u,title:An(c),channel:e.channel}),{storeName:l});let f=await T(e.dataDir,e.channel,{storeName:Il});await a.dispatchProgress(u,{type:`subagent_spawn`,childSessionId:f,task:c}),U.info(`cron child subagent spawned`,{parentSessionId:u,childSessionId:f,taskLength:c.length,taskPreview:Ht(c)});let p={...e,sessionId:f,sessionStoreName:Il,subagentContext:{depth:1,parentSessionId:u}},m,g=`done`;try{m=await Hl(p,new Gt),m.error&&(g=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);m={sessionId:f,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:h(e.dataDir,f,{storeName:Il}),toolResultsDir:i(e.dataDir,f,{storeName:Il})}},g=`error`,U.error(`cron child run failed`,{parentSessionId:u,childSessionId:f,error:r})}await a.dispatchProgress(u,{type:`subagent_complete`,childSessionId:f,task:c,status:g}),U.info(`cron child subagent completed`,{parentSessionId:u,childSessionId:f,status:g,durationMs:Date.now()-t,hasError:!!m.error});let v=fo({task:c,status:g,result:m.text,error:m.error}),y=new Date().toISOString();await O(e.dataDir,u,{role:`assistant`,content:v,timestamp:y,source:`cron`},{storeName:l});let S={task:c,status:g,content:v,childSessionId:f,createdAt:y};return await x(e.dataDir,u,S,{storeName:l}),await r(e.dataDir,u,e=>Gl(e,8),{storeName:l}),await s(e.dataDir,u,{},{storeName:l}),{...m,sessionId:u,context:{snapshotPath:h(e.dataDir,u,{storeName:l}),toolResultsDir:i(e.dataDir,u,{storeName:l})}}}function Gl(e,t){if(t<=0)return e.filter(e=>!Kl(e));let n=e.reduce((e,t,n)=>(Kl(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Kl(e)||r.has(t))}function Kl(e){return`source`in e&&e.source===`cron`}async function ql(e,t){if(Vt(e.dataDir),U.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,...Ll(e)}),e.channel===`CRON`&&!e.subagentContext)return Wl(e);let n=t??new Gt;try{return await Hl(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:vl(t)}),U.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 Jl={"AGENTS.md":`---
101
104
  title: "AGENTS.md Template"
102
105
  summary: ".aimax template for AGENTS.md"
103
106
  read_when:
@@ -390,7 +393,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
390
393
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
391
394
 
392
395
  Add whatever helps you do your job. This is your cheat sheet.
393
- `},Yc=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Xc(e,t){try{if(!(await L.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 L.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Zc(e,t,n){try{if(!(await L.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 L.mkdir(R.dirname(e),{recursive:!0});try{await L.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 Qc(e){let t=H(e);return[e,t,R.join(t,`skills`),R.join(t,`sessions`),R.join(t,`memory`),R.join(e,`workspace`)]}function $c(e){let t=H(e);return[...Yc.filter(e=>e!==`BOOTSTRAP.md`).map(e=>R.join(t,e)),R.join(t,`MEMORY.md`)]}function el(e){return R.join(H(e),`.bootstrapped`)}async function tl(e){try{return(await L.stat(el(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function nl(e){let t=el(e);await L.mkdir(R.dirname(t),{recursive:!0}),await L.writeFile(t,``,{encoding:`utf-8`})}async function rl(e){let t=[],n=[];for(let n of Qc(e))try{(await L.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of $c(e))try{(await L.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 il(e){return(await rl(e)).ready}async function al(e){if(await tl(e))return{ready:!0,performedBootstrap:!1};if((await rl(e)).ready)return await nl(e),{ready:!0,performedBootstrap:!1};let t=await ol(e);return await nl(e),{ready:!0,performedBootstrap:!0,result:t}}async function ol(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=H(e),r=R.join(e,`workspace`),i=R.join(n,`skills`),a=R.join(n,`sessions`),o=R.join(n,`memory`);await Xc(e,t),await Xc(n,t),await Xc(i,t),await Xc(a,t),await Xc(o,t),await Xc(r,t);for(let e of Yc){let r=Jc[e]??``;await Zc(R.join(n,e),r,t)}return await Zc(R.join(n,`MEMORY.md`),``,t),t}async function sl(e){let t=R.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await L.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 cl(e,t){let n=R.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 L.mkdir(R.dirname(n),{recursive:!0}),await L.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function ll(e,t){let n=await sl(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 ul(e,t=7){let n=await sl(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 cl(e,n),i}async function dl(e,t,n,r){let i=await Tc(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?_e(i.request)?(await Oc(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 fl(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await kc(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 dl(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await Oc(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 pl={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 ml(e){return e.action===`timeout`?pl.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?pl.approval.summary.approved:pl.approval.summary.denied}function hl(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:ml(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function gl(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 _l(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 vl(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
396
+ `},Yl=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Xl(e,t){try{if(!(await z.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 z.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Zl(e,t,n){try{if(!(await z.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 z.mkdir(B.dirname(e),{recursive:!0});try{await z.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 Ql(e){let t=Ye(e);return[e,t,B.join(t,`skills`),B.join(t,`sessions`),B.join(t,`memory`),B.join(e,`workspace`)]}function $l(e){let t=Ye(e);return[...Yl.filter(e=>e!==`BOOTSTRAP.md`).map(e=>B.join(t,e)),B.join(t,`MEMORY.md`)]}function eu(e){return B.join(Ye(e),`.bootstrapped`)}async function tu(e){try{return(await z.stat(eu(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function nu(e){let t=eu(e);await z.mkdir(B.dirname(t),{recursive:!0}),await z.writeFile(t,``,{encoding:`utf-8`})}async function ru(e){let t=[],n=[];for(let n of Ql(e))try{(await z.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of $l(e))try{(await z.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 iu(e){return(await ru(e)).ready}async function au(e){if(await tu(e))return{ready:!0,performedBootstrap:!1};if((await ru(e)).ready)return await nu(e),{ready:!0,performedBootstrap:!1};let t=await ou(e);return await nu(e),{ready:!0,performedBootstrap:!0,result:t}}async function ou(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=Ye(e),r=B.join(e,`workspace`),i=B.join(n,`skills`),a=B.join(n,`sessions`),o=B.join(n,`memory`);await Xl(e,t),await Xl(n,t),await Xl(i,t),await Xl(a,t),await Xl(o,t),await Xl(r,t);for(let e of Yl){let r=Jl[e]??``;await Zl(B.join(n,e),r,t)}return await Zl(B.join(n,`MEMORY.md`),``,t),t}async function su(e){let t=B.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await z.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 cu(e,t){let n=B.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 z.mkdir(B.dirname(n),{recursive:!0}),await z.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function lu(e,t){let n=await su(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 uu(e,t=7){let n=await su(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 cu(e,n),i}async function du(e,t,n,r){let i=await wl(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?he(i.request)?(await Dl(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 fu(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await Ol(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 du(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await Dl(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 pu={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 mu(e){return e.action===`timeout`?pu.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?pu.approval.summary.approved:pu.approval.summary.denied}function hu(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:mu(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function gu(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 _u(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 vu(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
394
397
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
395
398
  `)):(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(`
396
- `))}export{Je as BOOTSTRAP_FILE_NAMES,Ke as BOOTSTRAP_MAX_CHARS,qe as BOOTSTRAP_TOTAL_MAX_CHARS,p as DEFAULT_SESSION_STORE_NAME,pl as HITL_MESSAGES,jr as HitlPauseSignal,mt as MAX_CHILDREN_PER_SESSION,pt as MAX_SUBAGENT_DEPTH,E as MemoryIndexManager,tc as PLUGIN_MANIFEST_FILENAME,nc as PLUGIN_MANIFEST_FILENAMES,Oo as PluginHookRegistry,xo as PluginToolRegistry,ht as SubagentRegistry,Va as UiToolPauseSignal,pe as addAgent,le as addBinding,H as aimaxDir,x as appendCronExecutionRecord,Ri as appendRecentToMemory,Li as appendToMemory,O as appendTranscriptEntry,ml as approvalSummaryFromResolution,ol as bootstrapMountLayout,Qe as buildBootstrapContextFiles,vl as buildResumeNarration,ft as buildSkillsPrompt,Na as buildSubagentAnnounceMessage,go as buildSystemPrompt,ul as cleanupOldSubagentRecords,Ac as clearPendingHitl,Ic as clearPendingUiTool,m as collapseLogPath,h as contextSnapshotPath,Ya as createAgentTools,vi as createApplyPatchTool,ti as createBashTool,C as createBuiltinMemoryProvider,kr as createContextManager,ui as createEditFileTool,Vr as createExecTool,Ba as createImageTool,fi as createListDirTool,Gi as createMemoryAppendTool,aa as createMemoryForgetTool,Ui as createMemoryGetTool,ra as createMemoryListTool,ta as createMemoryLogTool,Vi as createMemorySearchTool,sa as createMemoryUpdateTool,qi as createMemoryWriteTool,Dc as createPendingHitl,Pc as createPendingUiTool,yo as createPluginProgressEmitter,lc as createPluginRuntime,Gr as createProcessTool,oi as createReadFileTool,T as createSession,nr as createSessionContextStore,la as createSessionSearchTool,Aa as createSkillListTool,ja as createSkillLoadTool,Pa as createSubagentSpawnTool,Ra as createSubagentsTool,Ja as createUiTool,ci as createWriteFileTool,S as cronExecutionsPath,qa as defaultUiToolInputSchema,zi as deleteMemoryFile,$s as discoverAIMaxPlugins,al as ensureBootstrapMountLayout,_ as ensureSession,g as exportSession,lt as findSkillByName,hl as formatApprovalResolution,gl as formatClarifyResolution,_l as formatReviewResolution,Zt as generateSessionTitle,oe as getAgentConfig,Z as getMemoryLines,tl as hasBootstrapSentinel,Sc as hitlHistoryPath,hc as initializePluginSystem,rl as inspectBootstrapMountLayout,u as inspectSession,il as isBootstrapMountLayoutReady,q as isHitlPauseSignal,Ha as isUiToolPauseSignal,ee as listAgents,ln as listAvailableSlashCommands,ue as listBindings,Ni as listMemoryFiles,k as listSessionSummaries,M as listSessions,ll as listSubagentRunsFromDisk,fe as loadAgentsConfig,Ye as loadBootstrapFiles,f as loadCronExecutionRecords,Tc as loadPendingHitl,Tc as readPendingHitl,Nc as loadPendingUiTool,Nc as readPendingUiTool,ic as loadPluginManifest,ac as loadPluginManifestRegistry,fc as loadPlugins,j as loadSessionContextSnapshot,c as loadSessionMetadata,dt as loadSkillView,ot as loadSkills,ct as loadSkillsFromDirs,st as loadSkillsWithPluginDirs,sl as loadSubagentRegistryFromDisk,t as loadTranscript,Ai as memoryDir,A as metadataPath,te as normalizeAgentId,ks as normalizePluginsConfig,l as normalizeSessionStoreName,xc as pendingHitlPath,jc as pendingUiToolPath,ji as primaryMemoryPath,Ec as readHitlHistory,Pi as readMemoryFile,Fi as readPrimaryMemory,v as registerEmbeddingProvider,P as registerMemoryProvider,se as removeAgent,me as removeBindings,Q as replaceMemoryFile,d as resetEmbeddingProviderRegistryForTests,F as resetMemoryProviderRegistryForTests,ne as resolveAgentDir,re as resolveAgentIdByBinding,de as resolveAgentsConfigPath,ce as resolveDefaultAgentId,w as resolveEmbeddingProvider,fl as resolveHitlRequest,fl as resolvePendingHitl,N as resolveMemoryProvider,ae as resolveModelFallbacks,ie as resolveModelString,Fc as resolvePendingUiTool,rc as resolvePluginManifestPath,r as rewriteTranscript,qc as runAgent,I as saveAgentsConfig,n as saveSessionMetadata,cl as saveSubagentRegistryToDisk,Ii as searchMemory,o as sessionDir,e as sessionMemoryPath,y as sessionsDir,nt as skillsDir,i as toolResultsDir,a as transcriptPath,Oc as transitionHitlStatus,he as updateAgentIdentity,s as updateSessionMetadata,As as validatePluginsConfig,dl as validateResume,Do as wrapToolsWithHooks};
399
+ `))}export{Je as BOOTSTRAP_FILE_NAMES,Ke as BOOTSTRAP_MAX_CHARS,qe as BOOTSTRAP_TOTAL_MAX_CHARS,p as DEFAULT_SESSION_STORE_NAME,pu as HITL_MESSAGES,ci as HitlPauseSignal,Wt as MAX_CHILDREN_PER_SESSION,Ut as MAX_SUBAGENT_DEPTH,E as MemoryIndexManager,tl as PLUGIN_MANIFEST_FILENAME,nl as PLUGIN_MANIFEST_FILENAMES,cs as PluginHookRegistry,ts as PluginToolRegistry,mt as SYSTEM_AGENTS_DIR,Gt as SubagentRegistry,xo as UiToolPauseSignal,de as addAgent,se as addBinding,gt as agentDirCandidates,Ye as aimaxDir,x as appendCronExecutionRecord,ga as appendRecentToMemory,ha as appendToMemory,O as appendTranscriptEntry,mu as approvalSummaryFromResolution,ou as bootstrapMountLayout,Ct as buildAgentDelegationPrompt,wt as buildAgentTaskPrompt,$e as buildBootstrapContextFiles,vu as buildResumeNarration,pt as buildSkillsPrompt,fo as buildSubagentAnnounceMessage,Xo as buildSystemPrompt,uu as cleanupOldSubagentRecords,kl as clearPendingHitl,Fl as clearPendingUiTool,m as collapseLogPath,h as contextSnapshotPath,ko as createAgentTools,Yi as createApplyPatchTool,Mi as createBashTool,C as createBuiltinMemoryProvider,oi as createContextManager,Vi as createEditFileTool,vi as createExecTool,bo as createImageTool,Ui as createListDirTool,Ca as createMemoryAppendTool,La as createMemoryForgetTool,xa as createMemoryGetTool,Fa as createMemoryListTool,Na as createMemoryLogTool,ya as createMemorySearchTool,za as createMemoryUpdateTool,Ta as createMemoryWriteTool,El as createPendingHitl,Nl as createPendingUiTool,$o as createPluginProgressEmitter,cl as createPluginRuntime,Si as createProcessTool,Li as createReadFileTool,T as createSession,Nr as createSessionContextStore,Va as createSessionSearchTool,co as createSkillListTool,lo as createSkillLoadTool,mo as createSubagentSpawnTool,vo as createSubagentsTool,Oo as createUiTool,zi as createWriteFileTool,S as cronExecutionsPath,Do as defaultUiToolInputSchema,_a as deleteMemoryFile,$c as discoverAIMaxPlugins,au as ensureBootstrapMountLayout,_ as ensureSession,g as exportSession,xt as filterSkillsForAgent,St as filterToolsForAgent,bt as findAgentDefinition,ut as findSkillByName,hu as formatApprovalResolution,gu as formatClarifyResolution,_u as formatReviewResolution,On as generateSessionTitle,ie as getAgentConfig,ma as getMemoryLines,tu as hasBootstrapSentinel,xl as hitlHistoryPath,ml as initializePluginSystem,ru as inspectBootstrapMountLayout,u as inspectSession,iu as isBootstrapMountLayoutReady,q as isHitlPauseSignal,So as isUiToolPauseSignal,I as listAgents,zn as listAvailableSlashCommands,ce as listBindings,ua as listMemoryFiles,k as listSessionSummaries,j as listSessions,lu as listSubagentRunsFromDisk,vt as loadAgentDefinitionsFromDir,ue as loadAgentsConfig,Xe as loadBootstrapFiles,f as loadCronExecutionRecords,wl as loadPendingHitl,wl as readPendingHitl,Ml as loadPendingUiTool,Ml as readPendingUiTool,il as loadPluginManifest,al as loadPluginManifestRegistry,dl as loadPlugins,ee as loadSessionContextSnapshot,c as loadSessionMetadata,ft as loadSkillView,st as loadSkills,lt as loadSkillsFromDirs,ct as loadSkillsWithPluginDirs,su as loadSubagentRegistryFromDisk,t as loadTranscript,sa as memoryDir,A as metadataPath,L as normalizeAgentId,kc as normalizePluginsConfig,l as normalizeSessionStoreName,yt as parseAgentDefinition,bl as pendingHitlPath,Al as pendingUiToolPath,ca as primaryMemoryPath,Tl as readHitlHistory,da as readMemoryFile,fa as readPrimaryMemory,v as registerEmbeddingProvider,N as registerMemoryProvider,ae as removeAgent,fe as removeBindings,Z as replaceMemoryFile,d as resetEmbeddingProviderRegistryForTests,P as resetMemoryProviderRegistryForTests,te as resolveAgentDir,R as resolveAgentIdByBinding,le as resolveAgentsConfigPath,oe as resolveDefaultAgentId,w as resolveEmbeddingProvider,fu as resolveHitlRequest,fu as resolvePendingHitl,M as resolveMemoryProvider,re as resolveModelFallbacks,ne as resolveModelString,Pl as resolvePendingUiTool,rl as resolvePluginManifestPath,r as rewriteTranscript,ql as runAgent,F as saveAgentsConfig,n as saveSessionMetadata,cu as saveSubagentRegistryToDisk,_t as scanAgentDefinitions,pa as searchMemory,o as sessionDir,e as sessionMemoryPath,y as sessionsDir,rt as skillsDir,i as toolResultsDir,a as transcriptPath,Dl as transitionHitlStatus,pe as updateAgentIdentity,s as updateSessionMetadata,Ac as validatePluginsConfig,du as validateResume,ss as wrapToolsWithHooks};