@gencode/agents 0.7.7 → 0.8.1

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,123 +1,124 @@
1
- import{A as e,C as t,D as n,E as r,F as i,I as a,M as o,N as s,O as c,P as l,S as u,T as d,_ as f,a as p,b as m,c as h,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,m as w,n as T,o as E,p as D,r as O,s as k,t as ee,u as A,v as j,w as te,x as M,y as N}from"./session-CiekMEUQ.js";import{n as P,t as F}from"./goal-events-Bdf1BDep.js";import{a as I,c as L,l as R,n as z,o as B,r as V,s as H,t as U}from"./goal-store-DxaeZmiE.js";import{a as ne,i as W,n as re,o as ie,r as ae,s as oe}from"./builtin-provider-Bhzb_o53.js";import{i as se,n as ce,r as le}from"./provider-registry-Kh5nNG84.js";import{a as ue,i as de,l as fe,n as pe,o as me,r as he,s as ge,t as _e}from"./session-store-DjXWnxJY.js";import{_ as ve,a as ye,c as be,d as xe,f as Se,g as Ce,h as we,i as Te,l as Ee,m as De,n as Oe,o as ke,p as Ae,s as je,t as Me,u as Ne,v as Pe}from"./config-CJ7qy-pr.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Fe,formatTaskForDisplay as Ie,isHitlExpired as Le,isHitlTool as Re,validateUiToolResult as ze}from"@gencode/shared";import G,{readFile as Be}from"node:fs/promises";import K,{join as Ve}from"node:path";import He from"gray-matter";import{createHash as Ue,randomUUID as We}from"node:crypto";import{TextDecoder as Ge}from"node:util";import{Agent as Ke}from"@mariozechner/pi-agent-core";import{AsyncLocalStorage as qe}from"node:async_hooks";import Je from"openai";import{Type as q,calculateCost as Ye,getEnvApiKey as Xe,parseStreamingJson as Ze,registerApiProvider as Qe,registerBuiltInApiProviders as $e,supportsXhigh as et}from"@mariozechner/pi-ai";import{AssistantMessageEventStream as tt}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as nt}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as rt,hasCopilotVisionInput as it}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as at,clampReasoning as ot}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as st}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import J from"node:fs";import ct from"log4js";import lt from"node:os";import{spawn as ut}from"node:child_process";import{isBinaryFile as dt}from"isbinaryfile";import ft from"ajv";import{createJiti as pt}from"jiti";const mt=2e4,ht=15e4,gt=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function _t(e){return K.join(e,`.aimax`)}async function vt(e){let t=_t(e),n=[];for(let e of gt){let r=K.join(t,e);try{let t=await G.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await G.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 yt(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,F as i,I as a,M as o,N as s,O as c,P as l,S as u,T as d,_ as f,a as p,b as m,c as h,d as g,f as _,g as v,h as y,i as b,j as x,k as S,l as C,m as w,n as T,o as E,p as D,r as O,s as k,t as ee,u as A,v as j,w as M,x as te,y as ne}from"./session-CiekMEUQ.js";import{n as N,t as P}from"./goal-events-Bdf1BDep.js";import{a as F,c as I,l as L,n as R,o as z,r as B,s as V,t as H}from"./goal-store-DxaeZmiE.js";import{a as re,i as U,n as ie,o as ae,r as oe,s as se}from"./builtin-provider-Bhzb_o53.js";import{i as ce,n as le,r as ue}from"./provider-registry-Kh5nNG84.js";import{a as de,i as fe,l as pe,n as me,o as he,r as ge,s as _e,t as ve}from"./session-store-DjXWnxJY.js";import{_ as ye,a as be,c as xe,d as Se,f as Ce,g as we,h as Te,i as Ee,l as De,m as Oe,n as ke,o as Ae,p as je,s as Me,t as Ne,u as Pe,v as Fe}from"./config-CJ7qy-pr.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Ie,formatTaskForDisplay as Le,isHitlExpired as Re,isHitlTool as ze,validateUiToolResult as Be}from"@gencode/shared";import W,{readFile as Ve}from"node:fs/promises";import G,{join as He}from"node:path";import Ue from"gray-matter";import{createHash as We,randomUUID as Ge}from"node:crypto";import{TextDecoder as Ke}from"node:util";import{Agent as qe}from"@mariozechner/pi-agent-core";import{AsyncLocalStorage as Je}from"node:async_hooks";import Ye from"openai";import{Type as K,calculateCost as Xe,getEnvApiKey as Ze,parseStreamingJson as Qe,registerApiProvider as $e,registerBuiltInApiProviders as et,supportsXhigh as tt}from"@mariozechner/pi-ai";import{AssistantMessageEventStream as nt}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as rt}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as it,hasCopilotVisionInput as at}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as ot,clampReasoning as st}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as ct}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import q from"node:fs";import lt from"log4js";import ut from"node:os";import{spawn as dt}from"node:child_process";import{isBinaryFile as ft}from"isbinaryfile";import pt from"ajv";import{createJiti as mt}from"jiti";const ht=2e4,gt=15e4,_t=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function vt(e){return G.join(e,`.aimax`)}async function yt(e){let t=vt(e),n=[];for(let e of _t){let r=G.join(t,e);try{let t=await W.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await W.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 bt(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 bt(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function xt(e,t){let n=t?.maxChars??mt,r=Math.max(1,t?.totalMaxChars??Math.max(n,ht)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=bt(`[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}=yt(a.content??``,a.name,e),l=bt(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 St=`You are a personal assistant running inside AiMax.`;async function Ct(e){try{return{presetSystemPrompt:He(await G.readFile(e,`utf-8`)).content.trim()||St}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:St};throw e}}async function wt(){return Ct(`/aimax/system_prompt.md`)}function Tt(e){return K.join(e,`.aimax`,`skills`)}function Et(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Dt(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${Et(n)}\n`)}function Ot(e){let t=He(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``}function kt(e){let t=He(e),n=t.data.metadata,r=(n&&typeof n==`object`&&!Array.isArray(n)?n.version:void 0)??t.data.version;return r==null?``:String(r).trim()}async function At(e){return(await G.stat(e)).mtime.toISOString()}async function jt(e){return Nt([Tt(e)])}async function Mt(e,t,n=[]){return Nt([...n,...t,Tt(e)])}async function Nt(e){let t=new Map;for(let n of e){let e;try{e=await G.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=K.join(n,e,`SKILL.md`),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=Ot(i),o=kt(i),s=await At(r)}catch(t){Dt(e,r,t);continue}t.set(e,{name:e,description:a,location:r,version:o,skillFileMtime:s})}}return Array.from(t.values()).slice(0,50)}async function Pt(e,t){let n=t.trim();if(!n)return;let r=(await Nt(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:K.dirname(r.location)}}async function Ft(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=K.resolve(r),a=K.basename(i)===`SKILL.md`?i:K.join(i,`SKILL.md`);if(K.basename(a)!==`SKILL.md`)return;let o;try{o=await G.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=Ot(o),c=kt(o),l=await At(a)}catch(e){Dt(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:K.dirname(a)}}async function It(e,t,n){let r=n?.trim()?await Ft(t,n):await Pt(e,t);if(!r)return;let i=await G.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Lt(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
3
+ `),truncated:!0,originalLength:r.length}}function xt(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function St(e,t){let n=t?.maxChars??ht,r=Math.max(1,t?.totalMaxChars??Math.max(n,gt)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=xt(`[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}=bt(a.content??``,a.name,e),l=xt(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 Ct=`You are a personal assistant running inside AiMax.`;async function wt(e){try{return{presetSystemPrompt:Ue(await W.readFile(e,`utf-8`)).content.trim()||Ct}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:Ct};throw e}}async function Tt(){return wt(`/aimax/system_prompt.md`)}function Et(e){return G.join(e,`.aimax`,`skills`)}function Dt(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ot(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${Dt(n)}\n`)}function kt(e){let t=Ue(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``}function At(e){let t=Ue(e),n=t.data.metadata,r=(n&&typeof n==`object`&&!Array.isArray(n)?n.version:void 0)??t.data.version;return r==null?``:String(r).trim()}async function jt(e){return(await W.stat(e)).mtime.toISOString()}async function Mt(e){return Pt([Et(e)])}async function Nt(e,t,n=[]){return Pt([...n,...t,Et(e)])}async function Pt(e){let t=new Map;for(let n of e){let e;try{e=await W.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=G.join(n,e,`SKILL.md`),i;try{i=await W.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=kt(i),o=At(i),s=await jt(r)}catch(t){Ot(e,r,t);continue}t.set(e,{name:e,description:a,location:r,version:o,skillFileMtime:s})}}return Array.from(t.values()).slice(0,50)}async function Ft(e,t){let n=t.trim();if(!n)return;let r=(await Pt(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:G.dirname(r.location)}}async function It(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=G.resolve(r),a=G.basename(i)===`SKILL.md`?i:G.join(i,`SKILL.md`);if(G.basename(a)!==`SKILL.md`)return;let o;try{o=await W.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=kt(o),c=At(o),l=await jt(a)}catch(e){Ot(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:G.dirname(a)}}async function Lt(e,t,n){let r=n?.trim()?await It(t,n):await Ft(e,t);if(!r)return;let i=await W.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Rt(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
5
5
  `)).join(`
6
- `)}\n</available_skills>`}var Rt=class{turn=null;wallClock={activeGoalId:null,lastAccountedAt:Date.now()};resetWallClock(){this.wallClock.lastAccountedAt=Date.now()}markActiveGoal(e,t,n){e&&(this.turn&&this.turn.turnId===e?(this.turn.activeGoalId=t,this.turn.lastTokenUsage=n):this.turn={turnId:e,activeGoalId:t,lastTokenUsage:n}),this.wallClock.activeGoalId!==t&&this.resetWallClock(),this.wallClock.activeGoalId=t}clearActiveGoal(){this.turn&&(this.turn.activeGoalId=null),this.wallClock.activeGoalId=null,this.resetWallClock()}tokenDeltaSinceLastAccounting(e){if(!this.turn||!this.turn.activeGoalId)return 0;let t=this.turn.lastTokenUsage;return Math.max(0,e.input-t.input)+Math.max(0,e.output-t.output)}timeDeltaSecondsSinceLastAccounting(){if(!this.wallClock.activeGoalId)return 0;let e=Date.now()-this.wallClock.lastAccountedAt;return Math.floor(e/1e3)}markAccounted(e,t){this.turn&&(this.turn.lastTokenUsage=e),t>0&&(this.wallClock.lastAccountedAt+=t*1e3),this.wallClock.lastAccountedAt>Date.now()&&(this.wallClock.lastAccountedAt=Date.now())}};async function zt(e,t,n,r,i){let a=await B(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await L(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}function Bt(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function Vt(e,t){let n=Bt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed),a=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The user's thread goal is still active. Continue working toward the objective below.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Tokens remaining: ${a}`,`Time used: ${e.timeUsedSeconds}s`,``,`Rules:`,`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- Only call update_goal with status "complete" when the objective is fully achieved and verified.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress and the goal remains active.`,`- Do not inform the user about this continuation context; treat it as internal steering.`,``,`</goal_context>`].join(`
7
- `)}function Ht(e,t){let n=Bt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed);return[`<goal_context>`,``,`The token budget for the current thread goal has been exhausted.`,`The goal status has been set to "budget_limited" automatically.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Instructions:`,`- Wrap up the current turn soon. Do not start new substantive work.`,`- Summarize progress made, any blockers, and what would be needed next.`,`- Do NOT call update_goal(complete) unless the objective is truly achieved.`,`- The user can increase the budget or resume the goal later via the CLI.`,``,`</goal_context>`].join(`
8
- `)}function Ut(e,t){let n=Bt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The thread goal objective has been edited by the user.`,`The following objective supersedes any previous thread goal objective.`,`Adjust your work direction accordingly.`,``,`<untrusted_objective>`,n,`</untrusted_objective>`,``,`Token budget: ${r}`,`Tokens remaining: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Do not call update_goal unless the updated goal is actually complete.`,``,`</goal_context>`].join(`
9
- `)}function Wt(e){return{role:`user`,content:e}}function Gt(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Kt=`AIMAX_GOAL_CONTINUATION`;var qt=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};function Jt(){let e=process.env[Kt];return e===void 0||e===``||e!==`0`}async function Yt(e,t,n,r){if(!Jt()||n.continuationCount>=Fe)return!1;let i=await B(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-DjXWnxJY.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Xt(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Zt(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await Yt(n,r,a,{storeName:i}))return!1;let u=await B(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await H(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=Wt(p?Ht(u,f):Vt(u,f));a.continuationCount++;let h=await c(m.content);if(a.lastTurnHadOutput=Xt(h),p&&(a.budgetWrapUpDone=!0),l&&await l({input:h.inputTokens,output:h.outputTokens,total:h.inputTokens+h.outputTokens}),a.continuationCount>=Fe){let e=await B(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-DxaeZmiE.js`).then(e=>e.i),{appendGoalEvent:o}=await import(`./goal-events-Bdf1BDep.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${Fe}), goal paused`)}}return!0}async function Qt(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function $t(e,t,n,r){let i=await B(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Wt(Ut(i,await H(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function en(e,t,n){(await B(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await L(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}async function tn(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function nn(e,t,n){let r=n.before?.status??null,i=n.after?.status??null,a=n.before?.goalId,o=n.after?.goalId;r===i&&a===o||await tn(e,t,{action:n.action,goal:n.after??null})}function rn(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e)o.role===`user`?t+=1:o.role===`assistant`?n+=1:o.role===`tool_result`?r+=1:o.role===`compaction`?i+=1:a+=1;return{userTurnCount:t,assistantTurnCount:n,toolResultCount:r,compactionCount:i,otherEntryCount:a,totalEntryCount:e.length}}function an(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(pn(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}mn(a)&&(r+=1,a.isError&&(i+=1))}let a=Array.from(t).sort();return{toolCallCount:n,distinctToolCount:a.length,toolNames:a,toolResultCount:r,failedToolResultCount:i}}function on(e,t={}){let n=dn(t.limit,`limit`),r=fn(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!mn(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:un(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function sn(e,t){let n=fn(e,`totalEntryCount`);return typeof t!=`number`||!Number.isFinite(t)?{startIndex:0,endIndex:n}:{startIndex:Math.min(n,Math.max(0,Math.floor(t))),endIndex:n}}function cn(e,t=80){let n=fn(e,`totalEntryCount`),r=fn(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function ln(e,t){return e.slice(t.startIndex,t.endIndex)}function un(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function dn(e,t){return e===void 0?1/0:fn(e,t)}function fn(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function pn(e){return e.role===`assistant`}function mn(e){return e.role===`tool_result`}const hn=24e3;async function gn(e){return wn({params:e,kind:`current_run`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function _n(e){return wn({params:e,kind:`recent_conversation`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function vn(e){return wn({params:e,kind:`transcript_range`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function yn(e){let t=Mn(e),n=await xn(e),r=await On(n.filePath,t.maxBytes);return{kind:`tool_result`,toolCallId:n.reference.toolCallId,toolName:n.reference.toolName,storagePath:n.reference.storagePath,content:r.content,originalBytes:r.originalBytes,returnedBytes:Buffer.byteLength(r.content,`utf-8`),truncated:r.truncated,limits:t,contextFiles:Sn(e.dataDir,e.sessionId,e.sessionOptions)}}function bn(e){return{maxEntries:Nn(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Nn(e?.maxBytes??hn,`limits.maxBytes`)}}async function xn(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Tn(await En(e.dataDir,e.sessionId,e.sessionOptions),{toolCallId:e.toolCallId,storagePath:e.storagePath});if(!t)throw Error(`Requested tool result is not referenced by this session transcript or context.`);return{reference:t,filePath:await Dn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Sn(t,n,r){return{transcriptPath:e(t,n,r),contextSnapshotPath:h(t,n,r),toolResultsDir:S(t,n,r)}}function Cn(e,t,n){let r=Pn(e.startIndex,`startIndex`),i=Pn(e.endIndex,`endIndex`);if(r<0||i<r||i>t)throw Error(`Requested transcript range is outside transcript bounds 0..${t}.`);if(i-r>n)throw Error(`Requested transcript range exceeds maximum of ${n} entries.`);return{startIndex:r,endIndex:i}}function wn(e){let t=Mn(e.params),n=Cn(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=kn(r,t.maxBytes);return{kind:e.kind,range:n,entries:i.entries,entryCount:i.entries.length,rangeEntryCount:r.length,totalEntryCount:e.transcript.length,returnedBytes:i.returnedBytes,truncated:i.truncated,limits:t,contextFiles:Sn(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Tn(e,t){if(t.toolCallId&&t.storagePath){let n=e.find(e=>e.toolCallId===t.toolCallId&&e.storagePath===t.storagePath);if(n)return n;let r=e.some(e=>e.toolCallId===t.toolCallId),i=e.some(e=>e.storagePath===t.storagePath);if(r&&i)throw Error(`Requested toolCallId and storagePath do not reference the same tool result.`);return}return e.find(e=>t.toolCallId?e.toolCallId===t.toolCallId:e.storagePath===t.storagePath)}async function En(e,t,n){let[r,i]=await Promise.all([m(e,t,n),j(e,t,n)]),a=new Map;for(let e of r)Ln(e)&&e.toolResultRef?.sessionId===t&&a.set(Rn(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(Rn(e),e);return Array.from(a.values())}async function Dn(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(K.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=S(e.dataDir,e.sessionId,e.sessionOptions),n=d(e.dataDir,e.sessionId,e.sessionOptions),r=K.resolve(e.dataDir,e.reference.storagePath);if(!In(K.resolve(t),r))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!In(K.resolve(n),r))throw Error(`Referenced tool result is outside the session directory.`);let[i,a,o]=await Promise.all([Fn(t),Fn(n),Fn(r)]);if(!In(i,o))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!In(a,o))throw Error(`Referenced tool result resolves outside the session directory.`);return o}async function On(e,t){let n=await G.stat(e),r=await G.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:jn(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function kn(e,t){let n=[],r=0,i=!1;for(let a of e){let e={...a,content:``},o=Buffer.byteLength(JSON.stringify(e),`utf-8`);if(r+o>=t){i=!0;break}let s=t-r-o,c=An(a.content,s);c.truncated&&(i=!0);let l={...a,content:c.value},u=Buffer.byteLength(JSON.stringify(l),`utf-8`);if(n.push(l),r+=u,c.truncated)break}return n.length<e.length&&(i=!0),{entries:n,returnedBytes:r,truncated:i}}function An(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:jn(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function jn(e){let t=new Ge(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function Mn(e){return bn(e.limits)}function Nn(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function Pn(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function Fn(e){try{return await G.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${zn(e)}`)}}function In(e,t){let n=K.relative(e,t);return n===``||!n.startsWith(`..`)&&!K.isAbsolute(n)}function Ln(e){return e.role===`tool_result`}function Rn(e){return`${e.toolCallId}\n${e.storagePath}`}function zn(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Bn(e){return K.join(e,`.aimax`,`auto-skills`)}function Vn(e){return K.join(e,`categories.json`)}function Hn(e){return K.join(e,`.auto_skills_prompt_snapshot.json`)}const Un=/^[a-z0-9][a-z0-9-]*$/,Wn=/^[a-z0-9][a-z0-9-]*$/;function Y(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||K.win32.isAbsolute(t)||K.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!Un.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Gn(e){let t=e.trim();if(!t)throw Error(`Auto-skill name cannot be empty.`);if(t.length>80)throw Error(`Auto-skill name is too long.`);if(t.includes(`/`)||t.includes(`\\`)||t===`.`||t===`..`||t.startsWith(`.`)||!Wn.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Kn(e,t){return`auto:${Y(e)}/${Gn(t)}`}function qn(e){let t=e.trim();if(!t.startsWith(`auto:`))throw Error(`Invalid auto-skill id: ${e}`);let n=t.slice(5),r=n.indexOf(`/`);if(r<=0||r===n.length-1)throw Error(`Invalid auto-skill id: ${e}`);if(n.indexOf(`/`,r+1)!==-1)throw Error(`Auto-skill id category path must be a single slug.`);let i=Y(n.slice(0,r)),a=Gn(n.slice(r+1));return{skillId:Kn(i,a),categoryPath:i,skillName:a}}function Jn(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Yn(e,t,n){let r=K.resolve(e),i=K.resolve(r,...Y(t).split(`/`),Gn(n));return Zn(r,i),i}function Xn(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||K.win32.isAbsolute(n)||K.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=K.resolve(e),a=K.resolve(i,...r);return Zn(i,a),a}function Zn(e,t){let n=K.resolve(e),r=K.resolve(t),i=K.relative(n,r);if(i.startsWith(`..`)||K.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Qn(e){let t=Vn(e),n;try{n=await G.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=Y(e),r=er(t);return{path:n,name:n.split(`/`).at(-1)??n,description:r.description,createdBy:r.createdBy}}).sort((e,t)=>e.path.localeCompare(t.path))}function $n(e){return new Map(e.map(e=>[e.path,e]))}function er(e){return typeof e==`string`?{description:e.trim()}:!e||typeof e!=`object`||Array.isArray(e)?{description:``}:{description:typeof e.description==`string`?e.description.trim():``,createdBy:typeof e.createdBy==`string`?e.createdBy.trim():void 0}}const tr=32*1024,nr=new Map;function rr(e){return new ar(e)}async function ir(e){let t=K.resolve(e);for(let e of Array.from(nr.keys()))e.startsWith(`${t}|`)&&nr.delete(e);await G.rm(Hn(t),{force:!0}).catch(()=>{})}var ar=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Bn(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return sr($n((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Y(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>cr(e.categoryPath,t)).map(or)}async autoSkillSearch(e){let t=e.query.trim().toLowerCase();if(!t)return[];let n=Math.max(1,e.limit??5);return(await this.visibleEntries()).map(e=>({entry:e,score:lr(e,t)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||e.entry.skillId.localeCompare(t.entry.skillId)).slice(0,n).map(({entry:e,score:t})=>({...or(e),score:t}))}async autoSkillView(e){let t=qn(e.skillId),n=(await this.visibleEntries()).find(e=>e.skillId===t.skillId);if(!n)throw Error(`Unknown auto-skill: ${e.skillId}`);if(e.filePath?.trim()){let t=Xn(n.skillDir,e.filePath),r=await vr(t,this.maxResourceBytes);return{...or(n),status:n.status,content:r,path:xr(K.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:xr(K.relative(n.skillDir,t))}}let r=await vr(n.skillFile,this.maxSkillBytes);return{...or(n),status:n.status,content:r,path:xr(K.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await ur(this.rootDir),i=nr.get(n);if(!e&&i&&hr(i.manifest,r))return i;let a=e?void 0:await pr(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return nr.set(n,e),e}let o=await Qn(this.rootDir),s=$n(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return nr.set(n,c),await mr(this.rootDir,c).catch(()=>{}),c}async parseEntriesFromManifest(e){let t=e.filter(e=>e.kind===`skill`).map(e=>e.filePath),n=[];for(let e of t){let t=await this.loadEntry(e);t&&n.push(t)}return n.sort((e,t)=>e.skillId.localeCompare(t.skillId))}async visibleEntries(){let e=await this.loadIndex();return this.visibleEntriesFrom(e)}visibleEntriesFrom(e){return this.includeArchived?e:e.filter(e=>e.status===`active`)}optionsHash(){return wr({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:tr})}async loadEntry(e){try{let t=K.dirname(e),n=Gn(K.basename(t)),r=xr(K.relative(this.rootDir,t)),i=Y(K.posix.dirname(r)),a=Kn(i,n),o=K.join(t,`metadata.json`),s=await gr(o);if(s?.skillId&&qn(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Y(s.categoryPath)!==i)throw Error(`metadata categoryPath does not match path for ${a}`);if(s?.source&&s.source!==`auto`)throw Error(`metadata source must be auto for ${a}`);let c=Jn(s?.status);return{skillId:a,name:n,description:yr(await _r(e,tr)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:br(s?.tags),relatedSkills:br(s?.relatedSkills),confidence:typeof s?.confidence==`number`?s.confidence:void 0,createdAt:typeof s?.createdAt==`string`?s.createdAt:void 0,updatedAt:typeof s?.updatedAt==`string`?s.updatedAt:void 0}}catch(t){process.stderr.write(`[auto-skills] skipped ${e}: ${Sr(t)}\n`);return}}};function or(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function sr(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function cr(e,t){return t?e===t:!0}function lr(e,t){let n=t.split(/\s+/).filter(Boolean),r=e.name.toLowerCase(),i=e.description.toLowerCase(),a=e.categoryPath.toLowerCase(),o=e.tags.join(` `).toLowerCase(),s=0;r===t&&(s+=80),r.includes(t)&&(s+=30),i.includes(t)&&(s+=20),a.includes(t)&&(s+=10),o.includes(t)&&(s+=10);for(let e of n)r.includes(e)&&(s+=8),i.includes(e)&&(s+=5),a.includes(e)&&(s+=3),o.includes(e)&&(s+=3);return s}async function ur(e){let t;try{t=await G.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await fr(K.join(e,`categories.json`),`categories`,n),await dr(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function dr(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=K.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await fr(t,`skill`,n),await fr(K.join(e,`metadata.json`),`metadata`,n),await fr(K.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await G.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await dr(t,i,n)}}async function fr(e,t,n){try{let r=await G.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function pr(e,t,n){let r;try{r=await G.readFile(Hn(e),`utf-8`)}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=JSON.parse(r);return e.version!==1||e.optionsHash!==t||!Array.isArray(e.entries)||!Array.isArray(e.categories)||!Array.isArray(e.manifest)||!hr(e.manifest,n)?void 0:e}catch{return}}async function mr(e,t){if(!await Cr(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await G.writeFile(Hn(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function hr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.filePath!==i.filePath||r.kind!==i.kind||r.size!==i.size||r.mtimeMs!==i.mtimeMs)return!1}return!0}async function gr(e){try{let t=await G.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function _r(e,t){let n=await G.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function vr(e,t){if((await G.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return G.readFile(e,`utf-8`)}function yr(e){let t=He(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
10
- `)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function br(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function xr(e){return e.split(K.sep).join(`/`)}function Sr(e){return e instanceof Error?e.message:String(e)}async function Cr(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function wr(e){return Ue(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Tr(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}}}const Er=`/aimax/agents`,Dr=/^[a-z]+(?:-[a-z]+)*$/;function Or(e){let t=[{dir:e.systemAgentsDir??Er,source:`system`},{dir:K.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:K.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function kr(e){let t=new Map;for(let n of Or(e)){let e=await Nr(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function Ar(e={}){let t=e.allAgents??e.availableAgents??[],n=Lr(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Fr(n,e),findAny:e=>Fr(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function jr(e){return!!(e&&typeof e==`object`&&Array.isArray(e.allAgents)&&Array.isArray(e.availableAgents)&&typeof e.findPublic==`function`&&typeof e.findAny==`function`&&typeof e.stats==`function`)}async function Mr(e){return jr(e.agentPolicy)?e.agentPolicy:Ar({allAgents:await kr(e)})}async function Nr(e,t){let n;try{n=await G.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=K.join(e,i.name),a=Pr(await G.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function Pr(e,t){let n=He(e),r=Hr(n.data.name)?.trim(),i=Hr(n.data.description)?.trim();if(!r||!Dr.test(r)||!i)return;let a=Hr(n.data.model)?.trim(),o=Hr(n.data.initPrompt)?.trim()??Hr(n.data.initialPrompt)?.trim(),s=Ur(n.data.maxTurns),c=Wr(n.data.tools),l=Wr(n.data.disallowedTools),u=Wr(n.data.skills),d=Gr(n.data.visibility);if(!(n.data.visibility!==void 0&&!d))return{name:r,description:i,visibility:d??`public`,...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 Fr(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Ir(e)===`public`))}function Ir(e){return e.visibility??`public`}function Lr(e){return e.filter(e=>Ir(e)===`public`)}function Rr(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function zr(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Kr)):void 0,r=new Set((t.disallowedTools??[]).map(Kr));return e.filter(e=>{let t=typeof e.name==`string`?Kr(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Br(e){let t=Lr(e).filter(e=>e.source!==`system`);return t.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name exactly matches one of the listed custom agents, that mention is an explicit delegation request.","For such a matching `@<agent-name>` request, you MUST call `subagent_spawn` to run the request through that custom agent, with the `agent` field set to the exact matched agent name.","Do not answer the request yourself, do not merely describe the agent, and do not omit the tool call when a matching `@<agent-name>` is present.",`If the mention does not exactly match a listed custom agent, do not invent a match; continue with the current agent or ask a concise clarification if needed.`,t.map(e=>`- ${e.name}: ${e.description}`).join(`
6
+ `)}\n</available_skills>`}var zt=class{turn=null;wallClock={activeGoalId:null,lastAccountedAt:Date.now()};resetWallClock(){this.wallClock.lastAccountedAt=Date.now()}markActiveGoal(e,t,n){e&&(this.turn&&this.turn.turnId===e?(this.turn.activeGoalId=t,this.turn.lastTokenUsage=n):this.turn={turnId:e,activeGoalId:t,lastTokenUsage:n}),this.wallClock.activeGoalId!==t&&this.resetWallClock(),this.wallClock.activeGoalId=t}clearActiveGoal(){this.turn&&(this.turn.activeGoalId=null),this.wallClock.activeGoalId=null,this.resetWallClock()}tokenDeltaSinceLastAccounting(e){if(!this.turn||!this.turn.activeGoalId)return 0;let t=this.turn.lastTokenUsage;return Math.max(0,e.input-t.input)+Math.max(0,e.output-t.output)}timeDeltaSecondsSinceLastAccounting(){if(!this.wallClock.activeGoalId)return 0;let e=Date.now()-this.wallClock.lastAccountedAt;return Math.floor(e/1e3)}markAccounted(e,t){this.turn&&(this.turn.lastTokenUsage=e),t>0&&(this.wallClock.lastAccountedAt+=t*1e3),this.wallClock.lastAccountedAt>Date.now()&&(this.wallClock.lastAccountedAt=Date.now())}};async function Bt(e,t,n,r,i){let a=await z(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await I(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}function Vt(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function Ht(e,t){let n=Vt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed),a=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The user's thread goal is still active. Continue working toward the objective below.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Tokens remaining: ${a}`,`Time used: ${e.timeUsedSeconds}s`,``,`Rules:`,`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- Only call update_goal with status "complete" when the objective is fully achieved and verified.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress and the goal remains active.`,`- Do not inform the user about this continuation context; treat it as internal steering.`,``,`</goal_context>`].join(`
7
+ `)}function Ut(e,t){let n=Vt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed);return[`<goal_context>`,``,`The token budget for the current thread goal has been exhausted.`,`The goal status has been set to "budget_limited" automatically.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Instructions:`,`- Wrap up the current turn soon. Do not start new substantive work.`,`- Summarize progress made, any blockers, and what would be needed next.`,`- Do NOT call update_goal(complete) unless the objective is truly achieved.`,`- The user can increase the budget or resume the goal later via the CLI.`,``,`</goal_context>`].join(`
8
+ `)}function Wt(e,t){let n=Vt(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The thread goal objective has been edited by the user.`,`The following objective supersedes any previous thread goal objective.`,`Adjust your work direction accordingly.`,``,`<untrusted_objective>`,n,`</untrusted_objective>`,``,`Token budget: ${r}`,`Tokens remaining: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Do not call update_goal unless the updated goal is actually complete.`,``,`</goal_context>`].join(`
9
+ `)}function Gt(e){return{role:`user`,content:e}}function Kt(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const qt=`AIMAX_GOAL_CONTINUATION`;var Jt=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};function Yt(){let e=process.env[qt];return e===void 0||e===``||e!==`0`}async function Xt(e,t,n,r){if(!Yt()||n.continuationCount>=Ie)return!1;let i=await z(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-DjXWnxJY.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Zt(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Qt(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await Xt(n,r,a,{storeName:i}))return!1;let u=await z(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await V(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=Gt(p?Ut(u,f):Ht(u,f));a.continuationCount++;let h=await c(m.content);if(a.lastTurnHadOutput=Zt(h),p&&(a.budgetWrapUpDone=!0),l&&await l({input:h.inputTokens,output:h.outputTokens,total:h.inputTokens+h.outputTokens}),a.continuationCount>=Ie){let e=await z(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-DxaeZmiE.js`).then(e=>e.i),{appendGoalEvent:o}=await import(`./goal-events-Bdf1BDep.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${Ie}), goal paused`)}}return!0}async function $t(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function en(e,t,n,r){let i=await z(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Gt(Wt(i,await V(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function tn(e,t,n){(await z(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await I(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}async function nn(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function rn(e,t,n){let r=n.before?.status??null,i=n.after?.status??null,a=n.before?.goalId,o=n.after?.goalId;r===i&&a===o||await nn(e,t,{action:n.action,goal:n.after??null})}function an(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e)o.role===`user`?t+=1:o.role===`assistant`?n+=1:o.role===`tool_result`?r+=1:o.role===`compaction`?i+=1:a+=1;return{userTurnCount:t,assistantTurnCount:n,toolResultCount:r,compactionCount:i,otherEntryCount:a,totalEntryCount:e.length}}function on(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(mn(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}hn(a)&&(r+=1,a.isError&&(i+=1))}let a=Array.from(t).sort();return{toolCallCount:n,distinctToolCount:a.length,toolNames:a,toolResultCount:r,failedToolResultCount:i}}function sn(e,t={}){let n=fn(t.limit,`limit`),r=pn(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!hn(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:dn(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function cn(e,t){let n=pn(e,`totalEntryCount`);return typeof t!=`number`||!Number.isFinite(t)?{startIndex:0,endIndex:n}:{startIndex:Math.min(n,Math.max(0,Math.floor(t))),endIndex:n}}function ln(e,t=80){let n=pn(e,`totalEntryCount`),r=pn(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function un(e,t){return e.slice(t.startIndex,t.endIndex)}function dn(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function fn(e,t){return e===void 0?1/0:pn(e,t)}function pn(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function mn(e){return e.role===`assistant`}function hn(e){return e.role===`tool_result`}const gn=24e3;async function _n(e){return Tn({params:e,kind:`current_run`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function vn(e){return Tn({params:e,kind:`recent_conversation`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function yn(e){return Tn({params:e,kind:`transcript_range`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function bn(e){let t=Nn(e),n=await Sn(e),r=await kn(n.filePath,t.maxBytes);return{kind:`tool_result`,toolCallId:n.reference.toolCallId,toolName:n.reference.toolName,storagePath:n.reference.storagePath,content:r.content,originalBytes:r.originalBytes,returnedBytes:Buffer.byteLength(r.content,`utf-8`),truncated:r.truncated,limits:t,contextFiles:Cn(e.dataDir,e.sessionId,e.sessionOptions)}}function xn(e){return{maxEntries:Pn(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Pn(e?.maxBytes??gn,`limits.maxBytes`)}}async function Sn(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=En(await Dn(e.dataDir,e.sessionId,e.sessionOptions),{toolCallId:e.toolCallId,storagePath:e.storagePath});if(!t)throw Error(`Requested tool result is not referenced by this session transcript or context.`);return{reference:t,filePath:await On({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Cn(t,n,r){return{transcriptPath:e(t,n,r),contextSnapshotPath:h(t,n,r),toolResultsDir:S(t,n,r)}}function wn(e,t,n){let r=Fn(e.startIndex,`startIndex`),i=Fn(e.endIndex,`endIndex`);if(r<0||i<r||i>t)throw Error(`Requested transcript range is outside transcript bounds 0..${t}.`);if(i-r>n)throw Error(`Requested transcript range exceeds maximum of ${n} entries.`);return{startIndex:r,endIndex:i}}function Tn(e){let t=Nn(e.params),n=wn(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=An(r,t.maxBytes);return{kind:e.kind,range:n,entries:i.entries,entryCount:i.entries.length,rangeEntryCount:r.length,totalEntryCount:e.transcript.length,returnedBytes:i.returnedBytes,truncated:i.truncated,limits:t,contextFiles:Cn(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function En(e,t){if(t.toolCallId&&t.storagePath){let n=e.find(e=>e.toolCallId===t.toolCallId&&e.storagePath===t.storagePath);if(n)return n;let r=e.some(e=>e.toolCallId===t.toolCallId),i=e.some(e=>e.storagePath===t.storagePath);if(r&&i)throw Error(`Requested toolCallId and storagePath do not reference the same tool result.`);return}return e.find(e=>t.toolCallId?e.toolCallId===t.toolCallId:e.storagePath===t.storagePath)}async function Dn(e,t,n){let[r,i]=await Promise.all([m(e,t,n),j(e,t,n)]),a=new Map;for(let e of r)Rn(e)&&e.toolResultRef?.sessionId===t&&a.set(zn(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(zn(e),e);return Array.from(a.values())}async function On(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(G.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=S(e.dataDir,e.sessionId,e.sessionOptions),n=d(e.dataDir,e.sessionId,e.sessionOptions),r=G.resolve(e.dataDir,e.reference.storagePath);if(!Ln(G.resolve(t),r))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Ln(G.resolve(n),r))throw Error(`Referenced tool result is outside the session directory.`);let[i,a,o]=await Promise.all([In(t),In(n),In(r)]);if(!Ln(i,o))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Ln(a,o))throw Error(`Referenced tool result resolves outside the session directory.`);return o}async function kn(e,t){let n=await W.stat(e),r=await W.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:Mn(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function An(e,t){let n=[],r=0,i=!1;for(let a of e){let e={...a,content:``},o=Buffer.byteLength(JSON.stringify(e),`utf-8`);if(r+o>=t){i=!0;break}let s=t-r-o,c=jn(a.content,s);c.truncated&&(i=!0);let l={...a,content:c.value},u=Buffer.byteLength(JSON.stringify(l),`utf-8`);if(n.push(l),r+=u,c.truncated)break}return n.length<e.length&&(i=!0),{entries:n,returnedBytes:r,truncated:i}}function jn(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:Mn(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function Mn(e){let t=new Ke(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function Nn(e){return xn(e.limits)}function Pn(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function Fn(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function In(e){try{return await W.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Bn(e)}`)}}function Ln(e,t){let n=G.relative(e,t);return n===``||!n.startsWith(`..`)&&!G.isAbsolute(n)}function Rn(e){return e.role===`tool_result`}function zn(e){return`${e.toolCallId}\n${e.storagePath}`}function Bn(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Vn(e){return G.join(e,`.aimax`,`auto-skills`)}function Hn(e){return G.join(e,`categories.json`)}function Un(e){return G.join(e,`.auto_skills_prompt_snapshot.json`)}const Wn=/^[a-z0-9][a-z0-9-]*$/,Gn=/^[a-z0-9][a-z0-9-]*$/;function J(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||G.win32.isAbsolute(t)||G.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!Wn.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Kn(e){let t=e.trim();if(!t)throw Error(`Auto-skill name cannot be empty.`);if(t.length>80)throw Error(`Auto-skill name is too long.`);if(t.includes(`/`)||t.includes(`\\`)||t===`.`||t===`..`||t.startsWith(`.`)||!Gn.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function qn(e,t){return`auto:${J(e)}/${Kn(t)}`}function Jn(e){let t=e.trim();if(!t.startsWith(`auto:`))throw Error(`Invalid auto-skill id: ${e}`);let n=t.slice(5),r=n.indexOf(`/`);if(r<=0||r===n.length-1)throw Error(`Invalid auto-skill id: ${e}`);if(n.indexOf(`/`,r+1)!==-1)throw Error(`Auto-skill id category path must be a single slug.`);let i=J(n.slice(0,r)),a=Kn(n.slice(r+1));return{skillId:qn(i,a),categoryPath:i,skillName:a}}function Yn(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Xn(e,t,n){let r=G.resolve(e),i=G.resolve(r,...J(t).split(`/`),Kn(n));return Qn(r,i),i}function Zn(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||G.win32.isAbsolute(n)||G.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=G.resolve(e),a=G.resolve(i,...r);return Qn(i,a),a}function Qn(e,t){let n=G.resolve(e),r=G.resolve(t),i=G.relative(n,r);if(i.startsWith(`..`)||G.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function $n(e){let t=Hn(e),n;try{n=await W.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=J(e),r=tr(t);return{path:n,name:n.split(`/`).at(-1)??n,description:r.description,createdBy:r.createdBy}}).sort((e,t)=>e.path.localeCompare(t.path))}function er(e){return new Map(e.map(e=>[e.path,e]))}function tr(e){return typeof e==`string`?{description:e.trim()}:!e||typeof e!=`object`||Array.isArray(e)?{description:``}:{description:typeof e.description==`string`?e.description.trim():``,createdBy:typeof e.createdBy==`string`?e.createdBy.trim():void 0}}const nr=32*1024,rr=new Map;function ir(e){return new or(e)}async function ar(e){let t=G.resolve(e);for(let e of Array.from(rr.keys()))e.startsWith(`${t}|`)&&rr.delete(e);await W.rm(Un(t),{force:!0}).catch(()=>{})}var or=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=G.resolve(e.rootDir??Vn(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return cr(er((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?J(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>lr(e.categoryPath,t)).map(sr)}async autoSkillSearch(e){let t=e.query.trim().toLowerCase();if(!t)return[];let n=Math.max(1,e.limit??5);return(await this.visibleEntries()).map(e=>({entry:e,score:ur(e,t)})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score||e.entry.skillId.localeCompare(t.entry.skillId)).slice(0,n).map(({entry:e,score:t})=>({...sr(e),score:t}))}async autoSkillView(e){let t=Jn(e.skillId),n=(await this.visibleEntries()).find(e=>e.skillId===t.skillId);if(!n)throw Error(`Unknown auto-skill: ${e.skillId}`);if(e.filePath?.trim()){let t=Zn(n.skillDir,e.filePath),r=await yr(t,this.maxResourceBytes);return{...sr(n),status:n.status,content:r,path:Sr(G.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Sr(G.relative(n.skillDir,t))}}let r=await yr(n.skillFile,this.maxSkillBytes);return{...sr(n),status:n.status,content:r,path:Sr(G.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await dr(this.rootDir),i=rr.get(n);if(!e&&i&&gr(i.manifest,r))return i;let a=e?void 0:await mr(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return rr.set(n,e),e}let o=await $n(this.rootDir),s=er(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return rr.set(n,c),await hr(this.rootDir,c).catch(()=>{}),c}async parseEntriesFromManifest(e){let t=e.filter(e=>e.kind===`skill`).map(e=>e.filePath),n=[];for(let e of t){let t=await this.loadEntry(e);t&&n.push(t)}return n.sort((e,t)=>e.skillId.localeCompare(t.skillId))}async visibleEntries(){let e=await this.loadIndex();return this.visibleEntriesFrom(e)}visibleEntriesFrom(e){return this.includeArchived?e:e.filter(e=>e.status===`active`)}optionsHash(){return Tr({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:nr})}async loadEntry(e){try{let t=G.dirname(e),n=Kn(G.basename(t)),r=Sr(G.relative(this.rootDir,t)),i=J(G.posix.dirname(r)),a=qn(i,n),o=G.join(t,`metadata.json`),s=await _r(o);if(s?.skillId&&Jn(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&J(s.categoryPath)!==i)throw Error(`metadata categoryPath does not match path for ${a}`);if(s?.source&&s.source!==`auto`)throw Error(`metadata source must be auto for ${a}`);let c=Yn(s?.status);return{skillId:a,name:n,description:br(await vr(e,nr)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:xr(s?.tags),relatedSkills:xr(s?.relatedSkills),confidence:typeof s?.confidence==`number`?s.confidence:void 0,createdAt:typeof s?.createdAt==`string`?s.createdAt:void 0,updatedAt:typeof s?.updatedAt==`string`?s.updatedAt:void 0}}catch(t){process.stderr.write(`[auto-skills] skipped ${e}: ${Cr(t)}\n`);return}}};function sr(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function cr(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function lr(e,t){return t?e===t:!0}function ur(e,t){let n=t.split(/\s+/).filter(Boolean),r=e.name.toLowerCase(),i=e.description.toLowerCase(),a=e.categoryPath.toLowerCase(),o=e.tags.join(` `).toLowerCase(),s=0;r===t&&(s+=80),r.includes(t)&&(s+=30),i.includes(t)&&(s+=20),a.includes(t)&&(s+=10),o.includes(t)&&(s+=10);for(let e of n)r.includes(e)&&(s+=8),i.includes(e)&&(s+=5),a.includes(e)&&(s+=3),o.includes(e)&&(s+=3);return s}async function dr(e){let t;try{t=await W.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await pr(G.join(e,`categories.json`),`categories`,n),await fr(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function fr(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=G.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await pr(t,`skill`,n),await pr(G.join(e,`metadata.json`),`metadata`,n),await pr(G.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await W.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await fr(t,i,n)}}async function pr(e,t,n){try{let r=await W.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function mr(e,t,n){let r;try{r=await W.readFile(Un(e),`utf-8`)}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=JSON.parse(r);return e.version!==1||e.optionsHash!==t||!Array.isArray(e.entries)||!Array.isArray(e.categories)||!Array.isArray(e.manifest)||!gr(e.manifest,n)?void 0:e}catch{return}}async function hr(e,t){if(!await wr(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await W.writeFile(Un(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function gr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.filePath!==i.filePath||r.kind!==i.kind||r.size!==i.size||r.mtimeMs!==i.mtimeMs)return!1}return!0}async function _r(e){try{let t=await W.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function vr(e,t){let n=await W.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function yr(e,t){if((await W.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return W.readFile(e,`utf-8`)}function br(e){let t=Ue(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
10
+ `)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function xr(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Sr(e){return e.split(G.sep).join(`/`)}function Cr(e){return e instanceof Error?e.message:String(e)}async function wr(e){try{return await W.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Tr(e){return We(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Er(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}}}const Dr=`/aimax/agents`,Or=/^[a-z]+(?:-[a-z]+)*$/;function kr(e){let t=[{dir:e.systemAgentsDir??Dr,source:`system`},{dir:G.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:G.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function Ar(e){let t=new Map;for(let n of kr(e)){let e=await Pr(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function jr(e={}){let t=e.allAgents??e.availableAgents??[],n=Rr(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Ir(n,e),findAny:e=>Ir(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function Mr(e){return!!(e&&typeof e==`object`&&Array.isArray(e.allAgents)&&Array.isArray(e.availableAgents)&&typeof e.findPublic==`function`&&typeof e.findAny==`function`&&typeof e.stats==`function`)}async function Nr(e){return Mr(e.agentPolicy)?e.agentPolicy:jr({allAgents:await Ar(e)})}async function Pr(e,t){let n;try{n=await W.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=G.join(e,i.name),a=Fr(await W.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function Fr(e,t){let n=Ue(e),r=Ur(n.data.name)?.trim(),i=Ur(n.data.description)?.trim();if(!r||!Or.test(r)||!i)return;let a=Ur(n.data.model)?.trim(),o=Ur(n.data.initPrompt)?.trim()??Ur(n.data.initialPrompt)?.trim(),s=Wr(n.data.maxTurns),c=Gr(n.data.tools),l=Gr(n.data.disallowedTools),u=Gr(n.data.skills),d=Kr(n.data.visibility);if(!(n.data.visibility!==void 0&&!d))return{name:r,description:i,visibility:d??`public`,...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 Ir(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Lr(e)===`public`))}function Lr(e){return e.visibility??`public`}function Rr(e){return e.filter(e=>Lr(e)===`public`)}function zr(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Br(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(qr)):void 0,r=new Set((t.disallowedTools??[]).map(qr));return e.filter(e=>{let t=typeof e.name==`string`?qr(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Vr(e){let t=Rr(e).filter(e=>e.source!==`system`);return t.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name exactly matches one of the listed custom agents, that mention is an explicit delegation request.","For such a matching `@<agent-name>` request, you MUST call `subagent_spawn` to run the request through that custom agent, with the `agent` field set to the exact matched agent name.","Do not answer the request yourself, do not merely describe the agent, and do not omit the tool call when a matching `@<agent-name>` is present.",`If the mention does not exactly match a listed custom agent, do not invent a match; continue with the current agent or ask a concise clarification if needed.`,t.map(e=>`- ${e.name}: ${e.description}`).join(`
11
11
  `),``].join(`
12
- `)}function Vr(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Hr(e){return typeof e==`string`?e:void 0}function Ur(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Wr(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 Gr(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Kr(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}const qr=new qe;async function Jr(e,t){return await qr.run(e,t)}function Yr(e){return{async emit(t){let n=qr.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})}}}var Xr=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 Jr({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}},Zr=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})}},Qr=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 $r(e){return{async chat(t){let n=ei(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await ri(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:ti(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}=ii(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 oi(e,s())}if(!t.ok){let e=await ai(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new Qr({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:ci(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new Qr({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=ni(o.usage),u=Math.max(0,Date.now()-n);return await ri(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 ei(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 ti(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
13
- `)}function ni(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 ri(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function ii(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 ai(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function oi(e,t){return e instanceof Qr?e:si(e)?t?new Qr({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new Qr({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function si(e){return e instanceof Error&&e.name===`AbortError`}function ci(e){return e===408||e===409||e===425||e===429||e>=500}var li=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 ui(e){return!!(e instanceof li||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var di=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 fi(e){return!!(e instanceof di||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const pi=new qe;function mi(){return{}}async function hi(e,t){return await pi.run(e,t)}function gi(e){let t=pi.getStore();!t||t.signal||(t.signal=e)}const _i=new qe;function vi(){return{}}async function yi(e,t){return await _i.run(e,t)}function bi(e){let t=_i.getStore();!t||t.signal||(t.signal=e)}function xi(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Si(e){if(!xi(e))return null;let t=e,n=Ci(t.message),r=Ti(n?.code)??Ti(t.code),i=Ti(n?.type)??Ti(t.type),a=Ti(n?.message)??wi(t.error)??Ti(t.message)??`Unknown upstream error`;return{message:Ei(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Di(r,i),raw:e}}function Ci(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 wi(e){if(!(!e||typeof e!=`object`))return Ti(e.message)}function Ti(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Ei(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Di(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 Oi=(e,t,n)=>{let r=new tt;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=ji(e,t,n?.apiKey||Xe(e.provider)||``,n?.headers),o=Mi(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=Ze(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=Si(t);if(n)throw new Qr({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}},Ye(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=Ri(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=Ze(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 Qr&&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},ki=(e,t,n)=>{let r=n?.apiKey||Xe(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=at(e,n,r),a=et(e)?n?.reasoning:ot(n?.reasoning);return Oi(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function Ai(e,t,n){return Mi(e,t,n)}function ji(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=it(t.messages);Object.assign(i,rt({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new Je({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Mi(e,t,n){let r=Bi(e),i=Ii(e,t,r);Fi(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=Li(t.tools,r):Ni(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 Ni(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 Pi(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 Fi(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 Ii(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Pi(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=st(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:nt(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:nt(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:nt(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=>nt(e.text)).join(``):a.map(e=>({type:`text`,text:nt(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(`
12
+ `)}function Hr(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Ur(e){return typeof e==`string`?e:void 0}function Wr(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Gr(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 Kr(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function qr(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}const Jr=new Je;async function Yr(e,t){return await Jr.run(e,t)}function Xr(e){return{async emit(t){let n=Jr.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})}}}var Zr=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 Yr({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}},Qr=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})}},Y=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 $r(e){return{async chat(t){let n=ti(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await ii(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:ni(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}=ai(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 si(e,s())}if(!t.ok){let e=await oi(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new Y({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:li(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw ei(e,s())}let c=o.choices?.[0]?.message?.content??o.choices?.[0]?.text??``,l=ri(o.usage),u=Math.max(0,Date.now()-n);return await ii(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 ei(e,t){return ci(e)&&t?new Y({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):ci(e)?new Y({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new Y({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function ti(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 ni(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
13
+ `)}function ri(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 ii(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function ai(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 oi(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function si(e,t){return e instanceof Y?e:ci(e)?t?new Y({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new Y({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function ci(e){return e instanceof Error&&e.name===`AbortError`}function li(e){return e===408||e===409||e===425||e===429||e>=500}var ui=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 di(e){return!!(e instanceof ui||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var fi=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 pi(e){return!!(e instanceof fi||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const mi=new Je;function hi(){return{}}async function gi(e,t){return await mi.run(e,t)}function _i(e){let t=mi.getStore();!t||t.signal||(t.signal=e)}const vi=new Je;function yi(){return{}}async function bi(e,t){return await vi.run(e,t)}function xi(e){let t=vi.getStore();!t||t.signal||(t.signal=e)}function Si(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Ci(e){if(!Si(e))return null;let t=e,n=wi(t.message),r=Ei(n?.code)??Ei(t.code),i=Ei(n?.type)??Ei(t.type),a=Ei(n?.message)??Ti(t.error)??Ei(t.message)??`Unknown upstream error`;return{message:Di(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Oi(r,i),raw:e}}function wi(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 Ti(e){if(!(!e||typeof e!=`object`))return Ei(e.message)}function Ei(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Di(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Oi(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 ki=(e,t,n)=>{let r=new nt;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=Mi(e,t,n?.apiKey||Ze(e.provider)||``,n?.headers),o=Ni(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=Qe(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=Ci(t);if(n)throw new Y({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}},Xe(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=zi(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=Qe(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 Y&&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},Ai=(e,t,n)=>{let r=n?.apiKey||Ze(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=ot(e,n,r),a=tt(e)?n?.reasoning:st(n?.reasoning);return ki(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function ji(e,t,n){return Ni(e,t,n)}function Mi(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=at(t.messages);Object.assign(i,it({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new Ye({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Ni(e,t,n){let r=Vi(e),i=Li(e,t,r);Ii(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=Ri(t.tools,r):Pi(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 Pi(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 Fi(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 Ii(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 Li(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Fi(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=ct(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:rt(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:rt(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:rt(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=>rt(e.text)).join(``):a.map(e=>({type:`text`,text:rt(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(`
14
14
 
15
15
  `);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(`
16
16
  `))}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(`
17
- `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:nt(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 Li(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function Ri(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 zi(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 Bi(e){let t=zi(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}const Vi=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Hi=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]);function Ui(e){let t=qi(e?.maxAttempts,3),n=Ji(e?.initialDelayMs,250),r=Ji(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Wi(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Gi(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 Ki(e){if(Zi(e))return!1;let t=Yi(e),n=Xi(e);if(t?.statusCode!==void 0)return $i(t.statusCode);if(t?.providerCode!==void 0)return Qi(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Vi.has(e))return!0;if(Hi.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;let r=ea(t?.message??n);return r===void 0?t?.retryable===!0:$i(r)}function qi(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function Ji(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Yi(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 Xi(e){if(typeof e==`string`)return e;if(e instanceof Error&&typeof e.message==`string`||e&&typeof e==`object`&&typeof e.message==`string`)return e.message}function Zi(e){return Yi(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function Qi(e){return/^\d+$/.test(e)?$i(Number(e)):!1}function $i(e){return e===408||e===409||e===425||e===429||e>=500}function ea(e){if(!e||!e.includes(`LLM upstream returned an error payload in a 200 stream:`))return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function ta(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 na(e=new Date){let t=ta(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let ra=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),ia=null;function aa(){return na()}function oa(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 sa(e){return K.join(e,`.aimax`)}function ca(e){return{appLogPath:K.join(e,`app.log`),errorLogPath:K.join(e,`errors.log`)}}function la(e){let{appLogPath:t,errorLogPath:n}=ca(e);ct.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 ua(e,t,n){return`[${aa()}] [${e}] ${t}${oa(n)}`}function da(e,t,n){process.stderr.write(`${ua(e,t,n)}\n`)}function fa(e,t,n){if(!ia){da(e,t,n);return}let r=ua(e,t,n),i=ct.getLogger();if(e===ra.ERROR){i.error(r);return}if(e===ra.WARN){i.warn(r);return}i.info(r)}function pa(e){let t=sa(e);ia?.dataDir!==e&&(J.mkdirSync(t,{recursive:!0}),la(t),ia={dataDir:e,logDir:t})}const X={info:(e,t)=>fa(ra.INFO,e,t),warn:(e,t)=>fa(ra.WARN,e,t),error:(e,t)=>fa(ra.ERROR,e,t)};function ma(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}async function ha(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=mi(),D=vi(),O=new Set,k=Promise.resolve(),ee,A=e=>{O.add(e),e.catch(e=>{ee??=e}).finally(()=>{O.delete(e)})},j=async()=>{for(;O.size>0;)await Promise.allSettled([...O]);if(ee)throw ee},te=t.subscribe(e=>{let t=k.then(()=>M(e));k=t.catch(()=>{}),A(t)});async function M(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=Ia(`partial`in t?t.partial:void 0)??Ia(`message`in t?t.message:void 0)??Ia(`message`in e?e.message:void 0),a=La(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=Pa(e);let r=La(``,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=Pa(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,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(y=Ca(t));let r=(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:Ma(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),a=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),o=new Set(r.map(e=>e.toolCallId));for(let e of w.values())!o.has(e.toolCallId)&&a.has(e.toolCallId)&&r.push(e);for(let e of r)w.delete(e.toolCallId);if(S.push({message:t,toolResults:r}),f&&!n){let e=!!E.signal,n=!!D.signal;if(e&&E.signal.transparentPause||await f(Aa(ka(t),e||n),n?[]:r.map(ja)),e||n)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=Fa(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Ma(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 N=Ui(d),P=N.enabled?N.maxAttempts:1;try{ga({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=P;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`);X.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,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 hi(E,async()=>{await yi(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=Ra(x),X.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,error:v}),await I(x,v,e,d))continue;await L(v,x),await s.dispatchProgress(i,{type:`error`,message:v})}v||X.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,inputTokens:g,outputTokens:_,turnRecordCount:S.length-d,textLength:p.length});break}catch(t){if(await j(),ui(t)||fi(t))throw t;if(v=Ra(t),X.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,error:v}),await I(t,v,e,d))continue;await L(v,t),await s.dispatchProgress(i,{type:`error`,message:v});break}}}finally{te()}function F(){p=``,m=``,h=``}async function I(e,n,r,a){if(!ya({error:e,attempt:r,maxAttempts:P,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=Wi(r,N);return X.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:P,delayMs:o,error:n}),await Ea({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:P,message:n,delayMs:o}),S.length=a,F(),Da(t),await Gi(o,u),!0}async function L(e,t){f&&await f(xa(e,t),[])}let R=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:R,durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:{input:g,output:_,total:g+_}},l);let z=(D.signal?``:S.length>0?Pa(S[S.length-1].message):``)||p||Sa(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return f&&!ba(S)&&!v&&p.trim().length>0&&await f({role:`assistant`,content:p,timestamp:new Date().toISOString()},[]),{text:z,inputTokens:g,outputTokens:_,error:v,turnRecords:S}}function ga(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model;if(!n||typeof n.id!=`string`)return;let r=typeof t?.systemPrompt==`string`?t.systemPrompt:``,i=Array.isArray(t?.messages)?[...t.messages]:[],a=e.continueFromHistory?i:_a(i,e.message),o=va(t?.tools);try{let t=Ai(n,{systemPrompt:r,messages:a,tools:o.length>0?o.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},{});e.eventDispatcher.dispatchProgress(e.sessionId,{type:`model_request`,model:n.id,provider:typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`,systemPrompt:r,tools:o,requestJson:t})}catch{}}function _a(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function va(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e).flatMap(e=>{let t=typeof e.name==`string`?e.name:``;return t?[{name:t,description:typeof e.description==`string`?e.description:void 0,parameters:e.parameters}]:[]}):[]}function ya(e){return e.attempt>=e.maxAttempts||!Ki(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&&Pa(e.message).trim().length===0)}function ba(e){return e.some(e=>ka(e.message)!==null||e.toolResults.length>0)}function xa(e,t){return{role:`assistant`,content:e,stopReason:(t&&typeof t==`object`?t.code:void 0)===`aborted`||e===`aborted`?`aborted`:`error`,errorMessage:e,timestamp:new Date().toISOString()}}function Sa(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 Ca(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:wa(t.errorCode),statusCode:Ta(t.statusCode),providerCode:wa(t.providerCode),providerType:wa(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function wa(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Ta(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Ea(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 Da(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&Oa(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function Oa(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function ka(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 Aa(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function ja(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 Ma(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:Na(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Na(e){let t=e.indexOf(`
17
+ `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:rt(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 Ri(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function zi(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 Bi(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 Vi(e){let t=Bi(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}const Hi=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Ui=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]);function Wi(e){let t=Ji(e?.maxAttempts,3),n=Yi(e?.initialDelayMs,250),r=Yi(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Gi(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Ki(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 qi(e){if(Qi(e))return!1;let t=Xi(e),n=Zi(e);if(t?.statusCode!==void 0)return ea(t.statusCode);if(t?.providerCode!==void 0)return $i(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Hi.has(e))return!0;if(Ui.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;let r=ta(t?.message??n);return r===void 0?t?.retryable===!0:ea(r)}function Ji(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function Yi(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Xi(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 Zi(e){if(typeof e==`string`)return e;if(e instanceof Error&&typeof e.message==`string`||e&&typeof e==`object`&&typeof e.message==`string`)return e.message}function Qi(e){return Xi(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function $i(e){return/^\d+$/.test(e)?ea(Number(e)):!1}function ea(e){return e===408||e===409||e===425||e===429||e>=500}function ta(e){if(!e||!e.includes(`LLM upstream returned an error payload in a 200 stream:`))return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function na(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 ra(e=new Date){let t=na(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let ia=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),aa=null;function oa(){return ra()}function sa(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 ca(e){return G.join(e,`.aimax`)}function la(e){return{appLogPath:G.join(e,`app.log`),errorLogPath:G.join(e,`errors.log`)}}function ua(e){let{appLogPath:t,errorLogPath:n}=la(e);lt.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 da(e,t,n){return`[${oa()}] [${e}] ${t}${sa(n)}`}function fa(e,t,n){process.stderr.write(`${da(e,t,n)}\n`)}function pa(e,t,n){if(!aa){fa(e,t,n);return}let r=da(e,t,n),i=lt.getLogger();if(e===ia.ERROR){i.error(r);return}if(e===ia.WARN){i.warn(r);return}i.info(r)}function ma(e){let t=ca(e);aa?.dataDir!==e&&(q.mkdirSync(t,{recursive:!0}),ua(t),aa={dataDir:e,logDir:t})}const X={info:(e,t)=>pa(ia.INFO,e,t),warn:(e,t)=>pa(ia.WARN,e,t),error:(e,t)=>pa(ia.ERROR,e,t)};function ha(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}async function ga(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=hi(),D=yi(),O=new Set,k=Promise.resolve(),ee,A=e=>{O.add(e),e.catch(e=>{ee??=e}).finally(()=>{O.delete(e)})},j=async()=>{for(;O.size>0;)await Promise.allSettled([...O]);if(ee)throw ee},M=t.subscribe(e=>{let t=k.then(()=>te(e));k=t.catch(()=>{}),A(t)});async function te(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=La(`partial`in t?t.partial:void 0)??La(`message`in t?t.message:void 0)??La(`message`in e?e.message:void 0),a=Ra(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=Fa(e);let r=Ra(``,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=Fa(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,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(y=wa(t));let r=(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:Na(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),a=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),o=new Set(r.map(e=>e.toolCallId));for(let e of w.values())!o.has(e.toolCallId)&&a.has(e.toolCallId)&&r.push(e);for(let e of r)w.delete(e.toolCallId);if(S.push({message:t,toolResults:r}),f&&!n){let e=!!E.signal,n=!!D.signal;if(e&&E.signal.transparentPause||await f(ja(Aa(t),e||n),n?[]:r.map(Ma)),e||n)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=Ia(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Na(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 ne=Wi(d),N=ne.enabled?ne.maxAttempts:1;try{_a({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=N;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`);X.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:N,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 gi(E,async()=>{await bi(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=za(x),X.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:N,error:v}),await F(x,v,e,d))continue;await I(v,x),await s.dispatchProgress(i,{type:`error`,message:v})}v||X.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:N,inputTokens:g,outputTokens:_,turnRecordCount:S.length-d,textLength:p.length});break}catch(t){if(await j(),di(t)||pi(t))throw t;if(v=za(t),X.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:N,error:v}),await F(t,v,e,d))continue;await I(v,t),await s.dispatchProgress(i,{type:`error`,message:v});break}}}finally{M()}function P(){p=``,m=``,h=``}async function F(e,n,r,a){if(!ba({error:e,attempt:r,maxAttempts:N,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=Gi(r,ne);return X.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:N,delayMs:o,error:n}),await Da({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:N,message:n,delayMs:o}),S.length=a,P(),Oa(t),await Ki(o,u),!0}async function I(e,t){f&&await f(Sa(e,t),[])}let L=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:L,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?Fa(S[S.length-1].message):``)||p||Ca(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return f&&!xa(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 _a(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model;if(!n||typeof n.id!=`string`)return;let r=typeof t?.systemPrompt==`string`?t.systemPrompt:``,i=Array.isArray(t?.messages)?[...t.messages]:[],a=e.continueFromHistory?i:va(i,e.message),o=ya(t?.tools);try{let t=ji(n,{systemPrompt:r,messages:a,tools:o.length>0?o.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},{});e.eventDispatcher.dispatchProgress(e.sessionId,{type:`model_request`,model:n.id,provider:typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`,systemPrompt:r,tools:o,requestJson:t})}catch{}}function va(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function ya(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e).flatMap(e=>{let t=typeof e.name==`string`?e.name:``;return t?[{name:t,description:typeof e.description==`string`?e.description:void 0,parameters:e.parameters}]:[]}):[]}function ba(e){return e.attempt>=e.maxAttempts||!qi(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&&Fa(e.message).trim().length===0)}function xa(e){return e.some(e=>Aa(e.message)!==null||e.toolResults.length>0)}function Sa(e,t){return{role:`assistant`,content:e,stopReason:(t&&typeof t==`object`?t.code:void 0)===`aborted`||e===`aborted`?`aborted`:`error`,errorMessage:e,timestamp:new Date().toISOString()}}function Ca(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 wa(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:Ta(t.errorCode),statusCode:Ea(t.statusCode),providerCode:Ta(t.providerCode),providerType:Ta(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function Ta(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Ea(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Da(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 Oa(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&ka(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function ka(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function Aa(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 ja(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Ma(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 Na(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:Pa(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Pa(e){let t=e.indexOf(`
18
18
  Preview:
19
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Pa(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Fa(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 Ia(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 La(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Ra(e){let t=za(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 za(e){if(e instanceof Qr)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:wa(t.code),statusCode:Ta(t.statusCode),statusText:wa(t.statusText),providerMessage:wa(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 Ba(e){let t=Ka(e.toolResultPreviewChars),n=qa(e.systemPrompt,e.agentDefinition),r=Ya(e.model,e.agentDefinition),i=zr(e.tools??[],e.agentDefinition),a=Ja(e.message,e.agentDefinition),o=await ha({agent:new Ke({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:Va({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new Xr,hookCtx:{sessionId:e.sessionId},abortSignal:e.abortSignal});return{text:o.text,usage:{input:o.inputTokens,output:o.outputTokens,total:o.inputTokens+o.outputTokens},error:o.error,toolCalls:Ua(o.turnRecords),toolResults:Wa(o.turnRecords,t)}}function Va(e){let t=e.phasePrefix??`silent_agent`;return new Zr({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await Ha(e.diagnosticDispatcher,t,n)}})}async function Ha(e,t,n){let r=n.sessionId;if(r){if(n.type===`stream_text_delta`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_stream`,message:`silent agent streamed text`,details:{textLength:n.text.length}});return}if(n.type===`tool_start`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_tool_started`,message:`silent agent tool started`,details:{toolCallId:n.toolCallId,toolName:n.name,input:n.input}});return}if(n.type===`tool_end`){await e.dispatchDiagnostic(r,{level:n.isError?`warn`:`info`,scope:`skill`,phase:`${t}_tool_completed`,message:n.isError?`silent agent tool failed`:`silent agent tool completed`,details:{toolCallId:n.toolCallId,toolName:n.name,isError:n.isError}});return}if(n.type===`error`){await e.dispatchDiagnostic(r,{level:`warn`,scope:`skill`,phase:`${t}_error`,message:`silent agent reported error`,details:{error:n.message}});return}n.type===`diagnostic`&&await e.dispatchDiagnostic(r,{level:n.level,scope:n.scope,phase:`${t}_${n.phase}`,message:n.message,...n.details?{details:n.details}:{}})}}function Ua(e){let t=[];for(let n of e)for(let e of n.message.content)e.type===`toolCall`&&t.push({id:e.id,name:e.name,arguments:e.arguments??{}});return t}function Wa(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Ga(e.content,t)})))}function Ga(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function Ka(e){let t=e??800;if(!Number.isFinite(t))throw Error(`toolResultPreviewChars must be a finite non-negative integer.`);return Math.max(0,Math.floor(t))}function qa(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
20
-
21
- `)}function Ja(e,t){return!t?.initPrompt||typeof e!=`string`?e:Vr(t,e)}function Ya(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}var Xa=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Bn(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=Y(e.path),n=no(e.description,`category description`),r=await this.readCategoryRegistry();if(r[t])throw Error(`Auto-skill category already exists: ${t}`);return r[t]={description:n,createdBy:e.createdBy?.trim()||`review-agent`},await this.writeCategoryRegistry(r),await ir(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:Vn(this.rootDir)}}async createSkill(e){let t=Gn(e.name),n=Y(e.categoryPath),r=no(e.description,`auto-skill description`),i=ro(e.body);await this.assertCategoryExists(n);let a=Kn(n,t),o=Yn(this.rootDir,n,t);if(await eo(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=K.join(o,`SKILL.md`),l=K.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:io(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:ao(e.evidence,s)};return await G.mkdir(o,{recursive:!0}),await G.writeFile(c,Za(t,r,i),`utf-8`),await to(l,u),await ir(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=qn(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Yn(this.rootDir,t.categoryPath,t.skillName),r=K.join(n,`SKILL.md`),i=K.join(n,`metadata.json`),a=await Qa(r),o=await $a(i),s=e.description===void 0?a.description:no(e.description,`auto-skill description`),c=e.body===void 0?a.body:ro(e.body),l=this.now().toISOString(),u={...o,skillId:t.skillId,status:o.status===`archived`?`archived`:`active`,categoryPath:t.categoryPath,source:`auto`,tags:e.tags===void 0?io(o.tags):io(e.tags),confidence:e.confidence??o.confidence,createdAt:typeof o.createdAt==`string`?o.createdAt:l,updatedAt:l,review:{...typeof o.review==`object`&&o.review!==null?o.review:{},...ao(e.evidence,l)}};return await G.writeFile(r,Za(t.skillName,s,c),`utf-8`),await to(i,u),await ir(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=qn(e.skillId),n=Yn(this.rootDir,t.categoryPath,t.skillName),r=K.join(n,`metadata.json`),i=K.join(n,`SKILL.md`);await G.access(i);let a=await $a(r),o=this.now().toISOString();return await to(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...ao(e.evidence,o)}}),await ir(this.rootDir),{action:`archive`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:i,metadataFile:r}}async assertCategoryExists(e){if(!(await this.readCategoryRegistry())[e])throw Error(`Unknown auto-skill category: ${e}. Create it first with create_category.`)}async readCategoryRegistry(){let e=Vn(this.rootDir),t;try{t=await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=Y(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await G.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await to(Vn(this.rootDir),t)}};function Za(e,t,n){return[`---`,`name: ${oo(e)}`,`description: ${oo(t)}`,`---`,``,n.trim(),``].join(`
22
- `)}async function Qa(e){let t=He(await G.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function $a(e){let t;try{t=await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}async function eo(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function to(e,t){await G.mkdir(K.dirname(e),{recursive:!0}),await G.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function no(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function ro(e){let t=e.trim();if(!t)throw Error(`Auto-skill body cannot be empty.`);if(t.length<20)throw Error(`Auto-skill body is too short to be useful.`);if(t.startsWith(`---`))throw Error(`Auto-skill body must not include frontmatter; metadata is generated by the store.`);return t}function io(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function ao(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function oo(e){return JSON.stringify(e)}const so=[`create`,`update`,`archive`,`create_category`],co=q.Object({}),lo=q.Object({categoryPath:q.Optional(q.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:q.Optional(q.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),uo=q.Object({query:q.String({description:`Search query for learned auto-skills.`}),limit:q.Optional(q.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),fo=q.Object({skillId:q.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:q.Optional(q.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),po=q.Object({action:q.Union(so.map(e=>q.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:q.Optional(q.String({description:`Exact auto-skill id for update/archive.`})),name:q.Optional(q.String({description:`Auto-skill slug for create.`})),categoryPath:q.Optional(q.String({description:`Existing single-level category slug for create.`})),newCategory:q.Optional(q.Object({path:q.String({description:`New single-level category slug to create.`}),description:q.String({description:`New category description.`})})),description:q.Optional(q.String({description:`Auto-skill description for create/update.`})),tags:q.Optional(q.Array(q.String({description:`Auto-skill tag.`}))),confidence:q.Optional(q.Number({description:`Optional confidence score from 0 to 1.`})),body:q.Optional(q.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:q.Optional(q.Object({sessionId:q.String({description:`Source session id.`}),reason:q.String({description:`Why this auto-skill write is justified.`}),toolCallCount:q.Optional(q.Number({description:`Tool calls observed in source run.`})),loadedSkills:q.Optional(q.Array(q.String({description:`Skill loaded during source run.`})))}))});function mo(e){let t=new ar({dataDir:e});return{name:`auto_skill_categories`,label:`Auto-Skill Categories`,description:`List learned auto-skill categories. Use before auto_skill_list when learned workflows may help.`,parameters:co,async execute(){try{let e=await t.autoSkillCategories();return Z({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return Z({categories:[],count:0,error:bo(e)})}}}}function ho(e){let t=new ar({dataDir:e});return{name:`auto_skill_list`,label:`Auto-Skill List`,description:`List active learned auto-skills by category without loading SKILL.md content.`,parameters:lo,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return Z({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Z({skills:[],count:0,error:bo(e)})}}}}function go(e){let t=new ar({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:uo,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return Z({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Z({skills:[],count:0,error:bo(e)})}}}}function _o(e){let t=new ar({dataDir:e});return{name:`auto_skill_view`,label:`Auto-Skill View`,description:`Load an active learned auto-skill by exact skillId, or read a file inside that auto-skill directory.`,parameters:fo,async execute(e,n){try{return Z({...await t.autoSkillView({skillId:n.skillId,filePath:n.filePath}),usage_hint:n.filePath?`This returned one file inside the auto-skill directory.`:`This returns SKILL.md. If it references helper files, call auto_skill_view({ skillId, filePath }) for only the needed file.`})}catch(e){return Z({skillId:n.skillId,error:bo(e)})}}}}function vo(e){let t=new Xa({dataDir:e});return{name:`auto_skill_manage`,label:`Auto-Skill Manage`,description:`Restricted review-agent tool for creating, updating, archiving learned auto-skills, or creating categories. Do not expose this tool to the main user-facing agent.`,parameters:po,async execute(e,n){try{return Z(await yo(t,n))}catch(e){return Z({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:bo(e)})}}}}async function yo(e,t){if(t.action===`create_category`){if(!t.newCategory)throw Error(`create_category requires newCategory.`);return e.createCategory({path:t.newCategory.path,description:t.newCategory.description})}if(t.action===`create`){if(!t.name||!t.categoryPath||!t.description||!t.body)throw Error(`create requires name, categoryPath, description, and body.`);return e.createSkill({name:t.name,categoryPath:t.categoryPath,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(t.action===`update`){if(!t.skillId)throw Error(`update requires skillId.`);return e.updateSkill({skillId:t.skillId,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(!t.skillId)throw Error(`archive requires skillId.`);return e.archiveSkill({skillId:t.skillId,evidence:t.evidence})}function Z(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function bo(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const xo=q.Object({kind:q.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>q.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:q.Optional(q.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:q.Optional(q.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:q.Optional(q.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:q.Optional(q.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function So(e){let t=bn({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??hn}),n={storeName:e.storeName};return{name:`auto_skill_review_context_view`,label:`Auto-Skill Review Context`,description:`Internal read-only review tool for controlled access to the current session transcript and persisted tool-result evidence. Only use inside the auto-skill review agent.`,parameters:xo,async execute(r,i){try{return i.kind===`tool_result`?wo(await yn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?wo(await gn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?wo(await _n({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?wo({...await vn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):wo(await vn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:Co(i),limits:t}))}catch(r){return wo({kind:i.kind,error:To(r),limits:t,contextFiles:Sn(e.dataDir,e.sessionId,n)})}}}}function Co(e){if(typeof e.startIndex!=`number`||typeof e.endIndex!=`number`)throw Error(`transcript_range requires startIndex and endIndex.`);return{startIndex:e.startIndex,endIndex:e.endIndex}}function wo(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function To(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Eo(e){let t=[ho(e.dataDir),go(e.dataDir),_o(e.dataDir),So({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(vo(e.dataDir)),t}const Do=`auto-skill-reviewer`;async function Oo(e){let t=e.createModel??Tr,n=e.tools??Eo({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:e.mode,currentRunRange:e.packet.currentRunRange,recentRange:e.packet.recentRange,reviewWindowRange:e.packet.reviewWindowRange}),r=t(e.runParams.llm,e.sessionId,e.runParams.messageId,e.runParams.channel),i=await Ba({sessionId:e.sessionId,systemPrompt:ko(e.mode),message:Ao(e.packet,e.mode),tools:n,model:r,getApiKey:t=>e.runParams.llm.apiKey,agentDefinition:e.reviewerAgent,abortSignal:e.runParams.abortSignal,diagnosticDispatcher:e.diagnosticDispatcher,diagnosticPhasePrefix:`auto_skill_review_internal`}),a=i.toolCalls,o=i.toolResults,s=jo(o);return{text:i.text,usage:i.usage,toolCalls:a,toolResults:o,writeResults:s,wrote:s.some(e=>!e.isError&&e.success===!0&&!e.error),error:i.error}}function ko(e){let t=e===`write`?"Write mode is active. `auto_skill_manage` is exposed for this run.":"Dry-run mode is active. `auto_skill_manage` is not exposed for this run.",n=[`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`auto_skill_review_context_view`,...e===`write`?[`auto_skill_manage`]:[]];return[`Run the configured auto-skill reviewer agent against the review packet for this invocation.`,`Apply the durable reviewer policy from the selected AgentDefinition together with the mode and tool boundaries below.`,``,`Current review mode: ${e}`,`Tools exposed for this run:`,...n.map(e=>`- ${e}`),``,t].join(`
23
- `)}function Ao(e,t){return[`Review mode: ${t}`,`Use the following auto-skill review packet as the source input for this invocation.`,``,`<auto_skill_review_packet>`,JSON.stringify(e,null,2),`</auto_skill_review_packet>`].join(`
24
- `)}function jo(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=Mo(e.content??e.preview);return{action:typeof t?.action==`string`?t.action:void 0,skillId:typeof t?.skillId==`string`?t.skillId:void 0,categoryPath:typeof t?.categoryPath==`string`?t.categoryPath:void 0,success:typeof t?.success==`boolean`?t.success:void 0,error:typeof t?.error==`string`?t.error:void 0,isError:e.isError}})}function Mo(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const No=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Po=No,Fo={session:{tool_call_volume:5,state_changing_tools:2},currentRun:{tool_call_volume:5,tool_diversity:3,state_changing_tools:3},reviewWindow:{tool_call_volume:5,state_changing_tools:1}},Io=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Lo(e){let t=zo(e.gates),n={session:Vo(`session`,e.sessionTranscript,t.session),currentRun:Vo(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:Vo(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Go(e.reviewState?.reviewCount,0),i=Go(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return qo(n,a,r,i,o,`run_error`);if(e.result?.paused)return qo(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return qo(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return qo(n,a,r,i,o,`max_reviews_per_session`);let s=a.find(e=>n[e].passed),c=s?n[s]:void 0;return{worthReview:!!s,skipped:!1,reasons:c?.reasons??[],stats:c?.stats??o,reviewCount:r,maxReviewsPerSession:i,selectedGateScope:s,consideredGateScopes:a,gateResults:n}}function Ro(e,t={}){let n=an(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??No),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(Jo(t)){for(let e of t.toolCalls??[])a.has(e.name)&&(o.add(e.name),s+=1),e.name===`skill_load`&&typeof e.arguments.name==`string`&&r.add(e.arguments.name),e.name===`auto_skill_view`&&typeof e.arguments.skillId==`string`&&i.add(e.arguments.skillId);continue}Yo(t)&&Xo(t)&&(c+=1)}return{toolCallCount:n.toolCallCount,distinctToolCount:n.distinctToolCount,toolNames:n.toolNames,stateChangingToolCallCount:s,stateChangingToolNames:Array.from(o).sort(),failedToolResultCount:n.failedToolResultCount,userTurnCount:l,loadedSkills:Array.from(r).sort(),viewedAutoSkills:Array.from(i).sort(),skillLookupFailureCount:c}}function zo(e){return{session:Bo(e?e.session:Fo.session),currentRun:Bo(e?e.currentRun:Fo.currentRun),reviewWindow:Bo(e?e.reviewWindow:Fo.reviewWindow)}}function Bo(e){let t={};for(let n of Io){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Po:void 0;if(typeof r==`number`){let e=Wo(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Wo(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:Ko(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:Ko(r.toolNames,i)})}return t}function Vo(e,t,n){let r=Ro(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=Io.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];Ho(t,o,r)?i.push({code:t,description:Uo(e,t,o)}):a.push(t)}return{scope:e,configured:o.length>0,passed:o.length>0&&a.length===0,reasons:i,missingReasonCodes:a,stats:r}}function Ho(e,t,n){switch(e){case`tool_call_volume`:return n.toolCallCount>=t.min;case`tool_diversity`:return n.distinctToolCount>=t.min;case`state_changing_tools`:return n.stateChangingToolCallCount>=t.min;case`tool_errors`:return n.failedToolResultCount>=t.min;case`multi_turn`:return n.userTurnCount>=t.min}}function Uo(e,t,n){let r=e===`currentRun`?`Current run`:e===`reviewWindow`?`Review window`:`Session`;switch(t){case`tool_call_volume`:return`${r} used at least ${n.min} tool calls.`;case`tool_diversity`:return`${r} used at least ${n.min} distinct tools.`;case`state_changing_tools`:return`${r} used at least ${n.min} configured state-changing tool calls.`;case`tool_errors`:return`${r} had at least ${n.min} failed tool results.`;case`multi_turn`:return`${r} had at least ${n.min} user turns.`}}function Wo(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Go(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Ko(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function qo(e,t,n,r,i,a){return{worthReview:!1,skipped:!0,skipReason:a,reasons:[],stats:i,reviewCount:n,maxReviewsPerSession:r,consideredGateScopes:t,gateResults:e}}function Jo(e){return e.role===`assistant`}function Yo(e){return e.role===`tool_result`}function Xo(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:Zo(e.content)?.success===!1}function Zo(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function Qo(e){let t=sn(e.transcript.length,e.transcriptStartIndex),n=cn(e.transcript.length,e.recentEntryLimit),r=sn(e.transcript.length,e.reviewWindowStartIndex??void 0),i=sn(e.transcript.length,0),a=ln(e.transcript,t),o=ln(e.transcript,r),s=Ro(e.transcript),c=Ro(a),l=Ro(o),u=rn(e.transcript),d=rn(a),f=rn(o),p=a.filter(es),m=a.filter(ts);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:$o(p[0]?.content??``,800),finalResponse:$o(e.result.text||m.at(-1)?.content||``,800),contextFiles:e.contextFiles,currentRunRange:t,recentRange:n,reviewWindowRange:r,sessionStats:u,currentRunStats:d,reviewWindowStats:f,session:{transcriptRange:i,stats:u,toolStats:s},currentRun:{transcriptRange:t,stats:d,toolStats:c},reviewWindow:{transcriptRange:r,stats:f,toolStats:l},reviewState:{reviewCount:e.reviewState?.reviewCount??0,lastCompletedReviewAt:e.reviewState?.lastCompletedReviewAt??null,lastReviewedTranscriptEndIndex:e.reviewState?.lastReviewedTranscriptEndIndex??null},transcriptSummary:{entryCount:d.totalEntryCount,userTurnCount:d.userTurnCount,assistantTurnCount:d.assistantTurnCount,toolResultCount:d.toolResultCount},toolStats:c,loadedSkills:c.loadedSkills,viewedAutoSkills:c.viewedAutoSkills,failedTools:on(a,{limit:8,maxPreviewChars:400}).map(e=>({toolName:e.toolName,preview:e.preview})),activeCategories:(e.activeCategories??[]).map(e=>({path:e.path,description:e.description}))}}function $o(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function es(e){return e.role===`user`}function ts(e){return e.role===`assistant`}function ns(e,t,n){return K.join(d(e,t,n),`auto-skill-review-state.json`)}function rs(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function is(e,t,n){let r=ns(e,t,n),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return rs(t);throw e}return ls(JSON.parse(i),t)}async function as(e,t,n){let r=ns(e,t.sessionId,n);await G.mkdir(K.dirname(r),{recursive:!0}),await G.writeFile(r,`${JSON.stringify(ls(t,t.sessionId),null,2)}\n`,`utf-8`)}async function os(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await as(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function ss(e){let t={...e.state,sessionId:e.sessionId,reviewCount:Math.max(0,Math.floor(e.state.reviewCount))+1,lastCompletedReviewAt:e.completedAt??new Date().toISOString(),lastFailedReviewAt:e.state.lastFailedReviewAt??null,lastReviewedTranscriptEndIndex:Math.max(0,Math.floor(e.reviewedTranscriptEndIndex))};return await as(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function cs(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await as(e.dataDir,t,{storeName:e.sessionStoreName}),t}function ls(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:fs(n.reviewCount,0),lastAttemptedReviewAt:us(n.lastAttemptedReviewAt),lastCompletedReviewAt:us(n.lastCompletedReviewAt),lastFailedReviewAt:us(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:ds(n.lastReviewedTranscriptEndIndex)}}function us(e){return typeof e==`string`&&e.trim()?e:null}function ds(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function fs(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function ps(e){return K.join(Bn(e),`.reviews`,`run-log.jsonl`)}async function ms(e,t){let n=ps(e);await G.mkdir(K.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await G.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const hs=`write`,gs=new Set([`off`,`gate`,`dry_run`,`write`]);async function _s(e){let t=vs(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=bs(e);if(n){await ws(e,t,n);return}let r,i;try{let n=await m(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=xs(n,e.transcriptStartIndex),o=await is(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=Ss(o.lastReviewedTranscriptEndIndex,n.length),c=xs(n,s);await Ts(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=Lo({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await Ts(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:l.worthReview,selectedGateScope:l.selectedGateScope,skipReason:l.skipReason}),!l.worthReview){await Es(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await Ts(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new ar({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=Qo({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:Sn(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await Ts(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await Es(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(Do);if(!p){X.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:Do}),await ws(e,t,`reviewer_agent_missing`,{reviewerAgentName:Do});return}i={mode:f,decision:l,packet:d},r=await os({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:o,sessionStoreName:e.runParams.sessionStoreName}),await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_started`,message:`auto-skill review agent started`,details:{mode:t.mode,selectedGateScope:l.selectedGateScope,reviewCount:l.reviewCount,maxReviewsPerSession:l.maxReviewsPerSession}});let h=e.curator??Oo,g=Eo({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:t.mode,currentRunRange:d.currentRunRange,recentRange:d.recentRange,reviewWindowRange:d.reviewWindowRange}),_=await h({sessionId:e.sessionId,runParams:e.runParams,packet:d,mode:t.mode,tools:g,reviewerAgent:p,diagnosticDispatcher:e.eventDispatcher});if(_.error){r=await cs({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await Ds(e.runParams.dataDir,i,{status:`failed`,curatorResult:_,error:_.error,reviewState:r});await Cs(e,_.error,{mode:t.mode,usage:_.usage,toolCalls:Os(_.toolCalls),toolResults:Fs(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewRunLogPath:n});return}r=await ss({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let v=await Ds(e.runParams.dataDir,i,{status:`completed`,curatorResult:_,reviewState:r});await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_completed`,message:`auto-skill review agent completed`,details:{mode:t.mode,usage:_.usage,text:Ps(_.text,2e3),toolCalls:Os(_.toolCalls),toolResults:Fs(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewState:r,reviewRunLogPath:v}})}catch(t){let n=t instanceof Error?t.message:String(t),a;r&&(r=await cs({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await Ds(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await Cs(e,n,a?{reviewRunLogPath:a}:void 0)}}function vs(e){return{mode:ys(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function ys(e){if(e==null)return hs;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?gs.has(t)?t:`off`:hs}function bs(e){if(e.runParams.subagentContext)return`subagent`;if(e.runParams.channel===`CRON`)return`cron`;if(e.result.error)return`run_error`;if(e.result.paused)return`hitl_paused`;if(e.result.uiToolPending)return`ui_tool_pending`}function xs(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function Ss(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function Cs(e,t,n){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skill_review_failed`,message:`auto-skill review failed`,details:{...n??{},error:t}})}async function ws(e,t,n,r={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:n===`run_error`?`warn`:`info`,scope:`skill`,phase:`auto_skill_review_skipped`,message:n===`reviewer_agent_missing`?`auto-skill review skipped because reviewer agent is missing`:`auto-skill review skipped before gate evaluation`,details:{mode:t.mode,reason:n,...r}})}async function Ts(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function Es(e,t,n,r,i={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_gated`,message:n.worthReview?`completed run is worth auto-skill review`:`completed run is not worth auto-skill review`,details:{mode:t.mode,worthReview:n.worthReview,skipped:n.skipped,...i.skipReason?{skipReason:i.skipReason}:{},transcriptEntryCount:r.length,transcriptStartIndex:e.transcriptStartIndex,reasons:n.reasons.map(e=>({code:e.code})),stats:n.stats,selectedGateScope:n.selectedGateScope,consideredGateScopes:n.consideredGateScopes,reviewCount:n.reviewCount,maxReviewsPerSession:n.maxReviewsPerSession,gateResults:Ns(n),...i.packet?{packet:i.packet}:{}}})}async function Ds(e,t,n){return ms(e,{sessionId:t.packet.sessionId,mode:t.mode,status:n.status,selectedGateScope:t.decision.selectedGateScope,reviewCount:t.decision.reviewCount,reasons:t.decision.reasons.map(e=>e.code),currentRunRange:t.packet.currentRunRange,reviewWindowRange:t.packet.reviewWindowRange,conclusion:n.curatorResult?As(n.curatorResult.text):void 0,conclusionText:n.curatorResult?js(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?Os(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?Fs(n.curatorResult.toolResults):void 0,writeResults:n.curatorResult?.writeResults,wrote:n.curatorResult?.wrote,error:n.error,reviewStateAfter:n.reviewState?{reviewCount:n.reviewState.reviewCount,lastReviewedTranscriptEndIndex:n.reviewState.lastReviewedTranscriptEndIndex}:void 0})}function Os(e){return e.map(e=>({...e,arguments:ks(e.name,e.arguments)}))}function ks(e,t){if(e!==`auto_skill_manage`)return t;let n={};for(let e of[`action`,`skillId`,`name`,`categoryPath`,`newCategory`])t[e]!==void 0&&(n[e]=t[e]);return n}function As(e){let t=Ms(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function js(e){return As(e)?void 0:Ps(e,8e3)}function Ms(e){let t=e.trim(),n=[t],r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);r?.[1]&&n.unshift(r[1].trim());let i=t.indexOf(`{`),a=t.lastIndexOf(`}`);return i>=0&&a>i&&n.push(t.slice(i,a+1)),Array.from(new Set(n.filter(Boolean)))}function Ns(e){return Object.fromEntries(Object.entries(e.gateResults).map(([e,t])=>[e,{configured:t.configured,passed:t.passed,reasons:t.reasons.map(e=>({code:e.code})),missingReasonCodes:t.missingReasonCodes,stats:t.stats}]))}function Ps(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function Fs(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}const Is=2,Ls=5;var Rs=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),X.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:ma(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&&X.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){X.info(`subagent status changed`,t);return}if(e.status===`killed`){X.warn(`subagent status changed`,t);return}X.error(`subagent status changed`,t)}};const zs=new Map;function Bs(e){let t=zs.get(e);return t||(t={},zs.set(e,t)),t}function Vs(e){zs.delete(e)}let Hs=!1;function Us(){Hs||=($e(),Qe({api:`openai-completions`,stream:Oi,streamSimple:ki}),!0)}const Ws=[`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(`
25
- `);async function Gs(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 qs(s);let c=r.flashModel,l=$r({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:Ws,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 Ks(500*e)}return qs(s)}function Ks(e){return new Promise(t=>setTimeout(t,e))}function qs(e,t=80){if(!e)return`New session`;try{let t=JSON.parse(e);if(Array.isArray(t))return t?.[0]?.content?.[0].text??e}catch{}let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}function Q(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}async function Js(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 Ys(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e;await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher});let o=await m(r.dataDir,t,{...Q(r)});await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher})}async function Xs(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:a=!1,runParams:o,hookRegistry:s,hookContext:c,startTime:l,compactionEntry:u,eventDispatcher:d}=e,f=Q(o);if(a||await p(o.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},f),u&&await p(o.dataDir,n,u,f),await p(o.dataDir,n,{role:`assistant`,content:t,timestamp:new Date().toISOString()},f),r){let t=await Gs({message:i.trim()?i:`New session`,llm:o.llm,text:e.replyText,hooks:s,hookCtx:c});await x(o.dataDir,n,{title:t},f),await d.dispatchProgress(n,{type:`title_updated`,title:t})}let m=Date.now()-l,g={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:m,context:{snapshotPath:h(o.dataDir,n,Q(o)),toolResultsDir:S(o.dataDir,n,Q(o))}};return X.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:m,isNewSession:r,textLength:t.length,hasCompactionEntry:!!u,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir}),await Ys({sessionId:n,result:g,runParams:o,hookRegistry:s,hookContext:c,eventDispatcher:d}),g}async function Zs(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:a,hookContext:o,startTime:s,text:c,usage:l,error:u,paused:d,uiToolPending:f,eventDispatcher:p}=e;if(n){let n=Q(i),s=await Gs({message:r,llm:i.llm,text:e.text,hooks:a,hookCtx:o});await x(i.dataDir,t,{title:s},n),await p.dispatchProgress(t,{type:`title_updated`,title:s})}let m={sessionId:t,text:c,usage:l,durationMs:Date.now()-s,error:u,paused:d,uiToolPending:f,context:{snapshotPath:h(i.dataDir,t,Q(i)),toolResultsDir:S(i.dataDir,t,Q(i))}},g={sessionId:t,kind:`completed`,durationMs:m.durationMs,isNewSession:n,inputTokens:l.input,outputTokens:l.output,totalTokens:l.total,hasError:!!u,error:u,paused:!!d,uiToolPending:!!f,textLength:c.length,snapshotPath:m.context.snapshotPath,toolResultsDir:m.context.toolResultsDir};return u?X.warn(`agent run finalized with error`,g):X.info(`agent run finalized`,g),await Ys({sessionId:t,result:m,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:p}),m}const Qs=new Set([`pause`,`resume`,`clear`,`help`]);async function $s(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`Goal objective cannot be empty`);let r=await B(e.dataDir,e.sessionId,t);if(!r)return{action:`created`,goal:await R(e.dataDir,e.sessionId,{goalId:We(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource})};if((await H(e.dataDir,e.sessionId,r,t)).trim()!==n)return{action:`replaced`,goal:await R(e.dataDir,e.sessionId,{goalId:We(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource})};if(r.status===`complete`)return{action:`unchanged`,goal:r};let i={};if(r.status===`paused`&&(i.status=`active`),e.tokenBudget!==void 0&&e.tokenBudget!==r.tokenBudget&&(i.tokenBudget=e.tokenBudget),Object.keys(i).length===0)return{action:`unchanged`,goal:r};let a=await L(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function ec(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(Qs.has(n))return{action:n,objective:``};let r=t,i,a=r.match(/^--token-budget\s+(\S+)(?:\s+([\s\S]*))?$/);if(a){let e=a[1]??``;if(i=e===`0`?null:Number.parseInt(e,10),i!==null&&(!Number.isFinite(i)||i<=0))throw Error(`--token-budget must be a positive integer or 0 for unlimited`);r=(a[2]??``).trim()}if(!r)throw Error(`Usage: /goal <objective> or /goal --token-budget <n> <objective>`);return{action:`set`,objective:r,tokenBudget:i}}function tc(e,t){let n=e.tokenBudget===null?`Token budget: unlimited`:`Token budget: ${e.tokenBudget} (used ${e.tokensUsed}, remaining ${Math.max(0,e.tokenBudget-e.tokensUsed)})`;return[`Thread Goal`,`Status: ${e.status}`,`Objective: ${t.length>200?`${t.slice(0,200)}...`:t}`,n,`Time used: ${e.timeUsedSeconds}s`,``,nc(e.status)].join(`
26
- `)}function nc(e){switch(e){case`active`:return`Commands: /goal pause, /goal clear`;case`paused`:return`Commands: /goal resume, /goal clear`;case`budget_limited`:return`Budget limited. Commands: /goal clear (do not declare complete solely due to budget)`;case`complete`:return`Goal complete. Commands: /goal clear`;default:return`Commands: /goal <objective>, /goal pause, /goal resume, /goal clear`}}async function rc(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:[`Goal commands`,` /goal <objective> Set or replace the thread goal (active)`,` /goal --token-budget <n> <text> Set goal with token budget (0 = unlimited)`,` /goal Show current goal summary`,` /goal pause Pause goal continuation`,` /goal resume Resume a paused goal`,` /goal clear Remove the goal`].join(`
27
- `)};if(e.action===`get`){let e=await B(t.dataDir,t.sessionId,n);return e?{replyText:tc(e,await H(t.dataDir,t.sessionId,e,n))}:{replyText:[`No thread goal is set for this session.`,``,`Usage: /goal <objective>`,`Example: /goal improve benchmark coverage`].join(`
28
- `)}}if(e.action===`set`){let r=await $s({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await H(t.dataDir,t.sessionId,r.goal,n);return r.action===`unchanged`?{replyText:r.goal.status===`complete`?`Goal is already complete.\n\n${tc(r.goal,i)}`:`Goal unchanged.\n\n${tc(r.goal,i)}`}:{replyText:`${r.action===`resumed`?`Goal resumed (active).`:r.action===`updated`?`Goal updated.`:`Goal set (active).`}\n\n${tc(r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await B(t.dataDir,t.sessionId,n);if(!e)throw Error(`No goal exists for this session`);if(e.status===`complete`)throw Error(`Cannot pause a completed goal`);if(e.status===`paused`)return{replyText:`Goal is already paused. Use /goal resume to continue.`};let r=await L(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`Goal paused.\n\n${tc(r,await H(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await B(t.dataDir,t.sessionId,n);if(!e)throw Error(`No goal exists for this session`);if(e.status===`complete`)throw Error(`Cannot resume a completed goal`);if(e.status===`budget_limited`)throw Error(`Cannot resume a budget-limited goal; clear or replace it instead`);if(e.status===`active`)return{replyText:`Goal is already active.\n\n${tc(e,await H(t.dataDir,t.sessionId,e,n))}`};let r=await L(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`Goal resumed (active).\n\n${tc(r,await H(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await U(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`Goal cleared.`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`No goal was set.`}:{replyText:`Unknown /goal command. Try /goal help.`}}const ic=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`},{name:`/goal`,description:`设置或查看线程目标`},{name:`/goal pause`,description:`暂停线程目标`},{name:`/goal resume`,description:`恢复线程目标`},{name:`/goal clear`,description:`清除线程目标`}];function ac(){return ic.map(e=>({...e}))}function oc(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function sc(e){let t=new Set,n=[];for(let r of e){let e=oc(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function cc(e){let t=ac(),n=sc(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function lc(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 uc(e){let t=lc(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 dc(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 fc(e,t){let n=uc(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===`goal`)try{let e=ec(n.rest);return{kind:`goal`,action:e.action,objective:e.objective,tokenBudget:e.tokenBudget}}catch(e){return{kind:`unknown`,name:n.name,args:e.message}}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:oc(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(sc(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 pc=new Set([`/new`,`/reset`,`/compact`]),mc=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),hc=new Set([`/help`]);function gc(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function _c(e){if(e.length===0)return[];let t=e.map(gc),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function vc(e){let t=cc(e.skills),n=t.builtin.filter(e=>pc.has(e.name)),r=t.builtin.filter(e=>mc.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>hc.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(..._c(n)),s.push(``),s.push(`目标命令`),s.push(..._c(r)),s.push(``),s.push(`技能命令`),s.push(..._c(i)),o.length>0?(s.push(..._c(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(..._c(a)),{kind:`reply`,text:s.join(`
29
- `)}}function yc(e,t){let n=t.trim().toLowerCase();return n&&sc(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function bc(e){let t=yc(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(`
30
-
31
- `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function xc(e){let t=fc(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?vc(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?bc({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:t.kind===`unknown`&&t.name===`goal`?{kind:`reply`,text:t.args||`Usage: /goal <objective> | /goal pause | /goal resume | /goal clear`}:{kind:`pass`,message:e.message}}function Sc(e){return Math.ceil(e.length/4*1.2)}function Cc(e){if(e.role===`user`)return Sc(e.content);if(e.role===`assistant`){let t=Sc(e.content);e.errorMessage&&(t+=Sc(e.errorMessage));for(let n of e.toolCalls??[])t+=Sc(n.name)+Sc(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(`
32
- `):e.content;return Sc(e.toolName)+Sc(t)}function $(e){return e.reduce((e,t)=>e+Cc(t),0)}const wc=[`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(`
33
- `);async function Tc(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Dc(t,r,i),l,u=$r({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:wc,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 Ec(500*e)}throw l}function Ec(e){return new Promise(t=>setTimeout(t,e))}function Dc(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`?Oc(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(`
19
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Fa(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Ia(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 La(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 Ra(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function za(e){let t=Ba(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 Ba(e){if(e instanceof Y)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:Ta(t.code),statusCode:Ea(t.statusCode),statusText:Ta(t.statusText),providerMessage:Ta(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 Va(e){let t=qa(e.toolResultPreviewChars),n=Ja(e.systemPrompt,e.agentDefinition),r=Xa(e.model,e.agentDefinition),i=Br(e.tools??[],e.agentDefinition),a=Ya(e.message,e.agentDefinition),o=await ga({agent:new qe({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:Ha({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new Zr,hookCtx:{sessionId:e.sessionId},abortSignal:e.abortSignal});return{text:o.text,usage:{input:o.inputTokens,output:o.outputTokens,total:o.inputTokens+o.outputTokens},error:o.error,toolCalls:Wa(o.turnRecords),toolResults:Ga(o.turnRecords,t)}}function Ha(e){let t=e.phasePrefix??`silent_agent`;return new Qr({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await Ua(e.diagnosticDispatcher,t,n)}})}async function Ua(e,t,n){let r=n.sessionId;if(r){if(n.type===`stream_text_delta`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_stream`,message:`silent agent streamed text`,details:{textLength:n.text.length}});return}if(n.type===`tool_start`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_tool_started`,message:`silent agent tool started`,details:{toolCallId:n.toolCallId,toolName:n.name,input:n.input}});return}if(n.type===`tool_end`){await e.dispatchDiagnostic(r,{level:n.isError?`warn`:`info`,scope:`skill`,phase:`${t}_tool_completed`,message:n.isError?`silent agent tool failed`:`silent agent tool completed`,details:{toolCallId:n.toolCallId,toolName:n.name,isError:n.isError}});return}if(n.type===`error`){await e.dispatchDiagnostic(r,{level:`warn`,scope:`skill`,phase:`${t}_error`,message:`silent agent reported error`,details:{error:n.message}});return}n.type===`diagnostic`&&await e.dispatchDiagnostic(r,{level:n.level,scope:n.scope,phase:`${t}_${n.phase}`,message:n.message,...n.details?{details:n.details}:{}})}}function Wa(e){let t=[];for(let n of e)for(let e of n.message.content)e.type===`toolCall`&&t.push({id:e.id,name:e.name,arguments:e.arguments??{}});return t}function Ga(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Ka(e.content,t)})))}function Ka(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function qa(e){let t=e??800;if(!Number.isFinite(t))throw Error(`toolResultPreviewChars must be a finite non-negative integer.`);return Math.max(0,Math.floor(t))}function Ja(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
20
+
21
+ `)}function Ya(e,t){return!t?.initPrompt||typeof e!=`string`?e:Hr(t,e)}function Xa(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}var Za=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=G.resolve(e.rootDir??Vn(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=J(e.path),n=ro(e.description,`category description`),r=await this.readCategoryRegistry();if(r[t])throw Error(`Auto-skill category already exists: ${t}`);return r[t]={description:n,createdBy:e.createdBy?.trim()||`review-agent`},await this.writeCategoryRegistry(r),await ar(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:Hn(this.rootDir)}}async createSkill(e){let t=Kn(e.name),n=J(e.categoryPath),r=ro(e.description,`auto-skill description`),i=io(e.body);await this.assertCategoryExists(n);let a=qn(n,t),o=Xn(this.rootDir,n,t);if(await to(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=G.join(o,`SKILL.md`),l=G.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:ao(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:oo(e.evidence,s)};return await W.mkdir(o,{recursive:!0}),await W.writeFile(c,Qa(t,r,i),`utf-8`),await no(l,u),await ar(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=Jn(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Xn(this.rootDir,t.categoryPath,t.skillName),r=G.join(n,`SKILL.md`),i=G.join(n,`metadata.json`),a=await $a(r),o=await eo(i),s=e.description===void 0?a.description:ro(e.description,`auto-skill description`),c=e.body===void 0?a.body:io(e.body),l=this.now().toISOString(),u={...o,skillId:t.skillId,status:o.status===`archived`?`archived`:`active`,categoryPath:t.categoryPath,source:`auto`,tags:e.tags===void 0?ao(o.tags):ao(e.tags),confidence:e.confidence??o.confidence,createdAt:typeof o.createdAt==`string`?o.createdAt:l,updatedAt:l,review:{...typeof o.review==`object`&&o.review!==null?o.review:{},...oo(e.evidence,l)}};return await W.writeFile(r,Qa(t.skillName,s,c),`utf-8`),await no(i,u),await ar(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=Jn(e.skillId),n=Xn(this.rootDir,t.categoryPath,t.skillName),r=G.join(n,`metadata.json`),i=G.join(n,`SKILL.md`);await W.access(i);let a=await eo(r),o=this.now().toISOString();return await no(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...oo(e.evidence,o)}}),await ar(this.rootDir),{action:`archive`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:i,metadataFile:r}}async assertCategoryExists(e){if(!(await this.readCategoryRegistry())[e])throw Error(`Unknown auto-skill category: ${e}. Create it first with create_category.`)}async readCategoryRegistry(){let e=Hn(this.rootDir),t;try{t=await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=J(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await W.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await no(Hn(this.rootDir),t)}};function Qa(e,t,n){return[`---`,`name: ${so(e)}`,`description: ${so(t)}`,`---`,``,n.trim(),``].join(`
22
+ `)}async function $a(e){let t=Ue(await W.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function eo(e){let t;try{t=await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}async function to(e){try{return await W.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function no(e,t){await W.mkdir(G.dirname(e),{recursive:!0}),await W.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function ro(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function io(e){let t=e.trim();if(!t)throw Error(`Auto-skill body cannot be empty.`);if(t.length<20)throw Error(`Auto-skill body is too short to be useful.`);if(t.startsWith(`---`))throw Error(`Auto-skill body must not include frontmatter; metadata is generated by the store.`);return t}function ao(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function oo(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function so(e){return JSON.stringify(e)}const co=[`create`,`update`,`archive`,`create_category`],lo=K.Object({}),uo=K.Object({categoryPath:K.Optional(K.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:K.Optional(K.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),fo=K.Object({query:K.String({description:`Search query for learned auto-skills.`}),limit:K.Optional(K.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),po=K.Object({skillId:K.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:K.Optional(K.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),mo=K.Object({action:K.Union(co.map(e=>K.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:K.Optional(K.String({description:`Exact auto-skill id for update/archive.`})),name:K.Optional(K.String({description:`Auto-skill slug for create.`})),categoryPath:K.Optional(K.String({description:`Existing single-level category slug for create.`})),newCategory:K.Optional(K.Object({path:K.String({description:`New single-level category slug to create.`}),description:K.String({description:`New category description.`})})),description:K.Optional(K.String({description:`Auto-skill description for create/update.`})),tags:K.Optional(K.Array(K.String({description:`Auto-skill tag.`}))),confidence:K.Optional(K.Number({description:`Optional confidence score from 0 to 1.`})),body:K.Optional(K.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:K.Optional(K.Object({sessionId:K.String({description:`Source session id.`}),reason:K.String({description:`Why this auto-skill write is justified.`}),toolCallCount:K.Optional(K.Number({description:`Tool calls observed in source run.`})),loadedSkills:K.Optional(K.Array(K.String({description:`Skill loaded during source run.`})))}))});function ho(e){let t=new or({dataDir:e});return{name:`auto_skill_categories`,label:`Auto-Skill Categories`,description:`List learned auto-skill categories. Use before auto_skill_list when learned workflows may help.`,parameters:lo,async execute(){try{let e=await t.autoSkillCategories();return Z({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return Z({categories:[],count:0,error:xo(e)})}}}}function go(e){let t=new or({dataDir:e});return{name:`auto_skill_list`,label:`Auto-Skill List`,description:`List active learned auto-skills by category without loading SKILL.md content.`,parameters:uo,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return Z({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Z({skills:[],count:0,error:xo(e)})}}}}function _o(e){let t=new or({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:fo,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return Z({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Z({skills:[],count:0,error:xo(e)})}}}}function vo(e){let t=new or({dataDir:e});return{name:`auto_skill_view`,label:`Auto-Skill View`,description:`Load an active learned auto-skill by exact skillId, or read a file inside that auto-skill directory.`,parameters:po,async execute(e,n){try{return Z({...await t.autoSkillView({skillId:n.skillId,filePath:n.filePath}),usage_hint:n.filePath?`This returned one file inside the auto-skill directory.`:`This returns SKILL.md. If it references helper files, call auto_skill_view({ skillId, filePath }) for only the needed file.`})}catch(e){return Z({skillId:n.skillId,error:xo(e)})}}}}function yo(e){let t=new Za({dataDir:e});return{name:`auto_skill_manage`,label:`Auto-Skill Manage`,description:`Restricted review-agent tool for creating, updating, archiving learned auto-skills, or creating categories. Do not expose this tool to the main user-facing agent.`,parameters:mo,async execute(e,n){try{return Z(await bo(t,n))}catch(e){return Z({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:xo(e)})}}}}async function bo(e,t){if(t.action===`create_category`){if(!t.newCategory)throw Error(`create_category requires newCategory.`);return e.createCategory({path:t.newCategory.path,description:t.newCategory.description})}if(t.action===`create`){if(!t.name||!t.categoryPath||!t.description||!t.body)throw Error(`create requires name, categoryPath, description, and body.`);return e.createSkill({name:t.name,categoryPath:t.categoryPath,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(t.action===`update`){if(!t.skillId)throw Error(`update requires skillId.`);return e.updateSkill({skillId:t.skillId,description:t.description,body:t.body,tags:t.tags,confidence:t.confidence,evidence:t.evidence})}if(!t.skillId)throw Error(`archive requires skillId.`);return e.archiveSkill({skillId:t.skillId,evidence:t.evidence})}function Z(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function xo(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const So=K.Object({kind:K.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>K.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:K.Optional(K.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:K.Optional(K.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:K.Optional(K.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:K.Optional(K.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function Co(e){let t=xn({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??gn}),n={storeName:e.storeName};return{name:`auto_skill_review_context_view`,label:`Auto-Skill Review Context`,description:`Internal read-only review tool for controlled access to the current session transcript and persisted tool-result evidence. Only use inside the auto-skill review agent.`,parameters:So,async execute(r,i){try{return i.kind===`tool_result`?To(await bn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?To(await _n({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?To(await vn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?To({...await yn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):To(await yn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:wo(i),limits:t}))}catch(r){return To({kind:i.kind,error:Eo(r),limits:t,contextFiles:Cn(e.dataDir,e.sessionId,n)})}}}}function wo(e){if(typeof e.startIndex!=`number`||typeof e.endIndex!=`number`)throw Error(`transcript_range requires startIndex and endIndex.`);return{startIndex:e.startIndex,endIndex:e.endIndex}}function To(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Eo(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Do(e){let t=[go(e.dataDir),_o(e.dataDir),vo(e.dataDir),Co({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(yo(e.dataDir)),t}const Oo=`auto-skill-reviewer`;async function ko(e){let t=e.createModel??Er,n=e.tools??Do({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:e.mode,currentRunRange:e.packet.currentRunRange,recentRange:e.packet.recentRange,reviewWindowRange:e.packet.reviewWindowRange}),r=t(e.runParams.llm,e.sessionId,e.runParams.messageId,e.runParams.channel),i=await Va({sessionId:e.sessionId,systemPrompt:Ao(e.mode),message:jo(e.packet,e.mode),tools:n,model:r,getApiKey:t=>e.runParams.llm.apiKey,agentDefinition:e.reviewerAgent,abortSignal:e.runParams.abortSignal,diagnosticDispatcher:e.diagnosticDispatcher,diagnosticPhasePrefix:`auto_skill_review_internal`}),a=i.toolCalls,o=i.toolResults,s=Mo(o);return{text:i.text,usage:i.usage,toolCalls:a,toolResults:o,writeResults:s,wrote:s.some(e=>!e.isError&&e.success===!0&&!e.error),error:i.error}}function Ao(e){let t=e===`write`?"Write mode is active. `auto_skill_manage` is exposed for this run.":"Dry-run mode is active. `auto_skill_manage` is not exposed for this run.",n=[`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`auto_skill_review_context_view`,...e===`write`?[`auto_skill_manage`]:[]];return[`Run the configured auto-skill reviewer agent against the review packet for this invocation.`,`Apply the durable reviewer policy from the selected AgentDefinition together with the mode and tool boundaries below.`,``,`Current review mode: ${e}`,`Tools exposed for this run:`,...n.map(e=>`- ${e}`),``,t].join(`
23
+ `)}function jo(e,t){return[`Review mode: ${t}`,`Use the following auto-skill review packet as the source input for this invocation.`,``,`<auto_skill_review_packet>`,JSON.stringify(e,null,2),`</auto_skill_review_packet>`].join(`
24
+ `)}function Mo(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=No(e.content??e.preview);return{action:typeof t?.action==`string`?t.action:void 0,skillId:typeof t?.skillId==`string`?t.skillId:void 0,categoryPath:typeof t?.categoryPath==`string`?t.categoryPath:void 0,success:typeof t?.success==`boolean`?t.success:void 0,error:typeof t?.error==`string`?t.error:void 0,isError:e.isError}})}function No(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const Po=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Fo=Po,Io={session:{tool_call_volume:5,state_changing_tools:2},currentRun:{tool_call_volume:5,tool_diversity:3,state_changing_tools:3},reviewWindow:{tool_call_volume:5,state_changing_tools:1}},Lo=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Ro(e){let t=Bo(e.gates),n={session:Ho(`session`,e.sessionTranscript,t.session),currentRun:Ho(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:Ho(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Ko(e.reviewState?.reviewCount,0),i=Ko(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return Jo(n,a,r,i,o,`run_error`);if(e.result?.paused)return Jo(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return Jo(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return Jo(n,a,r,i,o,`max_reviews_per_session`);let s=a.find(e=>n[e].passed),c=s?n[s]:void 0;return{worthReview:!!s,skipped:!1,reasons:c?.reasons??[],stats:c?.stats??o,reviewCount:r,maxReviewsPerSession:i,selectedGateScope:s,consideredGateScopes:a,gateResults:n}}function zo(e,t={}){let n=on(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??Po),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(Yo(t)){for(let e of t.toolCalls??[])a.has(e.name)&&(o.add(e.name),s+=1),e.name===`skill_load`&&typeof e.arguments.name==`string`&&r.add(e.arguments.name),e.name===`auto_skill_view`&&typeof e.arguments.skillId==`string`&&i.add(e.arguments.skillId);continue}Xo(t)&&Zo(t)&&(c+=1)}return{toolCallCount:n.toolCallCount,distinctToolCount:n.distinctToolCount,toolNames:n.toolNames,stateChangingToolCallCount:s,stateChangingToolNames:Array.from(o).sort(),failedToolResultCount:n.failedToolResultCount,userTurnCount:l,loadedSkills:Array.from(r).sort(),viewedAutoSkills:Array.from(i).sort(),skillLookupFailureCount:c}}function Bo(e){return{session:Vo(e?e.session:Io.session),currentRun:Vo(e?e.currentRun:Io.currentRun),reviewWindow:Vo(e?e.reviewWindow:Io.reviewWindow)}}function Vo(e){let t={};for(let n of Lo){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Fo:void 0;if(typeof r==`number`){let e=Go(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Go(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:qo(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:qo(r.toolNames,i)})}return t}function Ho(e,t,n){let r=zo(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=Lo.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];Uo(t,o,r)?i.push({code:t,description:Wo(e,t,o)}):a.push(t)}return{scope:e,configured:o.length>0,passed:o.length>0&&a.length===0,reasons:i,missingReasonCodes:a,stats:r}}function Uo(e,t,n){switch(e){case`tool_call_volume`:return n.toolCallCount>=t.min;case`tool_diversity`:return n.distinctToolCount>=t.min;case`state_changing_tools`:return n.stateChangingToolCallCount>=t.min;case`tool_errors`:return n.failedToolResultCount>=t.min;case`multi_turn`:return n.userTurnCount>=t.min}}function Wo(e,t,n){let r=e===`currentRun`?`Current run`:e===`reviewWindow`?`Review window`:`Session`;switch(t){case`tool_call_volume`:return`${r} used at least ${n.min} tool calls.`;case`tool_diversity`:return`${r} used at least ${n.min} distinct tools.`;case`state_changing_tools`:return`${r} used at least ${n.min} configured state-changing tool calls.`;case`tool_errors`:return`${r} had at least ${n.min} failed tool results.`;case`multi_turn`:return`${r} had at least ${n.min} user turns.`}}function Go(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Ko(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function qo(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function Jo(e,t,n,r,i,a){return{worthReview:!1,skipped:!0,skipReason:a,reasons:[],stats:i,reviewCount:n,maxReviewsPerSession:r,consideredGateScopes:t,gateResults:e}}function Yo(e){return e.role===`assistant`}function Xo(e){return e.role===`tool_result`}function Zo(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:Qo(e.content)?.success===!1}function Qo(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function $o(e){let t=cn(e.transcript.length,e.transcriptStartIndex),n=ln(e.transcript.length,e.recentEntryLimit),r=cn(e.transcript.length,e.reviewWindowStartIndex??void 0),i=cn(e.transcript.length,0),a=un(e.transcript,t),o=un(e.transcript,r),s=zo(e.transcript),c=zo(a),l=zo(o),u=an(e.transcript),d=an(a),f=an(o),p=a.filter(ts),m=a.filter(ns);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:es(p[0]?.content??``,800),finalResponse:es(e.result.text||m.at(-1)?.content||``,800),contextFiles:e.contextFiles,currentRunRange:t,recentRange:n,reviewWindowRange:r,sessionStats:u,currentRunStats:d,reviewWindowStats:f,session:{transcriptRange:i,stats:u,toolStats:s},currentRun:{transcriptRange:t,stats:d,toolStats:c},reviewWindow:{transcriptRange:r,stats:f,toolStats:l},reviewState:{reviewCount:e.reviewState?.reviewCount??0,lastCompletedReviewAt:e.reviewState?.lastCompletedReviewAt??null,lastReviewedTranscriptEndIndex:e.reviewState?.lastReviewedTranscriptEndIndex??null},transcriptSummary:{entryCount:d.totalEntryCount,userTurnCount:d.userTurnCount,assistantTurnCount:d.assistantTurnCount,toolResultCount:d.toolResultCount},toolStats:c,loadedSkills:c.loadedSkills,viewedAutoSkills:c.viewedAutoSkills,failedTools:sn(a,{limit:8,maxPreviewChars:400}).map(e=>({toolName:e.toolName,preview:e.preview})),activeCategories:(e.activeCategories??[]).map(e=>({path:e.path,description:e.description}))}}function es(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function ts(e){return e.role===`user`}function ns(e){return e.role===`assistant`}function rs(e,t,n){return G.join(d(e,t,n),`auto-skill-review-state.json`)}function is(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function as(e,t,n){let r=rs(e,t,n),i;try{i=await W.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return is(t);throw e}return us(JSON.parse(i),t)}async function os(e,t,n){let r=rs(e,t.sessionId,n);await W.mkdir(G.dirname(r),{recursive:!0}),await W.writeFile(r,`${JSON.stringify(us(t,t.sessionId),null,2)}\n`,`utf-8`)}async function ss(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await os(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function cs(e){let t={...e.state,sessionId:e.sessionId,reviewCount:Math.max(0,Math.floor(e.state.reviewCount))+1,lastCompletedReviewAt:e.completedAt??new Date().toISOString(),lastFailedReviewAt:e.state.lastFailedReviewAt??null,lastReviewedTranscriptEndIndex:Math.max(0,Math.floor(e.reviewedTranscriptEndIndex))};return await os(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function ls(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await os(e.dataDir,t,{storeName:e.sessionStoreName}),t}function us(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:ps(n.reviewCount,0),lastAttemptedReviewAt:ds(n.lastAttemptedReviewAt),lastCompletedReviewAt:ds(n.lastCompletedReviewAt),lastFailedReviewAt:ds(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:fs(n.lastReviewedTranscriptEndIndex)}}function ds(e){return typeof e==`string`&&e.trim()?e:null}function fs(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function ps(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function ms(e){return G.join(Vn(e),`.reviews`,`run-log.jsonl`)}async function hs(e,t){let n=ms(e);await W.mkdir(G.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await W.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const gs=`write`,_s=new Set([`off`,`gate`,`dry_run`,`write`]);async function vs(e){let t=ys(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=xs(e);if(n){await Ts(e,t,n);return}let r,i;try{let n=await m(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=Ss(n,e.transcriptStartIndex),o=await as(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=Cs(o.lastReviewedTranscriptEndIndex,n.length),c=Ss(n,s);await Es(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=Ro({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await Es(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:l.worthReview,selectedGateScope:l.selectedGateScope,skipReason:l.skipReason}),!l.worthReview){await Ds(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await Es(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new or({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=$o({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:Cn(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await Es(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await Ds(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(Oo);if(!p){X.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:Oo}),await Ts(e,t,`reviewer_agent_missing`,{reviewerAgentName:Oo});return}i={mode:f,decision:l,packet:d},r=await ss({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:o,sessionStoreName:e.runParams.sessionStoreName}),await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_started`,message:`auto-skill review agent started`,details:{mode:t.mode,selectedGateScope:l.selectedGateScope,reviewCount:l.reviewCount,maxReviewsPerSession:l.maxReviewsPerSession}});let h=e.curator??ko,g=Do({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:t.mode,currentRunRange:d.currentRunRange,recentRange:d.recentRange,reviewWindowRange:d.reviewWindowRange}),_=await h({sessionId:e.sessionId,runParams:e.runParams,packet:d,mode:t.mode,tools:g,reviewerAgent:p,diagnosticDispatcher:e.eventDispatcher});if(_.error){r=await ls({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await Os(e.runParams.dataDir,i,{status:`failed`,curatorResult:_,error:_.error,reviewState:r});await ws(e,_.error,{mode:t.mode,usage:_.usage,toolCalls:ks(_.toolCalls),toolResults:Is(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewRunLogPath:n});return}r=await cs({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let v=await Os(e.runParams.dataDir,i,{status:`completed`,curatorResult:_,reviewState:r});await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_completed`,message:`auto-skill review agent completed`,details:{mode:t.mode,usage:_.usage,text:Fs(_.text,2e3),toolCalls:ks(_.toolCalls),toolResults:Is(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewState:r,reviewRunLogPath:v}})}catch(t){let n=t instanceof Error?t.message:String(t),a;r&&(r=await ls({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await Os(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await ws(e,n,a?{reviewRunLogPath:a}:void 0)}}function ys(e){return{mode:bs(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function bs(e){if(e==null)return gs;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?_s.has(t)?t:`off`:gs}function xs(e){if(e.runParams.subagentContext)return`subagent`;if(e.runParams.channel===`CRON`)return`cron`;if(e.result.error)return`run_error`;if(e.result.paused)return`hitl_paused`;if(e.result.uiToolPending)return`ui_tool_pending`}function Ss(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function Cs(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function ws(e,t,n){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skill_review_failed`,message:`auto-skill review failed`,details:{...n??{},error:t}})}async function Ts(e,t,n,r={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:n===`run_error`?`warn`:`info`,scope:`skill`,phase:`auto_skill_review_skipped`,message:n===`reviewer_agent_missing`?`auto-skill review skipped because reviewer agent is missing`:`auto-skill review skipped before gate evaluation`,details:{mode:t.mode,reason:n,...r}})}async function Es(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function Ds(e,t,n,r,i={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_gated`,message:n.worthReview?`completed run is worth auto-skill review`:`completed run is not worth auto-skill review`,details:{mode:t.mode,worthReview:n.worthReview,skipped:n.skipped,...i.skipReason?{skipReason:i.skipReason}:{},transcriptEntryCount:r.length,transcriptStartIndex:e.transcriptStartIndex,reasons:n.reasons.map(e=>({code:e.code})),stats:n.stats,selectedGateScope:n.selectedGateScope,consideredGateScopes:n.consideredGateScopes,reviewCount:n.reviewCount,maxReviewsPerSession:n.maxReviewsPerSession,gateResults:Ps(n),...i.packet?{packet:i.packet}:{}}})}async function Os(e,t,n){return hs(e,{sessionId:t.packet.sessionId,mode:t.mode,status:n.status,selectedGateScope:t.decision.selectedGateScope,reviewCount:t.decision.reviewCount,reasons:t.decision.reasons.map(e=>e.code),currentRunRange:t.packet.currentRunRange,reviewWindowRange:t.packet.reviewWindowRange,conclusion:n.curatorResult?js(n.curatorResult.text):void 0,conclusionText:n.curatorResult?Ms(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?ks(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?Is(n.curatorResult.toolResults):void 0,writeResults:n.curatorResult?.writeResults,wrote:n.curatorResult?.wrote,error:n.error,reviewStateAfter:n.reviewState?{reviewCount:n.reviewState.reviewCount,lastReviewedTranscriptEndIndex:n.reviewState.lastReviewedTranscriptEndIndex}:void 0})}function ks(e){return e.map(e=>({...e,arguments:As(e.name,e.arguments)}))}function As(e,t){if(e!==`auto_skill_manage`)return t;let n={};for(let e of[`action`,`skillId`,`name`,`categoryPath`,`newCategory`])t[e]!==void 0&&(n[e]=t[e]);return n}function js(e){let t=Ns(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function Ms(e){return js(e)?void 0:Fs(e,8e3)}function Ns(e){let t=e.trim(),n=[t],r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);r?.[1]&&n.unshift(r[1].trim());let i=t.indexOf(`{`),a=t.lastIndexOf(`}`);return i>=0&&a>i&&n.push(t.slice(i,a+1)),Array.from(new Set(n.filter(Boolean)))}function Ps(e){return Object.fromEntries(Object.entries(e.gateResults).map(([e,t])=>[e,{configured:t.configured,passed:t.passed,reasons:t.reasons.map(e=>({code:e.code})),missingReasonCodes:t.missingReasonCodes,stats:t.stats}]))}function Fs(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function Is(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}const Ls=2,Rs=5;var zs=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),X.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:ha(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&&X.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){X.info(`subagent status changed`,t);return}if(e.status===`killed`){X.warn(`subagent status changed`,t);return}X.error(`subagent status changed`,t)}};const Bs=new Map;function Vs(e){let t=Bs.get(e);return t||(t={},Bs.set(e,t)),t}function Hs(e){Bs.delete(e)}let Us=!1;function Ws(){Us||=(et(),$e({api:`openai-completions`,stream:ki,streamSimple:Ai}),!0)}const Gs=[`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(`
25
+ `);async function Ks(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 Js(s);let c=r.flashModel,l=$r({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:Gs,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 qs(500*e)}return Js(s)}function qs(e){return new Promise(t=>setTimeout(t,e))}function Js(e,t=80){if(!e)return`New session`;try{let t=JSON.parse(e);if(Array.isArray(t))return t?.[0]?.content?.[0].text??e}catch{}let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}function Q(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}async function Ys(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 Xs(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e;await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher});let o=await m(r.dataDir,t,{...Q(r)});await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher})}async function Zs(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:a=!1,runParams:o,hookRegistry:s,hookContext:c,startTime:l,compactionEntry:u,eventDispatcher:d}=e,f=Q(o);if(a||await p(o.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},f),u&&await p(o.dataDir,n,u,f),await p(o.dataDir,n,{role:`assistant`,content:t,timestamp:new Date().toISOString()},f),r){let t=await Ks({message:i.trim()?i:`New session`,llm:o.llm,text:e.replyText,hooks:s,hookCtx:c});await x(o.dataDir,n,{title:t},f),await d.dispatchProgress(n,{type:`title_updated`,title:t})}let m=Date.now()-l,g={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:m,context:{snapshotPath:h(o.dataDir,n,Q(o)),toolResultsDir:S(o.dataDir,n,Q(o))}};return X.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:m,isNewSession:r,textLength:t.length,hasCompactionEntry:!!u,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir}),await Xs({sessionId:n,result:g,runParams:o,hookRegistry:s,hookContext:c,eventDispatcher:d}),g}async function Qs(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:a,hookContext:o,startTime:s,text:c,usage:l,error:u,paused:d,uiToolPending:f,eventDispatcher:p}=e;if(n){let n=Q(i),s=await Ks({message:r,llm:i.llm,text:e.text,hooks:a,hookCtx:o});await x(i.dataDir,t,{title:s},n),await p.dispatchProgress(t,{type:`title_updated`,title:s})}let m={sessionId:t,text:c,usage:l,durationMs:Date.now()-s,error:u,paused:d,uiToolPending:f,context:{snapshotPath:h(i.dataDir,t,Q(i)),toolResultsDir:S(i.dataDir,t,Q(i))}},g={sessionId:t,kind:`completed`,durationMs:m.durationMs,isNewSession:n,inputTokens:l.input,outputTokens:l.output,totalTokens:l.total,hasError:!!u,error:u,paused:!!d,uiToolPending:!!f,textLength:c.length,snapshotPath:m.context.snapshotPath,toolResultsDir:m.context.toolResultsDir};return u?X.warn(`agent run finalized with error`,g):X.info(`agent run finalized`,g),await Xs({sessionId:t,result:m,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:p}),m}const $s=new Set([`pause`,`resume`,`clear`,`help`]);async function ec(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`Goal objective cannot be empty`);let r=await z(e.dataDir,e.sessionId,t);if(!r)return{action:`created`,goal:await L(e.dataDir,e.sessionId,{goalId:Ge(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource})};if((await V(e.dataDir,e.sessionId,r,t)).trim()!==n)return{action:`replaced`,goal:await L(e.dataDir,e.sessionId,{goalId:Ge(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource})};if(r.status===`complete`)return{action:`unchanged`,goal:r};let i={};if(r.status===`paused`&&(i.status=`active`),e.tokenBudget!==void 0&&e.tokenBudget!==r.tokenBudget&&(i.tokenBudget=e.tokenBudget),Object.keys(i).length===0)return{action:`unchanged`,goal:r};let a=await I(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function tc(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if($s.has(n))return{action:n,objective:``};let r=t,i,a=r.match(/^--token-budget\s+(\S+)(?:\s+([\s\S]*))?$/);if(a){let e=a[1]??``;if(i=e===`0`?null:Number.parseInt(e,10),i!==null&&(!Number.isFinite(i)||i<=0))throw Error(`--token-budget must be a positive integer or 0 for unlimited`);r=(a[2]??``).trim()}if(!r)throw Error(`Usage: /goal <objective> or /goal --token-budget <n> <objective>`);return{action:`set`,objective:r,tokenBudget:i}}function nc(e,t){let n=e.tokenBudget===null?`Token budget: unlimited`:`Token budget: ${e.tokenBudget} (used ${e.tokensUsed}, remaining ${Math.max(0,e.tokenBudget-e.tokensUsed)})`;return[`Thread Goal`,`Status: ${e.status}`,`Objective: ${t.length>200?`${t.slice(0,200)}...`:t}`,n,`Time used: ${e.timeUsedSeconds}s`,``,rc(e.status)].join(`
26
+ `)}function rc(e){switch(e){case`active`:return`Commands: /goal pause, /goal clear`;case`paused`:return`Commands: /goal resume, /goal clear`;case`budget_limited`:return`Budget limited. Commands: /goal clear (do not declare complete solely due to budget)`;case`complete`:return`Goal complete. Commands: /goal clear`;default:return`Commands: /goal <objective>, /goal pause, /goal resume, /goal clear`}}async function ic(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:[`Goal commands`,` /goal <objective> Set or replace the thread goal (active)`,` /goal --token-budget <n> <text> Set goal with token budget (0 = unlimited)`,` /goal Show current goal summary`,` /goal pause Pause goal continuation`,` /goal resume Resume a paused goal`,` /goal clear Remove the goal`].join(`
27
+ `)};if(e.action===`get`){let e=await z(t.dataDir,t.sessionId,n);return e?{replyText:nc(e,await V(t.dataDir,t.sessionId,e,n))}:{replyText:[`No thread goal is set for this session.`,``,`Usage: /goal <objective>`,`Example: /goal improve benchmark coverage`].join(`
28
+ `)}}if(e.action===`set`){let r=await ec({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await V(t.dataDir,t.sessionId,r.goal,n);return r.action===`unchanged`?{replyText:r.goal.status===`complete`?`Goal is already complete.\n\n${nc(r.goal,i)}`:`Goal unchanged.\n\n${nc(r.goal,i)}`}:{replyText:`${r.action===`resumed`?`Goal resumed (active).`:r.action===`updated`?`Goal updated.`:`Goal set (active).`}\n\n${nc(r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await z(t.dataDir,t.sessionId,n);if(!e)throw Error(`No goal exists for this session`);if(e.status===`complete`)throw Error(`Cannot pause a completed goal`);if(e.status===`paused`)return{replyText:`Goal is already paused. Use /goal resume to continue.`};let r=await I(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`Goal paused.\n\n${nc(r,await V(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await z(t.dataDir,t.sessionId,n);if(!e)throw Error(`No goal exists for this session`);if(e.status===`complete`)throw Error(`Cannot resume a completed goal`);if(e.status===`budget_limited`)throw Error(`Cannot resume a budget-limited goal; clear or replace it instead`);if(e.status===`active`)return{replyText:`Goal is already active.\n\n${nc(e,await V(t.dataDir,t.sessionId,e,n))}`};let r=await I(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`Goal resumed (active).\n\n${nc(r,await V(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await H(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`Goal cleared.`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`No goal was set.`}:{replyText:`Unknown /goal command. Try /goal help.`}}const ac=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`},{name:`/goal`,description:`设置或查看线程目标`},{name:`/goal pause`,description:`暂停线程目标`},{name:`/goal resume`,description:`恢复线程目标`},{name:`/goal clear`,description:`清除线程目标`}];function oc(){return ac.map(e=>({...e}))}function sc(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function cc(e){let t=new Set,n=[];for(let r of e){let e=sc(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function lc(e){let t=oc(),n=cc(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function uc(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 dc(e){let t=uc(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 fc(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 pc(e,t){let n=dc(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===`goal`)try{let e=tc(n.rest);return{kind:`goal`,action:e.action,objective:e.objective,tokenBudget:e.tokenBudget}}catch(e){return{kind:`unknown`,name:n.name,args:e.message}}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:sc(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(cc(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 mc=new Set([`/new`,`/reset`,`/compact`]),hc=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),gc=new Set([`/help`]);function _c(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function vc(e){if(e.length===0)return[];let t=e.map(_c),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function yc(e){let t=lc(e.skills),n=t.builtin.filter(e=>mc.has(e.name)),r=t.builtin.filter(e=>hc.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>gc.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...vc(n)),s.push(``),s.push(`目标命令`),s.push(...vc(r)),s.push(``),s.push(`技能命令`),s.push(...vc(i)),o.length>0?(s.push(...vc(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...vc(a)),{kind:`reply`,text:s.join(`
29
+ `)}}function bc(e,t){let n=t.trim().toLowerCase();return n&&cc(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function xc(e){let t=bc(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(`
30
+
31
+ `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function Sc(e){let t=pc(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?yc(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?xc({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:t.kind===`unknown`&&t.name===`goal`?{kind:`reply`,text:t.args||`Usage: /goal <objective> | /goal pause | /goal resume | /goal clear`}:{kind:`pass`,message:e.message}}function Cc(e){return Math.ceil(e.length/4*1.2)}function wc(e){if(e.role===`user`)return Cc(e.content);if(e.role===`assistant`){let t=Cc(e.content);e.errorMessage&&(t+=Cc(e.errorMessage));for(let n of e.toolCalls??[])t+=Cc(n.name)+Cc(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(`
32
+ `):e.content;return Cc(e.toolName)+Cc(t)}function $(e){return e.reduce((e,t)=>e+wc(t),0)}const Tc=[`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(`
33
+ `);async function Ec(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Oc(t,r,i),l,u=$r({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:Tc,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 Dc(500*e)}throw l}function Dc(e){return new Promise(t=>setTimeout(t,e))}function Oc(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`?kc(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(`
34
34
  `):t.content,i=n.length>2e3?`${n.slice(0,2e3)}… [truncated]`:n;r.push(`Tool(${t.toolName})[${e}]: ${i}`)}return r.join(`
35
- `)}function Oc(e){let t=kc(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(`
36
- `)}function kc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Ac(t);if(e.name||e.path)return e}return{}}function Ac(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 jc(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Cc(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function Mc(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 Nc(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Pc(t),l=c>=0?t[c].content:void 0,u=Mc(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}=jc(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:$(u)}:{status:`compacted`,entry:{role:`compaction`,content:await Tc({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:$(d)}}function Pc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Fc=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
37
- `),Ic=[`.aimax/new.txt`];async function Lc(e){try{return(await Be(e,`utf-8`)).trim()||null}catch{return null}}async function Rc(e){for(let t of Ic){let n=await Lc(Ve(e,t));if(n)return n}return await Lc(`/aimax/new.txt`)||Fc}async function zc(e){return{kind:`reply`,text:await Rc(e)}}function Bc(){return{kind:`reply`,text:`✅ Session reset.`}}function Vc(e){let t=Wc(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Gc(r):null,a=n??i?.text,o=a?dc(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Kc(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:qc(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Hc(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=fc(e.slashCommandSource,t);if(n.kind===`goal`)return{kind:`goal`,action:n.action,objective:n.objective,tokenBudget:n.tokenBudget,transcriptMessage:e.transcriptMessage};let r=xc({message:e.messageForRun??``,skills:t});if(r.kind===`reply`)return{kind:`reply`,replyText:r.text,transcriptMessage:e.transcriptMessage};if(r.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:r.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(r.kind===`rewrite`){let t=e.inputMode===`text`?r.message:Kc(e.promptInput,r.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:qc(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Uc(e){let t=Hc(e.invocation,e.skills);if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await Xs({replyText:(t.action===`reset`?Bc():await zc(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await Xs({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`goal`){let n;try{n=await rc({action:t.action,objective:t.objective,tokenBudget:t.tokenBudget},{dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName})}catch(e){n={replyText:`Goal error: ${e.message}`}}return n.goalUpdate&&(await tn(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),Jc(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await H(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await Xs({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}let n=await Nc({entries:e.runParams.channel===`CRON`?[]:await m(e.runParams.dataDir,e.sessionId,Q(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await Xs({replyText:n.status===`compacted`?`⚙️ Compacted (kept ${n.keptCount}, dropped ${n.droppedCount}).`:`⚙️ Compaction skipped: ${n.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function Wc(e){return typeof e.message==`string`}function Gc(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 Kc(e,t){let n=Gc(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 qc(e){return typeof e==`string`?e:JSON.stringify(e)}function Jc(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}function Yc(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 Xc=[`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.`],Zc={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Qc(e,t){return e.map(e=>$c(e,t))}function $c(e,t){let n=new Date(e.timestamp).getTime();if(el(e))return{role:`user`,content:e.content,timestamp:n};if(tl(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:Zc,stopReason:e.stopReason??`stop`,errorMessage:e.errorMessage,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:nl(r)}],isError:r.isError,timestamp:n}}function el(e){return e.role===`user`}function tl(e){return e.role===`assistant`}function nl(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:`,...Xc];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
38
- `)}const rl=[`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 il(e){let t=h(e.dataDir,e.sessionId,e),n=new Map,r=new Map,i=[],o=[],s=[],c,l,u=0,d,f,p=await ll(t);for(let e of p.readStates)n.set(al(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);i.push(...p.compaction.budgets),o.push(...p.compaction.snips),s.push(...p.compaction.collapseSpans),c=p.compaction.sessionMemory,l=p.compaction.modelUsage,u=p.compaction.consecutiveAutocompactFailures,d=p.compaction.lastCompactionAt,f=p.compaction.lastCompactionLayer;let m=async()=>{let p={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await G.mkdir(K.dirname(t),{recursive:!0});let m=e.encryptSessions??!1;await a(t,JSON.stringify(p,null,2),m)};return{async findReusableRead(e,t,r){let i=al(e,t,r),a=n.get(i);if(!a)return null;let o=await sl(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:cl(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await sl(e.path)??Date.now()};return n.set(al(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())ol(i.path)===ol(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=S(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=K.join(s,c);await G.mkdir(s,{recursive:!0});let u=e.encryptSessions??!1;await a(l,t.content,u);let p=K.relative(e.dataDir,l).split(K.sep).join(`/`),h=pl(t.content,o),g={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:p,preview:h,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(g.toolCallId,g),i.push({toolCallId:g.toolCallId,toolName:g.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:h.length,strategy:`persist`,createdAt:g.createdAt}),d=g.createdAt,f=`L2`,await m(),{content:fl(g),reference:g}},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 ml(e.dataDir,e.sessionId,t,e),await m()},async recordModelUsage(e){l=e,await m()},async recordAutocompactResult(e){u=e.failed?u+1:0,d=e.timestamp,f=`L6`,await m()},getSnapshot(){return{version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function al(e,t,n){return`${ol(e)}::${t??``}::${n??``}`}function ol(e){return K.normalize(e)}async function sl(e){try{return(await G.stat(e)).mtimeMs}catch{return null}}function cl(e){return Ue(`sha1`).update(e).digest(`hex`)}async function ll(e){try{let t=await l(e);if(t===null)return ul();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?ul():{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:dl(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 ul()}}function ul(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function dl(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 fl(e){let t=e.preview.length<e.originalChars?`
39
- ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...rl,`Preview:`,e.preview+t].join(`
40
- `)}function pl(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
41
- `),r=n>t*.5?n:t;return e.slice(0,r)}async function ml(e,t,r,i){let o=n(e,t,i);await G.mkdir(K.dirname(o),{recursive:!0});let s=i?.encryptSessions??!1;await a(o,JSON.stringify(r,null,2),s)}const hl=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function gl(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,signal:c,hooks:l,hookCtx:u,contextStore:d,dataDir:f,sessionId:p,sessionStoreName:m,sessionPathScope:h}=e,g,_=Ol(t),v=_>=0?t.slice(_+1):t;_>=0&&(g=t[_].content);let y=t.length,b=Mc(Yc(v,a)),x=[];d&&(g=await _l({entries:b,existingSummary:g,llm:i,contextStore:d,signal:c,hooks:l,hookCtx:u}));let S=b;if(S=await vl({entries:S,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:d,compactionEvents:x}),S=await yl({entries:S,contextStore:d,compactionEvents:x}),S=await bl({entries:S,contextStore:d,compactionEvents:x,dataDir:f,sessionId:p,sessionStoreName:m,sessionPathScope:h}),!o)return{messages:Qc(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:$(S),compacted:!1},compactionEvents:x};let C=d?.getSnapshot(),w=Math.max(1e3,Math.floor(r*.7)),T=kl({entries:t,workingEntries:S,pendingUserMessage:s,checkpoint:C?.compaction.modelUsage}).projectedInputTokens>=w,E=C?.compaction.consecutiveAutocompactFailures??0;if(!T||E>=3)return{messages:Qc(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:$(S),compacted:!1},compactionEvents:x};let{toKeep:D,toSummarise:O}=jc(S,r);if(O.length===0)return{messages:Qc(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:$(S),compacted:!1},compactionEvents:x};let k=new Date().toISOString();try{let e=C?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Tc({entries:O,llm:i,previousSummary:g,signal:c,hooks:l,hookCtx:u}),r={role:`compaction`,content:t,keptCount:D.length,droppedCount:O.length,timestamp:k};return await d?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:k}),x.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${O.length} entries with session memory`:`Autocompact summarised ${O.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,$(O)),affectedEntries:O.length,snapshotVersion:2}),{messages:Qc(Mc(D),n),priorSummary:t,compactionEntry:r,stats:{originalCount:y,keptCount:D.length,estimatedTokens:$(D),compacted:!0},compactionEvents:x}}catch{return await d?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:k}),{messages:Qc(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:$(S),compacted:!1},compactionEvents:[...x,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function _l(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=$(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&Dl(t)>=3;if(!u&&!d)return n??l?.summary;let f=await Tc({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 vl(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Sl).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(!Sl(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=Cl(n)?wl(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
42
- `);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}),Mc(l.reverse())}async function yl(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-1728e5,a=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]),o=a.length>=3?a[a.length-3]??t.length:t.length,s=0,c=0,l=[];for(let[e,r]of t.entries()){if(!Sl(r)){l.push(r);continue}if(e>=o){l.push(r);continue}let t=Date.parse(r.timestamp);if(!(t>0&&t<i)){l.push(r);continue}let a=Cl(r)?wl(r):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${r.toolName}`,`Preview:\n${r.toolResultRef?.preview?.trim()||r.content.slice(0,400).trim()}`].join(`
43
- `);a!==r.content&&(s+=1,c+=Math.max(0,Math.floor((r.content.length-a.length)/4)),await n?.recordSnip({toolCallId:r.toolCallId,toolName:r.toolName,originalChars:r.content.length,retainedChars:a.length,reason:`microcompact`,createdAt:new Date().toISOString()})),l.push({...r,content:a})}return s===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${s} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:c,affectedEntries:s,snapshotVersion:2}),vl({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function bl(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o,sessionPathScope:s}=e,c={storeName:o,...s},l=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(l.length<=2)return t;let u=l[l.length-2]??t.length,d=[],f=0,p=0,m=0;for(;f<t.length;){if(f>=u||t[f]?.role===`user`){d.push(t[f]),f+=1;continue}let e=f;for(;f<u&&t[f]?.role!==`user`;)f+=1;let r=t.slice(e,f),o=r.filter(Sl).filter(e=>hl.has(e.toolName)),s=o.reduce((e,t)=>e+t.content.length,0);if(o.length<3||s<1500){d.push(...r);continue}let l=xl(r,o),h=new Date().toISOString(),g={role:`assistant`,content:l,timestamp:h};d.push(g),p+=r.length,m+=Math.max(0,Math.floor($(r)-$([g])));let _={id:We(),layer:`L5`,startEntryIndex:e,endEntryIndex:f-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:m,createdAt:h};await n?.recordCollapse(_),i&&a&&await Al(i,a,_,c)}return p>0&&r.push({type:`compaction`,reason:`Collapsed ${p} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:m,affectedEntries:p,snapshotVersion:2}),d}function xl(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(`
35
+ `)}function kc(e){let t=Ac(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(`
36
+ `)}function Ac(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=jc(t);if(e.name||e.path)return e}return{}}function jc(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 Mc(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=wc(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function Nc(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 Pc(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Fc(t),l=c>=0?t[c].content:void 0,u=Nc(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}=Mc(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:$(u)}:{status:`compacted`,entry:{role:`compaction`,content:await Ec({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:$(d)}}function Fc(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Ic=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
37
+ `),Lc=[`.aimax/new.txt`];async function Rc(e){try{return(await Ve(e,`utf-8`)).trim()||null}catch{return null}}async function zc(e){for(let t of Lc){let n=await Rc(He(e,t));if(n)return n}return await Rc(`/aimax/new.txt`)||Ic}async function Bc(e){return{kind:`reply`,text:await zc(e)}}function Vc(){return{kind:`reply`,text:`✅ Session reset.`}}function Hc(e){let t=Gc(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Kc(r):null,a=n??i?.text,o=a?fc(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?qc(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Jc(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Uc(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=pc(e.slashCommandSource,t);if(n.kind===`goal`)return{kind:`goal`,action:n.action,objective:n.objective,tokenBudget:n.tokenBudget,transcriptMessage:e.transcriptMessage};let r=Sc({message:e.messageForRun??``,skills:t});if(r.kind===`reply`)return{kind:`reply`,replyText:r.text,transcriptMessage:e.transcriptMessage};if(r.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:r.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(r.kind===`rewrite`){let t=e.inputMode===`text`?r.message:qc(e.promptInput,r.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Jc(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Wc(e){let t=Uc(e.invocation,e.skills);if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await Zs({replyText:(t.action===`reset`?Vc():await Bc(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await Zs({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`goal`){let n;try{n=await ic({action:t.action,objective:t.objective,tokenBudget:t.tokenBudget},{dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName})}catch(e){n={replyText:`Goal error: ${e.message}`}}return n.goalUpdate&&(await nn(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),Yc(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await V(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await Zs({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}let n=await Pc({entries:e.runParams.channel===`CRON`?[]:await m(e.runParams.dataDir,e.sessionId,Q(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await Zs({replyText:n.status===`compacted`?`⚙️ Compacted (kept ${n.keptCount}, dropped ${n.droppedCount}).`:`⚙️ Compaction skipped: ${n.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function Gc(e){return typeof e.message==`string`}function Kc(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 qc(e,t){let n=Kc(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 Jc(e){return typeof e==`string`?e:JSON.stringify(e)}function Yc(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}function Xc(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 Zc=[`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.`],Qc={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function $c(e,t){return e.map(e=>el(e,t))}function el(e,t){let n=new Date(e.timestamp).getTime();if(tl(e))return{role:`user`,content:e.content,timestamp:n};if(nl(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:Qc,stopReason:e.stopReason??`stop`,errorMessage:e.errorMessage,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:rl(r)}],isError:r.isError,timestamp:n}}function tl(e){return e.role===`user`}function nl(e){return e.role===`assistant`}function rl(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:`,...Zc];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
38
+ `)}function il(e){return{enabled:e?.enabled!==!1,minUserTurns:e?.minUserTurns??4,minEstimatedTokens:e?.minEstimatedTokens??4e3,recentProtectedTurnCount:e?.recentProtectedTurnCount??2,maxCandidates:e?.maxCandidates??40,maxSelectedTurns:e?.maxSelectedTurns??8,maxCandidateUserChars:e?.maxCandidateUserChars??600,maxCandidateAssistantChars:e?.maxCandidateAssistantChars??1e3,timeoutMs:e?.timeoutMs??2e4,maxTokens:e?.maxTokens??4096}}function al(e){let t=ll(e.entries),n=new Set(e.decision.selectedTurnIds),r=e.recentProtectedTurnCount>0?t.slice(-e.recentProtectedTurnCount):[],i=r.map(e=>e.turnId);for(let e of r)n.add(e.turnId);let a=[],o=[],s=[];for(let e of t){if(!n.has(e.turnId)){s.push(e.turnId);continue}a.push({turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex}),o.push(...e.entries)}return{entries:o,recentTurnIds:i,selectedRanges:a,droppedTurnIds:s}}async function ol(e){let t=il(e.config);if(!t.enabled||e.isSubagent||e.channel===`TASK`||e.channel===`CRON`||!e.pendingUserMessage?.trim())return;let n=ll(e.entries),r=$(e.entries);if(n.length<t.minUserTurns||r<t.minEstimatedTokens)return;let i=n.slice(-t.maxCandidates).map(e=>ul(e,t)),a=new Set(i.map(e=>e.turnId)),o=e.llm.flashModel||e.llm.model,s=new Date().toISOString();try{let n=await sl({currentUserMessage:e.pendingUserMessage,candidates:i,llm:{baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,model:o},config:t,signal:e.signal}),c=n.selectedTurnIds.filter(e=>!a.has(e));if(c.length>0)throw Error(`Topic segmentation returned unknown turn ids: ${c.join(`, `)}`);n.selectedTurnIds.length>t.maxSelectedTurns&&(n.selectedTurnIds=n.selectedTurnIds.slice(0,t.maxSelectedTurns));let l=al({entries:e.entries,candidates:i,decision:n,recentProtectedTurnCount:t.recentProtectedTurnCount}),u=dl({timestamp:s,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:i,decision:n,projected:l,tokenEstimateBefore:r,tokenEstimateAfter:$(l.entries)});return await pl(e,u),{entries:l.entries,audit:u}}catch(t){await pl(e,fl({timestamp:s,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:i,tokenEstimateBefore:r,reason:t instanceof Error?t.message:String(t)}));return}}async function sl(e){return cl((await $r({baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:gl,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,candidates:e.candidates,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxSelectedTurns:e.config.maxSelectedTurns},null,2),temperature:0,maxTokens:e.config.maxTokens,timeoutMs:e.config.timeoutMs,signal:e.signal})).text)}function cl(e){let t=e.trim();if(!t)throw Error(`Topic segmentation returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t,i=JSON.parse(r);if(i.version!==1||!Array.isArray(i.selectedTurnIds))throw Error(`Topic segmentation decision has invalid schema.`);return{version:1,selectedTurnIds:i.selectedTurnIds.filter(e=>typeof e==`string`),reason:typeof i.reason==`string`?i.reason:``,confidence:i.confidence===`high`||i.confidence===`medium`||i.confidence===`low`?i.confidence:`low`,currentTopicLabel:typeof i.currentTopicLabel==`string`?i.currentTopicLabel:void 0}}function ll(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,entries:[a],user:a.content,timestamp:a.timestamp};continue}n&&(n.entries.push(a),n.endIndex=i)}return r(),t}function ul(e,t){let n=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim()),r=new Set,i=!1;for(let t of e.entries){if(t.role===`assistant`){for(let e of t.toolCalls??[])r.add(e.name);t.stopReason===`error`&&(i=!0);continue}hl(t)&&(r.add(t.toolName),t.isError&&(i=!0))}return{turnId:e.turnId,startIndex:e.startIndex,endIndex:n?e.entries.indexOf(n)+e.startIndex:e.endIndex,user:ml(e.user,t.maxCandidateUserChars),assistant:n?ml((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function dl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:ml(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,selectedTurnIds:e.decision.selectedTurnIds,selectedRanges:e.projected.selectedRanges,forcedKeep:{recentTurnIds:e.projected.recentTurnIds},droppedTurnIds:e.projected.droppedTurnIds,confidence:e.decision.confidence,reason:e.decision.reason,tokenEstimate:{before:e.tokenEstimateBefore,after:e.tokenEstimateAfter}}}function fl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:ml(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,selectedTurnIds:[],selectedRanges:[],forcedKeep:{recentTurnIds:[]},droppedTurnIds:[],confidence:`low`,reason:`Topic segmentation fell back to full history.`,fallback:{used:!0,reason:ml(e.reason,500)},tokenEstimate:{before:e.tokenEstimateBefore,after:e.tokenEstimateBefore}}}async function pl(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=d(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await W.mkdir(n,{recursive:!0}),await W.appendFile(G.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function ml(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function hl(e){return e.role===`tool_result`}const gl=[`You classify conversation topic relevance for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurnIds":["..."],"reason":"...","confidence":"high|medium|low","currentTopicLabel":"optional"}`,`Task: select historical user turns relevant to the current user message.`,`Relevant includes same task continuation, follow-up, correction, reuse of previous artifact, explicit reference, or ambiguous references like 'this', 'above', 'just now'.`,`Do not answer the user. Do not rewrite the user message.`,`Do not select unrelated old topics.`,`Compaction entries are not candidates and have no special retention rule.`].join(`
39
+ `),_l=[`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 vl(e){let t=h(e.dataDir,e.sessionId,e),n=new Map,r=new Map,i=[],o=[],s=[],c,l,u=0,d,f,p=await Cl(t);for(let e of p.readStates)n.set(yl(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);i.push(...p.compaction.budgets),o.push(...p.compaction.snips),s.push(...p.compaction.collapseSpans),c=p.compaction.sessionMemory,l=p.compaction.modelUsage,u=p.compaction.consecutiveAutocompactFailures,d=p.compaction.lastCompactionAt,f=p.compaction.lastCompactionLayer;let m=async()=>{let p={version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await W.mkdir(G.dirname(t),{recursive:!0});let m=e.encryptSessions??!1;await a(t,JSON.stringify(p,null,2),m)};return{async findReusableRead(e,t,r){let i=yl(e,t,r),a=n.get(i);if(!a)return null;let o=await xl(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:Sl(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await xl(e.path)??Date.now()};return n.set(yl(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())bl(i.path)===bl(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=S(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=G.join(s,c);await W.mkdir(s,{recursive:!0});let u=e.encryptSessions??!1;await a(l,t.content,u);let p=G.relative(e.dataDir,l).split(G.sep).join(`/`),h=Dl(t.content,o),g={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:p,preview:h,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(g.toolCallId,g),i.push({toolCallId:g.toolCallId,toolName:g.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:h.length,strategy:`persist`,createdAt:g.createdAt}),d=g.createdAt,f=`L2`,await m(),{content:El(g),reference:g}},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 Ol(e.dataDir,e.sessionId,t,e),await m()},async recordModelUsage(e){l=e,await m()},async recordAutocompactResult(e){u=e.failed?u+1:0,d=e.timestamp,f=`L6`,await m()},getSnapshot(){return{version:2,updatedAt:new Date().toISOString(),readStates:Array.from(n.values()),toolResults:Array.from(r.values()).slice(-100),compaction:{sessionMemory:c,modelUsage:l,budgets:i.slice(-200),snips:o.slice(-200),collapseSpans:s.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function yl(e,t,n){return`${bl(e)}::${t??``}::${n??``}`}function bl(e){return G.normalize(e)}async function xl(e){try{return(await W.stat(e)).mtimeMs}catch{return null}}function Sl(e){return We(`sha1`).update(e).digest(`hex`)}async function Cl(e){try{let t=await l(e);if(t===null)return wl();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?wl():{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:Tl(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 wl()}}function wl(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Tl(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 El(e){let t=e.preview.length<e.originalChars?`
40
+ ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,..._l,`Preview:`,e.preview+t].join(`
41
+ `)}function Dl(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
42
+ `),r=n>t*.5?n:t;return e.slice(0,r)}async function Ol(e,t,r,i){let o=n(e,t,i);await W.mkdir(G.dirname(o),{recursive:!0});let s=i?.encryptSessions??!1;await a(o,JSON.stringify(r,null,2),s)}const kl=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Al(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,topicSegmentation:c,signal:l,hooks:u,hookCtx:d,contextStore:f,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g,channel:_,isSubagent:v}=e,y,b=Hl(t),x=b>=0?t.slice(b+1):t;b>=0&&(y=t[b].content);let S=t.length,C=Nc(Xc(x,a)),w=[],T=(await ol({entries:C,fullTranscript:t,pendingUserMessage:s,llm:i,config:c,sessionId:m,dataDir:p,sessionStoreName:h,sessionPathScope:g,channel:_,isSubagent:v,signal:l}))?.entries??C;f&&(y=await jl({entries:T,existingSummary:y,llm:i,contextStore:f,signal:l,hooks:u,hookCtx:d}));let E=T;if(E=await Ml({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:w}),E=await Nl({entries:E,contextStore:f,compactionEvents:w}),E=await Pl({entries:E,contextStore:f,compactionEvents:w,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g}),!o)return{messages:$c(E,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:E.length,estimatedTokens:$(E),compacted:!1},compactionEvents:w};let D=f?.getSnapshot(),O=Math.max(1e3,Math.floor(r*.7)),k=Ul({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:D?.compaction.modelUsage}).projectedInputTokens>=O,ee=D?.compaction.consecutiveAutocompactFailures??0;if(!k||ee>=3)return{messages:$c(E,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:E.length,estimatedTokens:$(E),compacted:!1},compactionEvents:w};let{toKeep:A,toSummarise:j}=Mc(E,r);if(j.length===0)return{messages:$c(E,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:E.length,estimatedTokens:$(E),compacted:!1},compactionEvents:w};let M=new Date().toISOString();try{let e=D?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Ec({entries:j,llm:i,previousSummary:y,signal:l,hooks:u,hookCtx:d}),r={role:`compaction`,content:t,keptCount:A.length,droppedCount:j.length,timestamp:M};return await f?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:M}),w.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${j.length} entries with session memory`:`Autocompact summarised ${j.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,$(j)),affectedEntries:j.length,snapshotVersion:2}),{messages:$c(Nc(A),n),priorSummary:t,compactionEntry:r,stats:{originalCount:S,keptCount:A.length,estimatedTokens:$(A),compacted:!0},compactionEvents:w}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:M}),{messages:$c(E,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:E.length,estimatedTokens:$(E),compacted:!1},compactionEvents:[...w,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function jl(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=$(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&Vl(t)>=3;if(!u&&!d)return n??l?.summary;let f=await Ec({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 Ml(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Il).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(!Il(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=Ll(n)?Rl(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
43
+ `);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}),Nc(l.reverse())}async function Nl(e){let{entries:t,contextStore:n,compactionEvents:r}=e,i=Date.now()-1728e5,a=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]),o=a.length>=3?a[a.length-3]??t.length:t.length,s=0,c=0,l=[];for(let[e,r]of t.entries()){if(!Il(r)){l.push(r);continue}if(e>=o){l.push(r);continue}let t=Date.parse(r.timestamp);if(!(t>0&&t<i)){l.push(r);continue}let a=Ll(r)?Rl(r):[`[microcompact] Tool output aged out of the hot context window.`,`Tool: ${r.toolName}`,`Preview:\n${r.toolResultRef?.preview?.trim()||r.content.slice(0,400).trim()}`].join(`
44
+ `);a!==r.content&&(s+=1,c+=Math.max(0,Math.floor((r.content.length-a.length)/4)),await n?.recordSnip({toolCallId:r.toolCallId,toolName:r.toolName,originalChars:r.content.length,retainedChars:a.length,reason:`microcompact`,createdAt:new Date().toISOString()})),l.push({...r,content:a})}return s===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${s} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:c,affectedEntries:s,snapshotVersion:2}),Ml({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Pl(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o,sessionPathScope:s}=e,c={storeName:o,...s},l=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(l.length<=2)return t;let u=l[l.length-2]??t.length,d=[],f=0,p=0,m=0;for(;f<t.length;){if(f>=u||t[f]?.role===`user`){d.push(t[f]),f+=1;continue}let e=f;for(;f<u&&t[f]?.role!==`user`;)f+=1;let r=t.slice(e,f),o=r.filter(Il).filter(e=>kl.has(e.toolName)),s=o.reduce((e,t)=>e+t.content.length,0);if(o.length<3||s<1500){d.push(...r);continue}let l=Fl(r,o),h=new Date().toISOString(),g={role:`assistant`,content:l,timestamp:h};d.push(g),p+=r.length,m+=Math.max(0,Math.floor($(r)-$([g])));let _={id:Ge(),layer:`L5`,startEntryIndex:e,endEntryIndex:f-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:m,createdAt:h};await n?.recordCollapse(_),i&&a&&await Wl(i,a,_,c)}return p>0&&r.push({type:`compaction`,reason:`Collapsed ${p} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:m,affectedEntries:p,snapshotVersion:2}),d}function Fl(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(`
44
45
  `),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
45
46
  `);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
46
47
 
47
- `)}function Sl(e){return e.role===`tool_result`}function Cl(e){return e.toolName===`skill_load`}function wl(e){let t=Tl(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(`
48
- `)}function Tl(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=El(t);if(e.name||e.path)return e}return{}}function El(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 Dl(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Ol(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function kl(e){let t=e.pendingUserMessage?.trim()?$([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=$(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=$(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 Al(e,t,n,r){let i=k(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0}),await G.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function jl(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await il({dataDir:e.dataDir,sessionId:e.sessionId,...t});return{async getReusableRead(e,t,r){let i=await n.findReusableRead(e,t,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await n.recordRead(e)},async invalidateReadPath(e){await n.invalidatePath(e)},persistToolResult(e){return n.persistToolResult(e)},async recordModelUsage(e){await n.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(t){return gl({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Ml(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}):gl({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})}const Nl=q.Object({command:q.String({description:`Shell command to execute`}),workdir:q.Optional(q.String({description:`Working directory (relative to workspace root)`})),env:q.Optional(q.Record(q.String(),q.String())),timeout:q.Optional(q.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:q.Optional(q.Number({description:`Wait this many milliseconds before returning running state`})),background:q.Optional(q.Boolean({description:`Return immediately with running session`}))});function Pl(e,t,n){return Math.max(t,Math.min(n,e))}function Fl(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Il(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:Pl(Math.floor(e),0,12e4)}function Ll(e,t){if(!t?.trim())return e;let n=K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t));if(!n.startsWith(e+K.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Rl(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 zl(e){return Vl({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
49
- `)}function Bl(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Vl(e){let t=Bl(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 Hl(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:Nl,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=Ll(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Fl(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,Il(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Rl(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?Vl({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[zl(l)],p=Bl(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(`
50
- `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Ul=q.Object({action:q.String({description:`Process action: list | poll | log | kill`}),sessionId:q.Optional(q.String({description:`Session id for non-list actions`})),offset:q.Optional(q.Number({description:`Log line offset (0-based)`})),limit:q.Optional(q.Number({description:`Maximum lines to return`})),timeout:q.Optional(q.Number({description:`Poll wait time in milliseconds`}))});function Wl(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Gl(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Kl(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:Ul,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(`
51
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Gl(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Wl(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`}}:Gl(`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}}:Gl(`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}}:Gl(`No session found for ${i}`)}return Gl(`Unsupported action: ${n.action}`)}}}const ql=2e5;function Jl(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Yl(e,t){let n=e+t;return n.length<=ql?{text:n,truncated:!1}:{text:n.slice(-ql),truncated:!0}}function Xl(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Yl(e.output,r);e.output=i.text;let a=Yl(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Zl(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:Jl(e.output),stdoutTail:Jl(e.stdout),stderrTail:Jl(e.stderr),outputTruncated:e.outputTruncated}}function Ql(e,t){return t?e.scopeKey===t:!0}function $l(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function eu(e){return e?e.split(/\r?\n/):[]}function tu(e){let t=eu(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=$l(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(`
52
- `);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 nu(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function ru(){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),nu(e))};return{start(t){let n=ut(`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:We(),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=>Xl(o,`stdout`,e)),n.stderr.on(`data`,e=>Xl(o,`stderr`,e));let s=$l(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Xl(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`),Xl(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`)})}),Zl(o)},get(e,t){let n=r(e);return!n||!Ql(n,t)?null:Zl(n)},list(n){return[...e.values(),...t.values()].filter(e=>Ql(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Zl(e))},async wait(e,t,n){let i=r(e);if(!i||!Ql(i,t))return null;if(i.status!==`running`)return Zl(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||!Ql(a,t)?null:Zl(a)},readLog(e){let t=r(e.sessionId);return!t||!Ql(t,e.scopeKey)?null:tu({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Ql(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||!Ql(n,t))return null;if(n.status!==`running`)return Zl(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?Zl(i):null}}}function iu(e){return Hl({workspaceDir:e,registry:ru(),scopeKey:e})}const au=5*1024*1024,ou=2e3;async function su(e,t){e&&await e(t).catch(()=>{})}function cu(e,t){return K.isAbsolute(e)?K.normalize(e):K.normalize(K.join(t,e))}const lu=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),offset:q.Optional(q.Number({description:`Line offset (1-based, default: 1)`})),limit:q.Optional(q.Number({description:`Maximum lines to read (default: 2000)`}))});function uu(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:lu,async execute(n,r){let i;try{i=cu(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 G.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 dt(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>au){let e=o.slice(0,au).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${au} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
53
- `),l=Math.max(1,r.offset??1),u=Math.min(ou,r.limit??ou),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(`
48
+ `)}function Il(e){return e.role===`tool_result`}function Ll(e){return e.toolName===`skill_load`}function Rl(e){let t=zl(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(`
49
+ `)}function zl(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Bl(t);if(e.name||e.path)return e}return{}}function Bl(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 Vl(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Hl(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Ul(e){let t=e.pendingUserMessage?.trim()?$([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=$(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=$(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 Wl(e,t,n,r){let i=k(e,t,r);await W.mkdir(G.dirname(i),{recursive:!0}),await W.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Gl(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await vl({dataDir:e.dataDir,sessionId:e.sessionId,...t});return{async getReusableRead(e,t,r){let i=await n.findReusableRead(e,t,r);return i?{reused:!0,lineCount:i.lineCount}:{reused:!1}},async rememberRead(e){await n.recordRead(e)},async invalidateReadPath(e){await n.invalidatePath(e)},persistToolResult(e){return n.persistToolResult(e)},async recordModelUsage(e){await n.recordModelUsage({version:1,model:e.model,inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,coveredTranscriptEntryCount:e.coveredTranscriptEntryCount,recordedAt:new Date().toISOString()})},manageHistory(t){return Al({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Kl(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent}):Al({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent})}const ql=K.Object({command:K.String({description:`Shell command to execute`}),workdir:K.Optional(K.String({description:`Working directory (relative to workspace root)`})),env:K.Optional(K.Record(K.String(),K.String())),timeout:K.Optional(K.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:K.Optional(K.Number({description:`Wait this many milliseconds before returning running state`})),background:K.Optional(K.Boolean({description:`Return immediately with running session`}))});function Jl(e,t,n){return Math.max(t,Math.min(n,e))}function Yl(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Xl(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:Jl(Math.floor(e),0,12e4)}function Zl(e,t){if(!t?.trim())return e;let n=G.isAbsolute(t)?G.normalize(t):G.normalize(G.join(e,t));if(!n.startsWith(e+G.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Ql(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 $l(e){return tu({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
50
+ `)}function eu(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function tu(e){let t=eu(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 nu(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:ql,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=Zl(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Yl(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,Xl(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Ql(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?tu({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[$l(l)],p=eu(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(`
51
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const ru=K.Object({action:K.String({description:`Process action: list | poll | log | kill`}),sessionId:K.Optional(K.String({description:`Session id for non-list actions`})),offset:K.Optional(K.Number({description:`Log line offset (0-based)`})),limit:K.Optional(K.Number({description:`Maximum lines to return`})),timeout:K.Optional(K.Number({description:`Poll wait time in milliseconds`}))});function iu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function au(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function ou(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:ru,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(`
52
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return au(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,iu(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`}}:au(`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}}:au(`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}}:au(`No session found for ${i}`)}return au(`Unsupported action: ${n.action}`)}}}const su=2e5;function cu(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function lu(e,t){let n=e+t;return n.length<=su?{text:n,truncated:!1}:{text:n.slice(-su),truncated:!0}}function uu(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=lu(e.output,r);e.output=i.text;let a=lu(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function du(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:cu(e.output),stdoutTail:cu(e.stdout),stderrTail:cu(e.stderr),outputTruncated:e.outputTruncated}}function fu(e,t){return t?e.scopeKey===t:!0}function pu(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function mu(e){return e?e.split(/\r?\n/):[]}function hu(e){let t=mu(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=pu(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(`
53
+ `);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 gu(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function _u(){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),gu(e))};return{start(t){let n=dt(`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:Ge(),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=>uu(o,`stdout`,e)),n.stderr.on(`data`,e=>uu(o,`stderr`,e));let s=pu(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,uu(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`),uu(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`)})}),du(o)},get(e,t){let n=r(e);return!n||!fu(n,t)?null:du(n)},list(n){return[...e.values(),...t.values()].filter(e=>fu(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>du(e))},async wait(e,t,n){let i=r(e);if(!i||!fu(i,t))return null;if(i.status!==`running`)return du(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||!fu(a,t)?null:du(a)},readLog(e){let t=r(e.sessionId);return!t||!fu(t,e.scopeKey)?null:hu({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!fu(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||!fu(n,t))return null;if(n.status!==`running`)return du(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?du(i):null}}}function vu(e){return nu({workspaceDir:e,registry:_u(),scopeKey:e})}const yu=5*1024*1024,bu=2e3;async function xu(e,t){e&&await e(t).catch(()=>{})}function Su(e,t){return G.isAbsolute(e)?G.normalize(e):G.normalize(G.join(t,e))}const Cu=K.Object({path:K.String({description:`File path (relative to workspace or absolute)`}),offset:K.Optional(K.Number({description:`Line offset (1-based, default: 1)`})),limit:K.Optional(K.Number({description:`Maximum lines to read (default: 2000)`}))});function wu(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Cu,async execute(n,r){let i;try{i=Su(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 W.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 ft(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>yu){let e=o.slice(0,yu).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${yu} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
54
+ `),l=Math.max(1,r.offset??1),u=Math.min(bu,r.limit??bu),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(`
54
55
  `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
55
56
  `),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
56
- `),lines:d.length,truncated:f}}}}}const du=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),content:q.String({description:`File content to write`})});function fu(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:du,async execute(r,i){let a;try{a=cu(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await G.mkdir(K.dirname(a),{recursive:!0}),await G.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await su(n,{type:`write`,operation:`write_file`,file:a,content:i.content,toolCallId:r,toolName:`write_file`})}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:a}}}return{content:[{type:`text`,text:`File written: ${i.path}`}],details:{path:a}}}}}const pu=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),old_string:q.String({description:`Exact text to replace`}),new_string:q.String({description:`Replacement text`})});function mu(e,t,n){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:pu,async execute(r,i){let a;try{a=cu(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await G.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await G.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await su(n,{type:`edit`,operation:`edit_file`,file:a,content:s,toolCallId:r,toolName:`edit_file`}),{content:[{type:`text`,text:`File edited: ${i.path}`}],details:{path:a,occurrences:1}}}}}const hu=q.Object({path:q.Optional(q.String({description:`Directory path (default: workspace root)`}))});function gu(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:hu,async execute(t,n){let r=n.path??`.`,i;try{i=cu(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await G.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(`
57
- `)||`(empty directory)`}],details:{entries:a}}}}}const _u=q.Object({input:q.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function vu(e,t){let n=K.isAbsolute(e)?K.normalize(e):K.normalize(K.join(t,e));if(!n.startsWith(t+K.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function yu(e,t){let n=K.relative(t,e);return!n||n===``?K.basename(e):n.startsWith(`..`)||K.isAbsolute(n)?e:n}async function bu(e){await G.mkdir(K.dirname(e),{recursive:!0})}async function xu(e,t){e&&await e(t).catch(()=>{})}function Su(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(`
58
- `)}function Cu(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:_u,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=Tu(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let r of a.hunks){if(r.kind===`add`){let i=vu(r.path,e);await bu(i),await G.writeFile(i,r.contents,`utf-8`),await xu(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),wu(o,s,`added`,yu(i,e));continue}if(r.kind===`delete`){let i=vu(r.path,e);await G.rm(i,{force:!0,recursive:!1}),await xu(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),wu(o,s,`deleted`,yu(i,e));continue}let i=vu(r.path,e),a=await ku(i,r.chunks);if(r.movePath){let c=vu(r.movePath,e);await bu(c),await G.writeFile(c,a,`utf-8`),await G.rm(i,{force:!0,recursive:!1}),await xu(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),wu(o,s,`modified`,yu(c,e))}else await G.writeFile(i,a,`utf-8`),await xu(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),wu(o,s,`modified`,yu(i,e))}return{content:[{type:`text`,text:Su(o)}],details:{summary:o}}}catch(e){if(ui(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function wu(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Tu(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Eu(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Du(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Eu(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 Du(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}=Ou(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 Ou(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 ku(e,t){let n=(await G.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
59
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=ju(n,Au(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
60
- `)}function Au(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Mu(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=Mu(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=Mu(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
61
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function ju(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 Mu(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(Nu(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Nu(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Nu(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Nu(e,t,n,e=>Pu(e.trim())))return n;return null}function Nu(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 Pu(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 Fu(e){return K.join(e,`.aimax`)}function Iu(e){return K.join(Fu(e),`MEMORY.md`)}async function Lu(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function Ru(e,t){let n=Fu(e),r=se({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:re({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function zu(e){return oe(Fu(e))}async function Bu(e){try{return await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Vu(e){return Bu(Iu(e))}async function Hu(e,t,n){let{provider:r}=Ru(e,n);return await r.search(t)}async function Uu(e,t,n,r,i){try{let{provider:a}=Ru(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Wu(e,t,n){let{provider:r,resolvedProviderId:i}=Ru(e,n);await r.append(t),await Lu(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 Gu(e,t,n,r){let{provider:i,resolvedProviderId:a}=Ru(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 Lu(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Lu(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 Lu(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 Lu(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Lu(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 Ku(e,t,n,r){let{provider:i,resolvedProviderId:a}=Ru(e,r);await i.updateFile(t,n),await Lu(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function qu(e,t,n){let{provider:r,resolvedProviderId:i}=Ru(e,n);await r.deleteFile(t),await Lu(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const Ju=q.Object({query:q.String({description:`Search query (case-insensitive substring match)`})});function Yu(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:Ju,async execute(n,r){let i=(await Hu(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(`
62
- `)}],details:{matches:i}}}}}const Xu=q.Object({file:q.String({description:`Memory file path (from memory_search results)`}),start_line:q.Number({description:`Start line number (1-based)`}),end_line:q.Number({description:`End line number (1-based)`})});function Zu(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:Xu,async execute(n,r){let i=await Uu(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(`
63
- `)||`(empty)`}],details:{lines:i}}}}}const Qu=q.Object({content:q.String({description:`Content to write to memory`})});function $u(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:Qu,async execute(n,r){try{return await Wu(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 ed=q.Object({section:q.Optional(q.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:q.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:q.Union([q.Literal(`append`),q.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function td(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:ed,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Wu(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 Ku(e,`MEMORY.md`,nd(await Vu(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Wu(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 nd(e,t,n){let r=e.split(`
57
+ `),lines:d.length,truncated:f}}}}}const Tu=K.Object({path:K.String({description:`File path (relative to workspace or absolute)`}),content:K.String({description:`File content to write`})});function Eu(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Tu,async execute(r,i){let a;try{a=Su(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await W.mkdir(G.dirname(a),{recursive:!0}),await W.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await xu(n,{type:`write`,operation:`write_file`,file:a,content:i.content,toolCallId:r,toolName:`write_file`})}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:a}}}return{content:[{type:`text`,text:`File written: ${i.path}`}],details:{path:a}}}}}const Du=K.Object({path:K.String({description:`File path (relative to workspace or absolute)`}),old_string:K.String({description:`Exact text to replace`}),new_string:K.String({description:`Replacement text`})});function Ou(e,t,n){return{name:`edit_file`,label:`Edit File`,description:`Replace the first occurrence of old_string with new_string in a file`,parameters:Du,async execute(r,i){let a;try{a=Su(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await W.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await W.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await xu(n,{type:`edit`,operation:`edit_file`,file:a,content:s,toolCallId:r,toolName:`edit_file`}),{content:[{type:`text`,text:`File edited: ${i.path}`}],details:{path:a,occurrences:1}}}}}const ku=K.Object({path:K.Optional(K.String({description:`Directory path (default: workspace root)`}))});function Au(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:ku,async execute(t,n){let r=n.path??`.`,i;try{i=Su(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await W.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(`
58
+ `)||`(empty directory)`}],details:{entries:a}}}}}const ju=K.Object({input:K.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Mu(e,t){let n=G.isAbsolute(e)?G.normalize(e):G.normalize(G.join(t,e));if(!n.startsWith(t+G.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Nu(e,t){let n=G.relative(t,e);return!n||n===``?G.basename(e):n.startsWith(`..`)||G.isAbsolute(n)?e:n}async function Pu(e){await W.mkdir(G.dirname(e),{recursive:!0})}async function Fu(e,t){e&&await e(t).catch(()=>{})}function Iu(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(`
59
+ `)}function Lu(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:ju,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=zu(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let r of a.hunks){if(r.kind===`add`){let i=Mu(r.path,e);await Pu(i),await W.writeFile(i,r.contents,`utf-8`),await Fu(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Ru(o,s,`added`,Nu(i,e));continue}if(r.kind===`delete`){let i=Mu(r.path,e);await W.rm(i,{force:!0,recursive:!1}),await Fu(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Ru(o,s,`deleted`,Nu(i,e));continue}let i=Mu(r.path,e),a=await Uu(i,r.chunks);if(r.movePath){let c=Mu(r.movePath,e);await Pu(c),await W.writeFile(c,a,`utf-8`),await W.rm(i,{force:!0,recursive:!1}),await Fu(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Ru(o,s,`modified`,Nu(c,e))}else await W.writeFile(i,a,`utf-8`),await Fu(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Ru(o,s,`modified`,Nu(i,e))}return{content:[{type:`text`,text:Iu(o)}],details:{summary:o}}}catch(e){if(di(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Ru(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function zu(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Bu(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Vu(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Bu(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 Vu(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}=Hu(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 Hu(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 Uu(e,t){let n=(await W.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
60
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Gu(n,Wu(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
61
+ `)}function Wu(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Ku(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=Ku(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=Ku(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
62
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Gu(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 Ku(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(qu(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(qu(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(qu(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(qu(e,t,n,e=>Ju(e.trim())))return n;return null}function qu(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 Ju(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 Yu(e){return G.join(e,`.aimax`)}function Xu(e){return G.join(Yu(e),`MEMORY.md`)}async function Zu(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function Qu(e,t){let n=Yu(e),r=ce({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:ie({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function $u(e){return se(Yu(e))}async function ed(e){try{return await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function td(e){return ed(Xu(e))}async function nd(e,t,n){let{provider:r}=Qu(e,n);return await r.search(t)}async function rd(e,t,n,r,i){try{let{provider:a}=Qu(e,i);return await a.getLines(t,n,r)}catch{return null}}async function id(e,t,n){let{provider:r,resolvedProviderId:i}=Qu(e,n);await r.append(t),await Zu(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 ad(e,t,n,r){let{provider:i,resolvedProviderId:a}=Qu(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 Zu(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Zu(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 Zu(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 Zu(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Zu(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 od(e,t,n,r){let{provider:i,resolvedProviderId:a}=Qu(e,r);await i.updateFile(t,n),await Zu(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function sd(e,t,n){let{provider:r,resolvedProviderId:i}=Qu(e,n);await r.deleteFile(t),await Zu(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const cd=K.Object({query:K.String({description:`Search query (case-insensitive substring match)`})});function ld(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:cd,async execute(n,r){let i=(await nd(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(`
63
+ `)}],details:{matches:i}}}}}const ud=K.Object({file:K.String({description:`Memory file path (from memory_search results)`}),start_line:K.Number({description:`Start line number (1-based)`}),end_line:K.Number({description:`End line number (1-based)`})});function dd(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:ud,async execute(n,r){let i=await rd(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(`
64
+ `)||`(empty)`}],details:{lines:i}}}}}const fd=K.Object({content:K.String({description:`Content to write to memory`})});function pd(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:fd,async execute(n,r){try{return await id(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 md=K.Object({section:K.Optional(K.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:K.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:K.Union([K.Literal(`append`),K.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function hd(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:md,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await id(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 od(e,`MEMORY.md`,gd(await td(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await id(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 gd(e,t,n){let r=e.split(`
64
65
  `),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(`
65
66
  `).trimEnd(),a,r.slice(s).join(`
66
67
  `).trimStart()].filter(e=>e.length>0).join(`
67
- `)}\n`}function rd(e,t){let n=e.split(`
68
+ `)}\n`}function _d(e,t){let n=e.split(`
68
69
  `),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(`
69
70
  `).trimEnd(),n.slice(a).join(`
70
71
  `).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
71
- `)}\n`:``}function id(e,t){let n=e.split(`
72
+ `)}\n`:``}function vd(e,t){let n=e.split(`
72
73
  `);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
73
- `)}\n`:``)}function ad(e,t,n){let r=e.split(`
74
+ `)}\n`:``)}function yd(e,t,n){let r=e.split(`
74
75
  `);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
75
- `)}\n`)}function od(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 sd(e,t){let n=[],r=t.split(`
76
- `);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 cd=q.Object({content:q.String({description:`Note to append to today's daily log`}),scope:q.Optional(q.Union([q.Literal(`daily`),q.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function ld(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:cd,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Gu(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 ud=q.Object({scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function dd(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:ud,async execute(n,r){try{let n=r.scope??`all`,i=await zu(e),a=[];for(let n of i.slice(0,30)){let r=await Uu(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
77
- `),t=sd(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(`
76
+ `)}\n`)}function bd(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 xd(e,t){let n=[],r=t.split(`
77
+ `);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 Sd=K.Object({content:K.String({description:`Note to append to today's daily log`}),scope:K.Optional(K.Union([K.Literal(`daily`),K.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Cd(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:Sd,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await ad(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 wd=K.Object({scope:K.Optional(K.Union([K.Literal(`long-term`),K.Literal(`recent`),K.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Td(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:wd,async execute(n,r){try{let n=r.scope??`all`,i=await $u(e),a=[];for(let n of i.slice(0,30)){let r=await rd(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
78
+ `),t=xd(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(`
78
79
  `):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
79
80
 
80
- `)||`(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 fd=q.Object({id:q.Optional(q.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:q.Optional(q.String({description:`Search query used to find memories to delete`})),limit:q.Optional(q.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function pd(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:fd,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=od(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=rd(await Vu(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 Ku(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 Uu(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=rd(n.join(`
81
- `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Ku(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 Uu(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=id(n.join(`
82
- `),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 Ku(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 qu(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 Hu(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await qu(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 md=q.Object({id:q.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:q.String({description:`New content to replace the existing memory with`})});function hd(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:md,async execute(n,r){try{let n=od(r.id);if(n.section){let i=nd(await Vu(e)??``,n.section,r.content);return await Ku(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 Uu(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=ad(i.join(`
83
- `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Ku(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 Ku(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 gd=q.Object({query:q.Optional(q.String({description:`Search query; omit to browse recent sessions.`})),role_filter:q.Optional(q.Union([q.Literal(`user`),q.Literal(`assistant`),q.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:q.Optional(q.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:q.Optional(q.Union([q.Literal(`llm`),q.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function _d(e,t){return{name:`session_search`,label:`Session Search`,description:`Search past conversation transcripts across sessions for cross-session recall. Use when the user asks about what was discussed, decided, or done in previous chats (e.g. last time, before, remember when). Omit query to browse recent sessions with zero LLM cost; include query to search transcripts and return summaries. Do not use this as the only source for stable project policy/config if long-term memory docs exist (use memory_search for durable docs).`,parameters:gd,async execute(n,r){let i=vd(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await yd(e,i,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let c=await bd({dataDir:e,query:o,roleFilter:s,messageLimit:50,sessionLimit:i,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(c.length===0){let e={mode:`query`,query:o,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let l=[];for(let n of c){let r=Nd(o,n.snippets);if(a===`off`){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let i=await Tc({entries:Ad(kd(await m(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Md({query:o})});l.push({session_id:n.sessionId,summary:i.trim()||r,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let u={mode:`query`,query:o,count:l.length,results:l};return{content:[{type:`text`,text:JSON.stringify(u,null,2)}],details:u}}}}function vd(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function yd(e,t,n){let r=await y(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await N(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 bd(e){let t=e.messageLimit??50,n=(await y(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=wd(e.query),i=(await Pd(n,6,async t=>xd({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Od).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 N(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 xd(t){let n=await l(e(t.dataDir,t.sessionId,{storeName:t.storeName}));if(n===null)return[];let r=[],i=n.split(`
84
- `);for(let e of i){let n=e.trim();if(!n||!Sd(n,t.terms))continue;let i;try{i=JSON.parse(n)}catch{continue}if(!Cd(i.role)||t.roleFilter&&i.role!==t.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Ed(i.content,t.terms,i.role);if(a<=0)continue;let o=Dd(i.content);r.push({sessionId:t.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),r.length>20&&(r.sort(Od),r.length=20)}return r.sort(Od),r}function Sd(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Cd(e){return e===`user`||e===`assistant`||e===`tool_result`}function wd(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=>Td(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 Td(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 Ed(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 Dd(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Od(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function kd(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function Ad(e,t,n){if(e.length===0)return e;let r=wd(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 jd(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 jd(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 Md(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(`
85
- `)}function Nd(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(`
86
- `)}`}async function Pd(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 Fd=q.Object({category:q.Optional(q.String({description:`Reserved category filter field. Not used yet.`}))}),Id=q.Object({name:q.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:q.Optional(q.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Ld(e,t,n=[]){return[...n,...t,Tt(e)]}function Rd(e,t,n=[]){let r=Ld(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Fd,async execute(e,t){let n=await Nt(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 zd(e){let t=Ld(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:Id,async execute(r,i){let a=await It(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``,version:``,skillFileMtime:``}}}}}const Bd=q.Object({});function Vd(e,t,n){return{name:`get_goal`,label:`Get Goal`,description:`Get the current thread goal, including status, budget, token and time usage, and remaining token budget. Returns null when no goal is set.`,parameters:Bd,async execute(r,i){let a=await B(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null})}],details:{}};let o=await H(e,t,a,{storeName:n}),s={goal:{...a,objective:o,remainingTokens:a.tokenBudget===null?void 0:Math.max(0,a.tokenBudget-a.tokensUsed)}};return{content:[{type:`text`,text:JSON.stringify(s,null,2)}],details:{}}}}}const Hd=q.Object({status:q.String({description:`Status to set. Only 'complete' is allowed.`})});function Ud(e,t,n,r,i=t){return{name:`update_goal`,label:`Update Goal`,description:`Update the existing goal. Only supports marking the goal as complete. Use this only when the objective has actually been achieved and no required work remains. Do not mark a goal complete merely because its budget is nearly exhausted or because you are stopping work.`,parameters:Hd,async execute(a,o){if(o.status!==`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Invalid status: "${o.status}". Only "complete" is allowed via this tool.`},null,2)}],details:{}};let s=await B(e,t,{storeName:n});if(!s)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`No active goal exists for this session. Use the CLI to set a goal first.`},null,2)}],details:{}};if(s.status===`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:s},null,2)}],details:{}};let c=await L(e,t,{status:`complete`},{storeName:n,eventSource:`tool`});if(!c)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Failed to update goal.`},null,2)}],details:{}};r&&await nn(r,i,{before:s,after:c,action:`completed`});let l={goal:{...c,remainingTokens:c.tokenBudget===null?void 0:Math.max(0,c.tokenBudget-c.tokensUsed)}};return{content:[{type:`text`,text:JSON.stringify(l,null,2)}],details:{}}}}}const Wd=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),Gd=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),Kd=q.Object({tasks:q.Array(Wd,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function qd(e){let t=e.label?`"${e.label}"`:`task: ${Ie(e.task)}`;return e.status===`done`?`${t}\n\n${Jd(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Jd(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}async function Yd(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(X.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:ma(p)}),!p){let e={status:`error`,error:`task must not be empty`};return X.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return X.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=We(),v=new AbortController,y=t,b=Fr(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return X.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await C(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return X.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}X.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let w=f({dataDir:s,sessionId:y,message:b?Vr(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,w),X.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await w,X.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let T=qd({task:p,label:m,status:S.status,result:S.result,error:S.error});if(S.status===`done`){let e={status:`done`,childSessionId:y,runId:_,result:S.result??``};return X.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:T}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return X.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:T}],isError:!0,details:E}}function Xd(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. `+(r===0?"IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. You MUST also use this tool when the user mentions '@<agent-name>' where <agent-name> matches a custom agent listed in the Custom Agents section — set the `agent` field to that exact name. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. ":`WARNING: You are already running as a subagent (depth ${r}). Spawning further subagents creates deeply nested hierarchies that are expensive and error-prone. Only use this tool if the current task genuinely cannot be completed with available tools directly. Prefer direct tool calls (exec, read_file, write_file, etc.) over spawning another subagent. `)+`Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:Gd,async execute(e,t){return Yd(u,e,t)}}}function Zd(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:Kd,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}X.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await Yd(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`Batch subagents: ${o.length-d.length}/${o.length} completed.`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${Jd(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
81
+ `)||`(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 Ed=K.Object({id:K.Optional(K.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:K.Optional(K.String({description:`Search query used to find memories to delete`})),limit:K.Optional(K.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:K.Optional(K.Union([K.Literal(`long-term`),K.Literal(`recent`),K.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Dd(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:Ed,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=bd(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=_d(await td(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 od(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 rd(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=_d(n.join(`
82
+ `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await od(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 rd(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=vd(n.join(`
83
+ `),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 od(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 sd(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 nd(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await sd(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 Od=K.Object({id:K.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:K.String({description:`New content to replace the existing memory with`})});function kd(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:Od,async execute(n,r){try{let n=bd(r.id);if(n.section){let i=gd(await td(e)??``,n.section,r.content);return await od(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 rd(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=yd(i.join(`
84
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await od(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 od(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 Ad=K.Object({query:K.Optional(K.String({description:`Search query; omit to browse recent sessions.`})),role_filter:K.Optional(K.Union([K.Literal(`user`),K.Literal(`assistant`),K.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:K.Optional(K.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:K.Optional(K.Union([K.Literal(`llm`),K.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function jd(e,t){return{name:`session_search`,label:`Session Search`,description:`Search past conversation transcripts across sessions for cross-session recall. Use when the user asks about what was discussed, decided, or done in previous chats (e.g. last time, before, remember when). Omit query to browse recent sessions with zero LLM cost; include query to search transcripts and return summaries. Do not use this as the only source for stable project policy/config if long-term memory docs exist (use memory_search for durable docs).`,parameters:Ad,async execute(n,r){let i=Md(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Nd(e,i,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let c=await Pd({dataDir:e,query:o,roleFilter:s,messageLimit:50,sessionLimit:i,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(c.length===0){let e={mode:`query`,query:o,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let l=[];for(let n of c){let r=qd(o,n.snippets);if(a===`off`){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let i=await Ec({entries:Wd(Ud(await m(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Kd({query:o})});l.push({session_id:n.sessionId,summary:i.trim()||r,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let u={mode:`query`,query:o,count:l.length,results:l};return{content:[{type:`text`,text:JSON.stringify(u,null,2)}],details:u}}}}function Md(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Nd(e,t,n){let r=await y(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await ne(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 Pd(e){let t=e.messageLimit??50,n=(await y(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Rd(e.query),i=(await Jd(n,6,async t=>Fd({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Hd).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 ne(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 Fd(t){let n=await l(e(t.dataDir,t.sessionId,{storeName:t.storeName}));if(n===null)return[];let r=[],i=n.split(`
85
+ `);for(let e of i){let n=e.trim();if(!n||!Id(n,t.terms))continue;let i;try{i=JSON.parse(n)}catch{continue}if(!Ld(i.role)||t.roleFilter&&i.role!==t.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Bd(i.content,t.terms,i.role);if(a<=0)continue;let o=Vd(i.content);r.push({sessionId:t.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),r.length>20&&(r.sort(Hd),r.length=20)}return r.sort(Hd),r}function Id(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Ld(e){return e===`user`||e===`assistant`||e===`tool_result`}function Rd(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=>zd(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 zd(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 Bd(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 Vd(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Hd(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Ud(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function Wd(e,t,n){if(e.length===0)return e;let r=Rd(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 Gd(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 Gd(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 Kd(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(`
86
+ `)}function qd(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(`
87
+ `)}`}async function Jd(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 Yd=K.Object({category:K.Optional(K.String({description:`Reserved category filter field. Not used yet.`}))}),Xd=K.Object({name:K.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:K.Optional(K.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Zd(e,t,n=[]){return[...n,...t,Et(e)]}function Qd(e,t,n=[]){let r=Zd(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Yd,async execute(e,t){let n=await Pt(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 $d(e){let t=Zd(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:Xd,async execute(r,i){let a=await Lt(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``,version:``,skillFileMtime:``}}}}}const ef=K.Object({});function tf(e,t,n){return{name:`get_goal`,label:`Get Goal`,description:`Get the current thread goal, including status, budget, token and time usage, and remaining token budget. Returns null when no goal is set.`,parameters:ef,async execute(r,i){let a=await z(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null})}],details:{}};let o=await V(e,t,a,{storeName:n}),s={goal:{...a,objective:o,remainingTokens:a.tokenBudget===null?void 0:Math.max(0,a.tokenBudget-a.tokensUsed)}};return{content:[{type:`text`,text:JSON.stringify(s,null,2)}],details:{}}}}}const nf=K.Object({status:K.String({description:`Status to set. Only 'complete' is allowed.`})});function rf(e,t,n,r,i=t){return{name:`update_goal`,label:`Update Goal`,description:`Update the existing goal. Only supports marking the goal as complete. Use this only when the objective has actually been achieved and no required work remains. Do not mark a goal complete merely because its budget is nearly exhausted or because you are stopping work.`,parameters:nf,async execute(a,o){if(o.status!==`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Invalid status: "${o.status}". Only "complete" is allowed via this tool.`},null,2)}],details:{}};let s=await z(e,t,{storeName:n});if(!s)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`No active goal exists for this session. Use the CLI to set a goal first.`},null,2)}],details:{}};if(s.status===`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:s},null,2)}],details:{}};let c=await I(e,t,{status:`complete`},{storeName:n,eventSource:`tool`});if(!c)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Failed to update goal.`},null,2)}],details:{}};r&&await rn(r,i,{before:s,after:c,action:`completed`});let l={goal:{...c,remainingTokens:c.tokenBudget===null?void 0:Math.max(0,c.tokenBudget-c.tokensUsed)}};return{content:[{type:`text`,text:JSON.stringify(l,null,2)}],details:{}}}}}const af=K.Object({task:K.String({description:`The task description for the subagent to execute`}),label:K.Optional(K.String({description:`Optional short label to identify this subagent`})),agent:K.Optional(K.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),of=K.Object({task:K.String({description:`The task description for the subagent to execute`}),label:K.Optional(K.String({description:`Optional short label to identify this subagent`})),agent:K.Optional(K.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),sf=K.Object({tasks:K.Array(af,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function cf(e){let t=e.label?`"${e.label}"`:`task: ${Le(e.task)}`;return e.status===`done`?`${t}\n\n${lf(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function lf(e){let t=e.trim().match(/^\[Subagent (?:completed|failed|killed)\][^\n]*(?:\n\n([\s\S]*))?$/);return t?t[1]?.trim()||`(no output)`:e}async function uf(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(X.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:ha(p)}),!p){let e={status:`error`,error:`task must not be empty`};return X.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return X.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Ge(),v=new AbortController,y=t,b=Ir(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return X.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await C(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return X.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}X.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let w=f({dataDir:s,sessionId:y,message:b?Hr(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,w),X.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await w,X.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let T=cf({task:p,label:m,status:S.status,result:S.result,error:S.error});if(S.status===`done`){let e={status:`done`,childSessionId:y,runId:_,result:S.result??``};return X.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:T}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return X.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:T}],isError:!0,details:E}}function df(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`subagent_spawn`,label:`Spawn Subagent`,description:`Spawn an isolated subagent session to delegate a task. `+(r===0?"IMPORTANT: You MUST use this tool whenever the user explicitly mentions 'subagent', '@subagent', or asks for subagent-based execution. You MUST also use this tool when the user mentions '@<agent-name>' where <agent-name> matches a custom agent listed in the Custom Agents section — set the `agent` field to that exact name. Do not use it for routine decomposition or inferred parallelism — only when the user or system instructions explicitly require subagent delegation or parallel agent execution. ":`WARNING: You are already running as a subagent (depth ${r}). Spawning further subagents creates deeply nested hierarchies that are expensive and error-prone. Only use this tool if the current task genuinely cannot be completed with available tools directly. Prefer direct tool calls (exec, read_file, write_file, etc.) over spawning another subagent. `)+`Waits for the subagent to finish and returns the final subagent result as this tool call's result.`,parameters:of,async execute(e,t){return uf(u,e,t)}}}function ff(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:sf,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}X.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await uf(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`Batch subagents: ${o.length-d.length}/${o.length} completed.`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${lf(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
87
88
 
88
- `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const Qd=q.Object({action:q.Union([`list`,`kill`].map(e=>q.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:q.Optional(q.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function $d(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 ef(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 tf(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:Qd,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} (${$d(e.runtimeMs)})${n}`})).join(`
89
- `)};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=ef(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 nf=q.Object({image:q.String({description:`Image path or URL`}),prompt:q.Optional(q.String({description:`Prompt for image analysis`})),model:q.Optional(q.String({description:`Optional model override`})),maxBytesMb:q.Optional(q.Number({description:`Optional size cap in MB`}))});function rf(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:nf,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}const af=q.Object({reason:q.String({description:`A brief explanation of why user input is needed through this UI form.`})});function of(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??af,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=ze(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 di(e,i,t,e,o,s,n);throw bi(r),r}}}function sf(e,t){let n=K.join(e,`workspace`),r=t?.memoryOptions,i=ru(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await O(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[Hl({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Kl({registry:i,scopeKey:n}),uu(n,t?.contextManager),fu(n,t?.contextManager,s),mu(n,t?.contextManager,s),gu(n),Cu(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[Vd(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),Ud(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId)]:[],Yu(e,r),_d(e,r),Zu(e,r),td(e,r),ld(e,r),dd(e,r),pd(e,r),hd(e,r),Rd(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),zd({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(mo(e),ho(e),go(e),_o(e)),t&&c.push(Xd(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Zd(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),tf(t.registry,t.parentSessionId)),c}function cf(e){return e.length===0?``:[`## Auto-Skills`,`Auto-skills are learned from prior completed tasks and are stored separately from curated/user/plugin skills.`,`Auto-skill categories are single-level routing slugs in the current MVP.`,`Prefer curated/user/plugin skills from <available_skills> when both options apply.`,`Use auto-skills only when they clearly match the current task, especially project-specific or previously learned workflows.`,"Match the task to one or more category paths below, call `auto_skill_list({ categoryPath })`, then call `auto_skill_view({ skillId })` for the best match.","If no category is clear but an auto-skill may help, call `auto_skill_search({ query, limit: 5 })`.",`Archived auto-skills are not listed or loaded.`,`<auto_skill_categories>`,[...e].sort((e,t)=>e.path.localeCompare(t.path)).map(e=>e.description?` - ${e.path} | ${e.description}`:` - ${e.path}`).join(`
89
+ `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const pf=K.Object({action:K.Union([`list`,`kill`].map(e=>K.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:K.Optional(K.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function mf(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 hf(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 gf(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:pf,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} (${mf(e.runtimeMs)})${n}`})).join(`
90
+ `)};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=hf(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 _f=K.Object({image:K.String({description:`Image path or URL`}),prompt:K.Optional(K.String({description:`Prompt for image analysis`})),model:K.Optional(K.String({description:`Optional model override`})),maxBytesMb:K.Optional(K.Number({description:`Optional size cap in MB`}))});function vf(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:_f,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}const yf=K.Object({reason:K.String({description:`A brief explanation of why user input is needed through this UI form.`})});function bf(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??yf,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=Be(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new fi(e,i,t,e,o,s,n);throw xi(r),r}}}function xf(e,t){let n=G.join(e,`workspace`),r=t?.memoryOptions,i=_u(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await O(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[nu({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),ou({registry:i,scopeKey:n}),wu(n,t?.contextManager),Eu(n,t?.contextManager,s),Ou(n,t?.contextManager,s),Au(n),Lu(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[tf(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),rf(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId)]:[],ld(e,r),jd(e,r),dd(e,r),hd(e,r),Cd(e,r),Td(e,r),Dd(e,r),kd(e,r),Qd(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),$d({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(ho(e),go(e),_o(e),vo(e)),t&&c.push(df(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),ff(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),gf(t.registry,t.parentSessionId)),c}function Sf(e){return e.length===0?``:[`## Auto-Skills`,`Auto-skills are learned from prior completed tasks and are stored separately from curated/user/plugin skills.`,`Auto-skill categories are single-level routing slugs in the current MVP.`,`Prefer curated/user/plugin skills from <available_skills> when both options apply.`,`Use auto-skills only when they clearly match the current task, especially project-specific or previously learned workflows.`,"Match the task to one or more category paths below, call `auto_skill_list({ categoryPath })`, then call `auto_skill_view({ skillId })` for the best match.","If no category is clear but an auto-skill may help, call `auto_skill_search({ query, limit: 5 })`.",`Archived auto-skills are not listed or loaded.`,`<auto_skill_categories>`,[...e].sort((e,t)=>e.path.localeCompare(t.path)).map(e=>e.description?` - ${e.path} | ${e.description}`:` - ${e.path}`).join(`
90
91
  `),`</auto_skill_categories>`,``].join(`
91
- `)}const lf={get_goal:`Get the current thread goal including status, budget, and usage`,update_goal:`Mark the existing thread goal as complete when the objective is achieved`,read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,auto_skill_categories:`List learned auto-skill categories`,auto_skill_list:`List active learned auto-skills by category`,auto_skill_search:`Search active learned auto-skills`,auto_skill_view:`Load an active learned auto-skill by exact skillId`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},uf=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`get_goal`,`update_goal`,`auto_skill_categories`,`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function df(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:[...uf.filter(e=>t.has(e)),...n.filter(e=>!uf.includes(e)).sort()],displayName:t}}function ff(e){let{ordered:t,displayName:n}=df(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)??lf[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
92
+ `)}const Cf={get_goal:`Get the current thread goal including status, budget, and usage`,update_goal:`Mark the existing thread goal as complete when the objective is achieved`,read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,auto_skill_categories:`List learned auto-skill categories`,auto_skill_list:`List active learned auto-skills by category`,auto_skill_search:`Search active learned auto-skills`,auto_skill_view:`Load an active learned auto-skill by exact skillId`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},wf=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`get_goal`,`update_goal`,`auto_skill_categories`,`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function Tf(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:[...wf.filter(e=>t.has(e)),...n.filter(e=>!wf.includes(e)).sort()],displayName:t}}function Ef(e){let{ordered:t,displayName:n}=Tf(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)??Cf[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
92
93
  `),``].join(`
93
- `)}function pf(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Use `get_goal` to view the current goal, its status, budget, and usage.",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,'- When you have completed the objective and verified it against the requirements, use `update_goal` with `status: "complete"`.',"- Do NOT call `update_goal(complete)` merely because the budget is nearly exhausted or work is paused.",`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, `get_goal` returns null and `update_goal` reports an error.",``].join(`
94
- `)}function mf(){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(`
95
- `)}function hf(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
96
- `)}function gf(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(`
97
- `)}function _f(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
94
+ `)}function Df(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Use `get_goal` to view the current goal, its status, budget, and usage.",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,'- When you have completed the objective and verified it against the requirements, use `update_goal` with `status: "complete"`.',"- Do NOT call `update_goal(complete)` merely because the budget is nearly exhausted or work is paused.",`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, `get_goal` returns null and `update_goal` reports an error.",``].join(`
95
+ `)}function Of(){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(`
96
+ `)}function kf(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
97
+ `)}function Af(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(`
98
+ `)}function jf(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
98
99
  `)).join(`
99
100
  `)}\n</available_skills>`,``].join(`
100
- `)}function vf(e=[]){let t=cf(e).trim();return t?`${t}\n`:``}function yf(){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(`
101
- `)}function bf(){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(`
102
- `)}function xf(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(`
103
- `)}function Sf(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(`
104
- `)}function Cf(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(`
105
- `)}function wf(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Tf(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
106
- `)}function Tf(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 Ef(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(`
107
- `)}function Df(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(`
108
- `)}function Of(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(`
109
- `)}function kf(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(`
110
- `)}function Af(e){return e<=0?``:[`## Subagent Constraint`,`You are running as a subagent (nesting depth: ${e}). Your role is to complete the delegated task directly using available tools.`,`Do NOT spawn further subagents unless the task absolutely cannot be completed any other way.`,`If you find yourself wanting to use subagent_spawn, first ask whether a direct tool call (exec, read_file, write_file, edit_file, etc.) can achieve the same result.`,`Subagent nesting adds overhead and complexity — prefer direct execution in all but the most exceptional cases.`,``].join(`
111
- `)}function jf(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(`
112
- `):``}function Mf(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:[...uf],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Af(e.subagentDepth??0),ff({toolNames:i,toolSummaries:e.toolSummaries}),gf(n),pf(),mf(),Br(e.availableAgents??[]),_f(a),vf(e.autoSkillCategories),yf(),bf(),xf(e.memoryCitationsMode??`off`),Sf({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Cf(e.sandboxInfo),wf({currentDate:e.currentDate,timezone:e.timezone}),hf(),Ef({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Of({isMinimal:n}),Df(e.runtimeInfo),kf({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),jf(e.priorConversationSummary)].filter(Boolean).join(`
113
- `)}const Nf=Symbol(`pluginToolOwner`);var Pf=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,Nf,{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=of({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,Nf,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Ff(e){return e[Nf]}function If(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=Ff(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Jr({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(ui(e))return gi(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(ui(i)){gi(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}const Lf={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Rf(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function zf(e){let t=Rf(e?.warningThreshold,Lf.warningThreshold),n=Rf(e?.criticalThreshold,Lf.criticalThreshold),r=Rf(e?.globalCircuitBreakerThreshold,Lf.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Lf.enabled,historySize:Rf(e?.historySize,Lf.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Lf.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Lf.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Lf.detectors.pingPong}}}function Bf(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Vf(e,t){return`${e}:${Wf(t)}`}function Hf(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Hf).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Hf(t[e])}`).join(`,`)}}`}function Uf(e){try{return Hf(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 Wf(e){let t=Uf(e);return Ue(`sha256`).update(t).digest(`hex`)}function Gf(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Bf(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Kf(e){return!Bf(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Bf(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
114
- `).trim()}function qf(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Hf(e)}function Jf(e,t,n,r){if(r!==void 0)return`error:${Wf(qf(r))}`;if(!Bf(n))return n===void 0?void 0:Wf(n);let i=Bf(n.details)?n.details:{},a=Kf(n);if(Gf(e,t)&&e===`process`&&Bf(t)){let e=t.action;if(e===`poll`)return Wf({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Wf({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 Wf({details:i,text:a})}function Yf(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 Xf(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 Zf(e,t){return[e,t].toSorted().join(`|`)}function Qf(e,t,n,r){let i=zf(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Vf(t,n),s=Yf(a,t,o),c=s.count,l=Gf(t,n),u=Xf(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:${Zf(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 $f(e,t,n,r,i){let a=zf(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Vf(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function ep(e,t){let n=zf(t.config),r=Jf(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Vf(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 tp(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 np(e){return e&&e.trim()||`tool`}function rp(e,t,n){if(!e.execute)return e;let r=np(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Qf(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);tp(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}$f(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return ep(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw ep(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function ip(e,t,n){return e.map(e=>rp(e,t,n))}async function ap(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,autoSkillCategories:u,effectivePromptText:f,pluginTools:p,pluginSkillDirs:h,skillsLoadPaths:g,presetSystemPrompt:_},dependencies:{registry:v,spawnFn:y,createModel:b,abortSignal:x}}=e,S=t.autoSkills?.load?.enabled===!0,C=t.agentPolicy?.activeAgent,w=t.channel===`CRON`,T=w?[]:await m(t.dataDir,n,Q(t)),E={model:t.llm.model,api:`openai-completions`},D=await jl({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=w?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Ml({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,pendingUserMessage:f,signal:x,hooks:r,hookCtx:i,contextManager:D,dataDir:t.dataDir,sessionId:n});await sp({sessionId:n,historyResult:O,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let k=t.subagentContext?.depth??0,ee=d(t.dataDir,n,Q(t)),A=zr([...sf(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:ee,registry:v,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:g,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:h,skillsLoadPaths:g,reportSkillUsed:async e=>{await o.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:o,spawnFn:y}),...p],C),j=A.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),te={};for(let e of A){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||te[t]||(te[t]=n)}let M=t.messaging?.enabled??t.channel!==`CRON`,N=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],P=Mf({dataDir:t.dataDir,projectDir:t.projectDir,skills:Rr(l,C),autoSkillCategories:S?u:[],contextFiles:s,toolNames:j,toolSummaries:te,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:M,channels:N},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:lt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});P=await op({systemPrompt:P,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let F=await r.dispatch(`before_prompt_build`,{prompt:f},i,{eventDispatcher:o});for(let e of F)e&&(e.systemPrompt&&(P=e.systemPrompt),e.prependContext&&(P=`${e.prependContext}\n\n${P}`));await r.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:P},i,{eventDispatcher:o});let I=ip(If(A,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},Bs),L=C?.model??t.llm.model,R=await r.dispatch(`before_model_resolve`,{prompt:f},i,{eventDispatcher:o});for(let e of R)e&&e.modelOverride&&(L=e.modelOverride);let z=b({...t.llm,model:L},n,t.messageId,t.channel),B=new Ke({initialState:{systemPrompt:P,model:z,tools:I,messages:[]},getApiKey:e=>t.llm.apiKey});return O.messages.length>0&&B.replaceMessages(O.messages),{agent:B,resolvedModelId:L,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:a.workspaceDir}}async function op(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 ${A(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 sp(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=cp(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 cp(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(`
115
-
116
- `):void 0}}async function lp(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++,X.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){X.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}X.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=up(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await ha({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?X.warn(`subagent announce round completed with error`,v):X.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&X.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function up(e){if(e.length===1){let t=e[0];return qd({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>qd({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
101
+ `)}function Mf(e=[]){let t=Sf(e).trim();return t?`${t}\n`:``}function Nf(){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(`
102
+ `)}function Pf(){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(`
103
+ `)}function Ff(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(`
104
+ `)}function If(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(`
105
+ `)}function Lf(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(`
106
+ `)}function Rf(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=zf(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
107
+ `)}function zf(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 Bf(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(`
108
+ `)}function Vf(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(`
109
+ `)}function Hf(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(`
110
+ `)}function Uf(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(`
111
+ `)}function Wf(e){return e<=0?``:[`## Subagent Constraint`,`You are running as a subagent (nesting depth: ${e}). Your role is to complete the delegated task directly using available tools.`,`Do NOT spawn further subagents unless the task absolutely cannot be completed any other way.`,`If you find yourself wanting to use subagent_spawn, first ask whether a direct tool call (exec, read_file, write_file, edit_file, etc.) can achieve the same result.`,`Subagent nesting adds overhead and complexity — prefer direct execution in all but the most exceptional cases.`,``].join(`
112
+ `)}function Gf(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(`
113
+ `):``}function Kf(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:[...wf],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Wf(e.subagentDepth??0),Ef({toolNames:i,toolSummaries:e.toolSummaries}),Af(n),Df(),Of(),Vr(e.availableAgents??[]),jf(a),Mf(e.autoSkillCategories),Nf(),Pf(),Ff(e.memoryCitationsMode??`off`),If({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Lf(e.sandboxInfo),Rf({currentDate:e.currentDate,timezone:e.timezone}),kf(),Bf({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Hf({isMinimal:n}),Vf(e.runtimeInfo),Uf({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Gf(e.priorConversationSummary)].filter(Boolean).join(`
114
+ `)}const qf=Symbol(`pluginToolOwner`);var Jf=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,qf,{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=bf({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,qf,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Yf(e){return e[qf]}function Xf(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=Yf(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Yr({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(di(e))return _i(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(di(i)){_i(i);let o={content:[{type:`text`,text:i.message}],isError:!0,details:{}};return await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,result:o,durationMs:Date.now()-u},n,r),o}throw await t.dispatch(`after_tool_call`,{toolCallId:e,toolName:a,params:d,error:String(i),durationMs:Date.now()-u},n,r),i}}}})}const Zf={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Qf(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function $f(e){let t=Qf(e?.warningThreshold,Zf.warningThreshold),n=Qf(e?.criticalThreshold,Zf.criticalThreshold),r=Qf(e?.globalCircuitBreakerThreshold,Zf.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Zf.enabled,historySize:Qf(e?.historySize,Zf.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Zf.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Zf.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Zf.detectors.pingPong}}}function ep(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function tp(e,t){return`${e}:${ip(t)}`}function np(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(np).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${np(t[e])}`).join(`,`)}}`}function rp(e){try{return np(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 ip(e){let t=rp(e);return We(`sha256`).update(t).digest(`hex`)}function ap(e,t){if(e===`command_status`)return!0;if(e!==`process`||!ep(t))return!1;let n=t.action;return n===`poll`||n===`log`}function op(e){return!ep(e)||!Array.isArray(e.content)?``:e.content.filter(e=>ep(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
115
+ `).trim()}function sp(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:np(e)}function cp(e,t,n,r){if(r!==void 0)return`error:${ip(sp(r))}`;if(!ep(n))return n===void 0?void 0:ip(n);let i=ep(n.details)?n.details:{},a=op(n);if(ap(e,t)&&e===`process`&&ep(t)){let e=t.action;if(e===`poll`)return ip({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return ip({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 ip({details:i,text:a})}function lp(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 up(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 dp(e,t){return[e,t].toSorted().join(`|`)}function fp(e,t,n,r){let i=$f(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=tp(t,n),s=lp(a,t,o),c=s.count,l=ap(t,n),u=up(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:${dp(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 pp(e,t,n,r,i){let a=$f(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:tp(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function mp(e,t){let n=$f(t.config),r=cp(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=tp(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 hp(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 gp(e){return e&&e.trim()||`tool`}function _p(e,t,n){if(!e.execute)return e;let r=gp(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=fp(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);hp(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}pp(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return mp(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw mp(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function vp(e,t,n){return e.map(e=>_p(e,t,n))}async function yp(e){let{session:{runParams:t,sessionId:n,hookRegistry:r,hookContext:i,runContext:a,eventDispatcher:o},runtimeInputs:{contextFiles:s,bootstrapWarnings:c,skills:l,autoSkillCategories:u,effectivePromptText:f,pluginTools:p,pluginSkillDirs:h,skillsLoadPaths:g,presetSystemPrompt:_},dependencies:{registry:v,spawnFn:y,createModel:b,abortSignal:x}}=e,S=t.autoSkills?.load?.enabled===!0,C=t.agentPolicy?.activeAgent,w=t.channel===`CRON`,T=w?[]:await m(t.dataDir,n,Q(t)),E={model:t.llm.model,api:`openai-completions`},D=await Gl({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=w?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Kl({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:x,hooks:r,hookCtx:i,contextManager:D,dataDir:t.dataDir,sessionId:n});await xp({sessionId:n,historyResult:O,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let k=t.subagentContext?.depth??0,ee=d(t.dataDir,n,Q(t)),A=Br([...xf(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:ee,registry:v,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:g,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:h,skillsLoadPaths:g,reportSkillUsed:async e=>{await o.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:o,spawnFn:y}),...p],C),j=A.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),M={};for(let e of A){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||M[t]||(M[t]=n)}let te=t.messaging?.enabled??t.channel!==`CRON`,ne=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],N=Kf({dataDir:t.dataDir,projectDir:t.projectDir,skills:zr(l,C),autoSkillCategories:S?u:[],contextFiles:s,toolNames:j,toolSummaries:M,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:te,channels:ne},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:ut.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});N=await bp({systemPrompt:N,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let P=await r.dispatch(`before_prompt_build`,{prompt:f},i,{eventDispatcher:o});for(let e of P)e&&(e.systemPrompt&&(N=e.systemPrompt),e.prependContext&&(N=`${e.prependContext}\n\n${N}`));await r.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:N},i,{eventDispatcher:o});let F=vp(Xf(A,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},Vs),I=C?.model??t.llm.model,L=await r.dispatch(`before_model_resolve`,{prompt:f},i,{eventDispatcher:o});for(let e of L)e&&e.modelOverride&&(I=e.modelOverride);let R=b({...t.llm,model:I},n,t.messageId,t.channel),z=new qe({initialState:{systemPrompt:N,model:R,tools:F,messages:[]},getApiKey:e=>t.llm.apiKey});return O.messages.length>0&&z.replaceMessages(O.messages),{agent:z,resolvedModelId:I,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:a.workspaceDir}}async function bp(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 ${A(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 xp(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=Sp(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 Sp(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(`
116
+
117
+ `):void 0}}async function Cp(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++,X.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){X.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}X.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=wp(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await ga({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?X.warn(`subagent announce round completed with error`,v):X.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&X.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function wp(e){if(e.length===1){let t=e[0];return cf({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>cf({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
117
118
 
118
119
  ---
119
120
 
120
- `)}`}function dp(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 fp(e){let t=dp(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=K.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 pp(e){let t=e.watchFactory??((e,t,n)=>J.watch(e,t,n)),n=K.join(e.dataDir,`.aimax`),r=[{target:K.join(n,`MEMORY.md`),kind:`memory-file`},{target:K.join(n,`memory.md`),kind:`memory-file-lower`},{target:K.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=fp({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 mp(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=K.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=_p(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:h?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=K.join(t.dataDir,`.aimax`),h=se({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),g=h?.provider??re({dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),_=h?.registration.id??g.id,v=h?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:h?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!h}}).catch(()=>{});let y=pp({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await p(t.dataDir,i,e,gp({sessionOptions:Q(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function hp(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function gp(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function _p(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 vp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yp(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function bp(){let e=lt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function xp(e){let t=e.trim(),n=bp();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?K.join(n,t.slice(2)):void 0:K.resolve(t)}const Sp=new ft({allErrors:!0,strict:!1}),Cp=new Map;function wp(e,t){let n=Cp.get(t);if(n)return n;let r=Sp.compile(e);return Cp.set(t,r),r}function Tp(e){let t=e.cacheKey??JSON.stringify(e.schema),n=wp(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Ep(e){let t=yp(e?.allow),n=yp(e?.deny),r=yp(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 Dp(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=Tp({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 Op(e){try{return J.realpathSync(e)}catch{return null}}function kp(e){try{return J.statSync(e)}catch{return null}}function Ap(e,t){let n=K.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!K.isAbsolute(n)}function jp(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Mp=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Np=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Pp(e){let t=K.join(e,`package.json`);if(J.existsSync(t))try{let e=JSON.parse(J.readFileSync(t,`utf-8`));return vp(e)?e:void 0}catch{return}}function Fp(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 Ip(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Lp(e){let t=Op(e.source),n=Op(e.rootDir);return!t||!n||Ap(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Rp(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=K.resolve(r);if(n.has(t))continue;n.add(t);let i=kp(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 zp(e){return Lp({source:e.source,rootDir:e.rootDir})||Rp({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Ip(e.ownershipUid)})}function Bp(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=${jp(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Vp(e){let t=zp({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Bp(t),source:e.source}),!0):!1}function Hp(e){return K.basename(e,K.extname(e))}function Up(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 Wp(e){for(let t of Np){let n=K.join(e,t);if(J.existsSync(n))return n}return null}function Gp(e){let t;try{t=J.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=K.join(e.rootDir,n.name);if(n.isFile()){if(!Mp.has(K.extname(n.name)))continue;let r=K.dirname(t);if(Vp({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Up({idHint:Hp(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Pp(t),i=Fp(r);if(i.status===`ok`){for(let n of i.entries){let i=K.resolve(t,n);if(!Ap(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!J.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Mp.has(K.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Vp({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Hp(i)}`:Hp(i);e.candidates.push(Up({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=Wp(t);a&&(Vp({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Up({idHint:K.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Kp(e){return e?e.map(xp).filter(e=>typeof e==`string`&&e.length>0):[]}function qp(){let e=bp();if(e)return K.join(e,`.aimax`,`extensions`)}function Jp(e){return K.join(e,`.aimax`,`extensions`)}function Yp(e){return K.join(e,`.aimax`,`extensions`)}function Xp(e={}){let t=[],n=[],r=Kp(e.extraPaths);for(let i of r){if(!J.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=kp(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Mp.has(K.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=K.dirname(i);if(Vp({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Up({idHint:Hp(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Gp({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Gp({rootDir:Jp(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Gp({rootDir:Yp(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=qp();return i?Gp({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&&Gp({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Zp(e){let t=e.rejectHardlinks??!0,n=Op(e.rootPath),r=Op(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!Ap(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=J.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:J.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Qp=`aimax.plugin.json`,$p=[Qp];function em(e){for(let t of $p){let n=K.join(e,t);if(J.existsSync(n))return n}return K.join(e,Qp)}function tm(e,t=!0){let n=em(e),r=Zp({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(J.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{J.closeSync(r.fd)}if(!vp(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=vp(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=yp(i.skills),f;return vp(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 nm(e){let t=new Map,n=[];for(let r of e){let e=tm(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 rm=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function im(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===rm.ERROR){X.error(i);return}if(e===rm.WARN){X.warn(i);return}X.info(i)}function am(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>im(rm.INFO,e.pluginId,t,n),warn:n=>im(rm.WARN,e.pluginId,t,n),error:n=>im(rm.ERROR,e.pluginId,t,n)})}}}function om(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 sm(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 cm(e){let t=[...e.registry.diagnostics],n=new Pf,r=new Xr,i=[],a=[],o=e.runtime?.llm?$r({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=lm(e.runtime?.llmAllowlist),c=pt(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=om({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=sm({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=am({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(!um(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`);W({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`);ce({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=K.isAbsolute(e)?e:K.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Yr(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=K.isAbsolute(e)?e:K.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function lm(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function um(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function dm(e={}){let t=Ep(e.config),n=Xp({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=nm(n.candidates),i=Dp({config:t,registry:r}),a=cm({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 fm(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?dm({...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 Xr,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 pm(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=K.join(t.dataDir,`workspace`),o=n,s=!o,c=Q(t);o?(await r(t.dataDir,o,c)||(s=!0),await g(t.dataDir,o,c)):o=await C(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel},u=fm({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await mp({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:i,hookRegistry:d});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:d,pluginContext:u,runContext:f,start:e=>Js({sessionId:o,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:i,...e})}}function mm(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function hm(e){if(!(e instanceof Error))return{errorValue:mm(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]=mm(n[e]));return t}async function gm(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...hm(e.error)}})}function _m(e,t,n){return K.join(d(e,t,n),`pending-ui-tool.json`)}async function vm(e,t,n,r){let i=d(e,t,r);await G.mkdir(i,{recursive:!0}),await a(_m(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function ym(e,t,n){let r=await l(_m(e,t,n));return r===null?null:JSON.parse(r)}async function bm(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await vm(e,t,a,r),a}async function xm(e,t,n,r,i){let a=await ym(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 vm(e,t,o,i),o}async function Sm(e,t,n){try{await G.unlink(_m(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const Cm=`crons`;function wm(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:ma(e.message)}}function Tm(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Re(t))}async function Em(e,t,n,r){let i=await B(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function Dm(e,t,n,r,i,a){let o=await B(e,t,{storeName:a?.storeName});await Em(e,t,n,a);let s=await zt(e,t,n,r,a);return s.goal&&await nn(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}async function Om(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=mi();if(i=await hi(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(ui(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=km(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 km(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 Am(e,t){pa(e.dataDir),Us();let n=Date.now(),r=new Zr(e),i=Vc(e);X.info(`agent invocation prepared`,{requestedSessionId:i.requestedSessionId,previousSessionId:i.previousSessionId,inputMode:i.inputMode,hasSlashCommand:!!i.slashCommandSource,resetAction:i.resetCommand?.action,resetShortCircuit:i.resetShortCircuit,transcriptLength:i.transcriptMessage.length,messageForRunLength:i.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await pm({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,h=c.pluginContext,g=c.runContext,_=(await m(e.dataDir,l,{storeName:e.sessionStoreName})).length;X.info(`agent run started`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:u,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),X.info(u?`session created`:`session resumed`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await te(e.dataDir,hp({sessionId:l,title:qs(a),channel:e.channel}),Q(e)),e.pendingGoal&&await R(e.dataDir,l,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`}),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(o=await g.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let v=new AbortController;e.abortSignal?.aborted?v.abort():e.abortSignal?.addEventListener(`abort`,()=>v.abort());let y=await vt(e.dataDir),b=[],x=xt(y,{warn:e=>b.push(e)}),S=await wt();await r.dispatchDiagnostic(l,{level:b.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length}}),X.info(`bootstrap context loaded`,{sessionId:l,bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length});let C=e.skillsLoadPaths??[],w=await Mt(e.dataDir,h.pluginSkillDirs,C),T=await Mr({dataDir:e.dataDir,projectDir:e.projectDir,systemAgentsDir:e.systemAgentsDir,agentPolicy:e.agentPolicy}),E=T.stats(),D=e.agentPolicy?.activeAgent??T.findPublic(e.agentPolicy?.requestedAgentName);if(e.agentPolicy?.requestedAgentName&&!D)throw Error(`Unknown custom agent: ${e.agentPolicy.requestedAgentName}`);let O={...T,...D?{activeAgent:D}:{},...e.agentPolicy?.requestedAgentName?{requestedAgentName:e.agentPolicy.requestedAgentName}:{}},k={...e,agentPolicy:O};await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length,skills:w.map(e=>({name:e.name,description:e.description,location:e.location}))}}),X.info(`skills loaded`,{sessionId:l,skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,agents:T.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),X.info(`custom agents loaded`,{sessionId:l,agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,requestedAgentName:O.requestedAgentName});let ee=await jm({dataDir:e.dataDir,sessionId:l,eventDispatcher:r,enabled:e.autoSkills?.load?.enabled===!0}),A=e=>g.appendTranscriptEntry(e),j=await Uc({invocation:i,skills:w,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(j.kind===`completed`)return X.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!j.result.error,paused:!!j.result.paused,uiToolPending:!!j.result.uiToolPending,textLength:j.result.text.length}),j.result;let M=j.effectivePrompt;a=j.transcriptMessage;let N=typeof M==`string`?M:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof M==`string`?`string`:`messages`,transcriptLength:a.length}}),X.info(`invocation resolved`,{sessionId:l,promptType:typeof M==`string`?`string`:`messages`,transcriptLength:a.length});let P=await ap({session:{runParams:k,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},runtimeInputs:{contextFiles:x,bootstrapWarnings:b,skills:w,autoSkillCategories:ee,effectivePromptText:N,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:C,presetSystemPrompt:S.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>Am(e,new Rs),createModel:Tr,abortSignal:v.signal}}),F=P.agent,I=P.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:I,historyMessageCount:P.historyMessages.length,pluginToolCount:h.pluginTools.length}}),X.info(`agent runtime created`,{sessionId:l,modelId:I,historyMessageCount:P.historyMessages.length,pluginToolCount:h.pluginTools.length}),v.signal.addEventListener(`abort`,()=>F.abort());let L=0,z=0,B=``,V,H=!1,U=new Rt;await Em(e.dataDir,l,U,{storeName:e.sessionStoreName});let ne=()=>({input:L,output:z,total:L+z});try{if(Tm(e)){let t=await Om({params:e,agent:F,sessionId:l,eventDispatcher:r,appendEntry:A,abortSignal:v.signal});return B=t.text,Zs({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:B,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(a);H=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let i=await $t(e.dataDir,l,M,{storeName:e.sessionStoreName});X.info(`first agent turn started`,{sessionId:l,modelId:I});let s=await ha({agent:F,message:i.prompt,continueFromHistory:!!e.uiToolResume,sessionId:l,channel:e.channel,modelId:I,historyMessages:P.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await A(e);for(let e of t)await A(e)}});B=s.text,L+=s.inputTokens,z+=s.outputTokens,s.error&&(V=s.error),i.hadObjectiveUpdatedSteering&&!s.error&&await en(e.dataDir,l,{storeName:e.sessionStoreName}),await r.dispatchDiagnostic(l,{level:s.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!s.error,error:s.error,inputTokens:s.inputTokens,outputTokens:s.outputTokens}});let c={sessionId:l,hasError:!!s.error,error:s.error,inputTokens:s.inputTokens,outputTokens:s.outputTokens};s.error?X.warn(`first agent turn completed with error`,c):X.info(`first agent turn completed`,c);let d=await Dm(e.dataDir,l,U,ne(),r,{storeName:e.sessionStoreName,eventSource:`runner`});d.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),X.info(`announce loop started`,{sessionId:l});let m=await lp({agent:F,registry:t,sessionId:l,resolvedModelId:I,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,retry:e.llmRetry,appendEntry:A});if(m.text&&(B=m.text),L+=m.inputTokens,z+=m.outputTokens,m.error&&!V&&(V=m.error),await r.dispatchDiagnostic(l,{level:m.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!m.error,error:m.error,inputTokens:m.inputTokens,outputTokens:m.outputTokens}}),d=await Dm(e.dataDir,l,U,ne(),r,{storeName:e.sessionStoreName,eventSource:`runner`}),d.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Jt()){let n=new qt;n.reset();let i=!0,a=Fe;for(;i&&n.continuationCount<a&&!v.signal.aborted;)if(i=await Zt({agent:F,dataDir:e.dataDir,sessionId:l,sessionStoreName:e.sessionStoreName,state:n,accounting:U,abortSignal:v.signal,executeTurn:async t=>{let n=await ha({agent:F,message:t,continueFromHistory:!1,sessionId:l,channel:e.channel,modelId:I,historyMessages:[],eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,onTurnRecordProduced:async(e,t)=>{await Qt(A,e,t)}});L+=n.inputTokens,z+=n.outputTokens,B=n.text||B,n.error&&!V&&(V=n.error);let i=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:i}},flushAccountingAfterTurn:async()=>{(await Dm(e.dataDir,l,U,ne(),r,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),i){let e=await lp({agent:F,registry:t,sessionId:l,resolvedModelId:I,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,appendEntry:A});L+=e.inputTokens,z+=e.outputTokens,e.text&&(B=e.text),e.error&&!V&&(V=e.error)}}let h={sessionId:l,hasError:!!m.error,error:m.error,inputTokens:m.inputTokens,outputTokens:m.outputTokens};m.error?X.warn(`announce loop completed with error`,h):X.info(`announce loop completed`,h)}catch(t){if(ui(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await pe(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),X.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:L,output:z,total:L+z};return await Mm({runtime:P,resolvedModelId:I,usage:c,currentUserEntryCoveredByUsage:H}),Zs({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:B||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(fi(t)){let i=t,o=i.request.outputSchema.properties??{};await bm(e.dataDir,l,i.request,Q(e)),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length}}),X.info(`agent paused for UI tool input`,{sessionId:l,requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length});let s={input:L,output:z,total:L+z};return await Mm({runtime:P,resolvedModelId:I,usage:s,currentUserEntryCoveredByUsage:H}),Zs({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:B||``,usage:s,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}throw await gm({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),X.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{try{await Dm(e.dataDir,l,U,ne(),r,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}U.clearActiveGoal(),Vs(l),g.stop()}let W={input:L,output:z,total:L+z};await r.dispatchDiagnostic(l,{level:V?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:W.input,outputTokens:W.output,totalTokens:W.total,hasError:!!V,error:V}});let re={sessionId:l,durationMs:Date.now()-n,inputTokens:W.input,outputTokens:W.output,totalTokens:W.total,hasError:!!V,error:V};return V?X.warn(`agent run completed with error`,re):X.info(`agent run completed`,re),await Mm({runtime:P,resolvedModelId:I,usage:W,currentUserEntryCoveredByUsage:H}),await _s({sessionId:l,runParams:k,eventDispatcher:r,transcriptStartIndex:_,result:{text:B,usage:W,durationMs:Date.now()-n,error:V}}),Zs({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:B,usage:W,error:V})}async function jm(e){if(!e.enabled)return[];try{let t=await new ar({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}async function Mm(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 Nm(e){pa(e.dataDir);let n=Date.now(),i=new Zr(e),a=Vc(e),o=a.transcriptMessage.trim()||`CRON task`,s=e.sessionStoreName;X.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:s,...wm(e)});let c=a.requestedSessionId,l=!c;c?(await r(e.dataDir,c,{storeName:s})||(l=!0),await g(e.dataDir,c,{storeName:s})):c=await C(e.dataDir,e.channel,{storeName:s}),l&&await te(e.dataDir,hp({sessionId:c,title:qs(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:Cm});await i.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:u,task:o}),X.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:u,taskLength:o.length,taskPreview:ma(o)});let d={...e,sessionId:u,sessionStoreName:Cm,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await Am(d,new Rs),f.error&&(m=`error`)}catch(t){let r=t instanceof Error?t.message:String(t);f={sessionId:u,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:h(e.dataDir,u,{storeName:Cm}),toolResultsDir:S(e.dataDir,u,{storeName:Cm})}},m=`error`,X.error(`cron child run failed`,{parentSessionId:c,childSessionId:u,error:r})}await i.dispatchProgress(c,{type:`subagent_complete`,childSessionId:u,task:o,status:m}),X.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let _=qd({task:o,status:m,result:f.text,error:f.error}),v=new Date().toISOString();await p(e.dataDir,c,{role:`assistant`,content:_,timestamp:v,source:`cron`},{storeName:s});let y={task:o,status:m,content:_,childSessionId:u,createdAt:v};return await b(e.dataDir,c,y,{storeName:s}),await t(e.dataDir,c,e=>Pm(e,8),{storeName:s}),await x(e.dataDir,c,{},{storeName:s}),{...f,sessionId:c,context:{snapshotPath:h(e.dataDir,c,{storeName:s}),toolResultsDir:S(e.dataDir,c,{storeName:s})}}}function Pm(e,t){if(t<=0)return e.filter(e=>!Fm(e));let n=e.reduce((e,t,n)=>(Fm(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Fm(e)||r.has(t))}function Fm(e){return`source`in e&&e.source===`cron`}async function Im(e,t){if(pa(e.dataDir),X.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,...wm(e)}),e.channel===`CRON`&&!e.subagentContext)return Nm(e);let n=t??new Rs;try{return await Am(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:hm(t)}),X.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 Lm={"AGENTS.md":`---
121
+ `)}`}function Tp(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 Ep(e){let t=Tp(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=G.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 Dp(e){let t=e.watchFactory??((e,t,n)=>q.watch(e,t,n)),n=G.join(e.dataDir,`.aimax`),r=[{target:G.join(n,`MEMORY.md`),kind:`memory-file`},{target:G.join(n,`memory.md`),kind:`memory-file-lower`},{target:G.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=Ep({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 Op(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=G.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=jp(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:h?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},m=G.join(t.dataDir,`.aimax`),h=ce({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),g=h?.provider??ie({dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),_=h?.registration.id??g.id,v=h?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:h?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!h}}).catch(()=>{});let y=Dp({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await p(t.dataDir,i,e,Ap({sessionOptions:Q(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function kp(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Ap(e){return e.sessionOptions.storeName||e.sessionOptions.subagent||e.providerId||e.pluginId?{...e.sessionOptions,providerId:e.providerId,pluginId:e.pluginId,onMemoryChanged:e.onMemoryChanged}:{onMemoryChanged:e.onMemoryChanged}}function jp(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 Mp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Np(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Pp(){let e=ut.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Fp(e){let t=e.trim(),n=Pp();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?G.join(n,t.slice(2)):void 0:G.resolve(t)}const Ip=new pt({allErrors:!0,strict:!1}),Lp=new Map;function Rp(e,t){let n=Lp.get(t);if(n)return n;let r=Ip.compile(e);return Lp.set(t,r),r}function zp(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Rp(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Bp(e){let t=Np(e?.allow),n=Np(e?.deny),r=Np(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 Vp(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=zp({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 Hp(e){try{return q.realpathSync(e)}catch{return null}}function Up(e){try{return q.statSync(e)}catch{return null}}function Wp(e,t){let n=G.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!G.isAbsolute(n)}function Gp(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Kp=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),qp=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Jp(e){let t=G.join(e,`package.json`);if(q.existsSync(t))try{let e=JSON.parse(q.readFileSync(t,`utf-8`));return Mp(e)?e:void 0}catch{return}}function Yp(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 Xp(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Zp(e){let t=Hp(e.source),n=Hp(e.rootDir);return!t||!n||Wp(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Qp(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=G.resolve(r);if(n.has(t))continue;n.add(t);let i=Up(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 $p(e){return Zp({source:e.source,rootDir:e.rootDir})||Qp({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Xp(e.ownershipUid)})}function em(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=${Gp(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function tm(e){let t=$p({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:em(t),source:e.source}),!0):!1}function nm(e){return G.basename(e,G.extname(e))}function rm(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 im(e){for(let t of qp){let n=G.join(e,t);if(q.existsSync(n))return n}return null}function am(e){let t;try{t=q.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=G.join(e.rootDir,n.name);if(n.isFile()){if(!Kp.has(G.extname(n.name)))continue;let r=G.dirname(t);if(tm({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(rm({idHint:nm(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Jp(t),i=Yp(r);if(i.status===`ok`){for(let n of i.entries){let i=G.resolve(t,n);if(!Wp(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!q.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Kp.has(G.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(tm({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${nm(i)}`:nm(i);e.candidates.push(rm({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=im(t);a&&(tm({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(rm({idHint:G.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function om(e){return e?e.map(Fp).filter(e=>typeof e==`string`&&e.length>0):[]}function sm(){let e=Pp();if(e)return G.join(e,`.aimax`,`extensions`)}function cm(e){return G.join(e,`.aimax`,`extensions`)}function lm(e){return G.join(e,`.aimax`,`extensions`)}function um(e={}){let t=[],n=[],r=om(e.extraPaths);for(let i of r){if(!q.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Up(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Kp.has(G.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=G.dirname(i);if(tm({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(rm({idHint:nm(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&am({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?am({rootDir:cm(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&am({rootDir:lm(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=sm();return i?am({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&&am({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function dm(e){let t=e.rejectHardlinks??!0,n=Hp(e.rootPath),r=Hp(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!Wp(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=q.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:q.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const fm=`aimax.plugin.json`,pm=[fm];function mm(e){for(let t of pm){let n=G.join(e,t);if(q.existsSync(n))return n}return G.join(e,fm)}function hm(e,t=!0){let n=mm(e),r=dm({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(q.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{q.closeSync(r.fd)}if(!Mp(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=Mp(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=Np(i.skills),f;return Mp(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 gm(e){let t=new Map,n=[];for(let r of e){let e=hm(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 _m=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function vm(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===_m.ERROR){X.error(i);return}if(e===_m.WARN){X.warn(i);return}X.info(i)}function ym(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>vm(_m.INFO,e.pluginId,t,n),warn:n=>vm(_m.WARN,e.pluginId,t,n),error:n=>vm(_m.ERROR,e.pluginId,t,n)})}}}function bm(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 xm(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 Sm(e){let t=[...e.registry.diagnostics],n=new Jf,r=new Zr,i=[],a=[],o=e.runtime?.llm?$r({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Cm(e.runtime?.llmAllowlist),c=mt(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=bm({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=xm({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=ym({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(!wm(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`);U({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`);le({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=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Xr(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=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Cm(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function wm(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Tm(e={}){let t=Bp(e.config),n=um({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=gm(n.candidates),i=Vp({config:t,registry:r}),a=Sm({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 Em(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Tm({...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 Zr,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 Dm(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=G.join(t.dataDir,`workspace`),o=n,s=!o,c=Q(t);o?(await r(t.dataDir,o,c)||(s=!0),await g(t.dataDir,o,c)):o=await C(t.dataDir,t.channel,{...c});let l={sessionId:o,workspaceDir:a,channel:t.channel},u=Em({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await Op({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:u.memoryPluginId,eventDispatcher:i,hookRegistry:d});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:d,pluginContext:u,runContext:f,start:e=>Ys({sessionId:o,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:i,...e})}}function Om(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function km(e){if(!(e instanceof Error))return{errorValue:Om(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]=Om(n[e]));return t}async function Am(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...km(e.error)}})}function jm(e,t,n){return G.join(d(e,t,n),`pending-ui-tool.json`)}async function Mm(e,t,n,r){let i=d(e,t,r);await W.mkdir(i,{recursive:!0}),await a(jm(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function Nm(e,t,n){let r=await l(jm(e,t,n));return r===null?null:JSON.parse(r)}async function Pm(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Mm(e,t,a,r),a}async function Fm(e,t,n,r,i){let a=await Nm(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 Mm(e,t,o,i),o}async function Im(e,t,n){try{await W.unlink(jm(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const Lm=`crons`;function Rm(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:ha(e.message)}}function zm(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!ze(t))}async function Bm(e,t,n,r){let i=await z(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function Vm(e,t,n,r,i,a){let o=await z(e,t,{storeName:a?.storeName});await Bm(e,t,n,a);let s=await Bt(e,t,n,r,a);return s.goal&&await rn(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}async function Hm(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=hi();if(i=await gi(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(di(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Um(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 Um(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 Wm(e,t){ma(e.dataDir),Ws();let n=Date.now(),r=new Qr(e),i=Hc(e);X.info(`agent invocation prepared`,{requestedSessionId:i.requestedSessionId,previousSessionId:i.previousSessionId,inputMode:i.inputMode,hasSlashCommand:!!i.slashCommandSource,resetAction:i.resetCommand?.action,resetShortCircuit:i.resetShortCircuit,transcriptLength:i.transcriptMessage.length,messageForRunLength:i.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let a=i.transcriptMessage,o=!1,s=i.previousSessionId,c=await Dm({runParams:e,requestedSessionId:i.requestedSessionId,eventDispatcher:r}),l=c.sessionId,u=c.isNewSession,d=c.workspaceDir,f=c.hookContext,p=c.hookRegistry,h=c.pluginContext,g=c.runContext,_=(await m(e.dataDir,l,{storeName:e.sessionStoreName})).length;X.info(`agent run started`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:u,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:u,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),X.info(u?`session created`:`session resumed`,{sessionId:l,requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}),await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:u?`session_created`:`session_resumed`,message:u?`session created`:`session resumed`,details:{requestedSessionId:i.requestedSessionId,previousSessionId:s,workspaceDir:d}}),u&&await M(e.dataDir,kp({sessionId:l,title:Js(a),channel:e.channel}),Q(e)),e.pendingGoal&&await L(e.dataDir,l,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`}),i.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(o=await g.persistInitialUserEntry(a)),await c.start({resetCommand:i.resetCommand,previousSessionId:s,resetMessage:i.slashCommandSource,startMessage:typeof i.promptInput==`string`?i.promptInput:a});let v=new AbortController;e.abortSignal?.aborted?v.abort():e.abortSignal?.addEventListener(`abort`,()=>v.abort());let y=await yt(e.dataDir),b=[],x=St(y,{warn:e=>b.push(e)}),S=await Tt();await r.dispatchDiagnostic(l,{level:b.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length}}),X.info(`bootstrap context loaded`,{sessionId:l,bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length});let C=e.skillsLoadPaths??[],w=await Nt(e.dataDir,h.pluginSkillDirs,C),T=await Nr({dataDir:e.dataDir,projectDir:e.projectDir,systemAgentsDir:e.systemAgentsDir,agentPolicy:e.agentPolicy}),E=T.stats(),D=e.agentPolicy?.activeAgent??T.findPublic(e.agentPolicy?.requestedAgentName);if(e.agentPolicy?.requestedAgentName&&!D)throw Error(`Unknown custom agent: ${e.agentPolicy.requestedAgentName}`);let O={...T,...D?{activeAgent:D}:{},...e.agentPolicy?.requestedAgentName?{requestedAgentName:e.agentPolicy.requestedAgentName}:{}},k={...e,agentPolicy:O};await r.dispatchDiagnostic(l,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length,skills:w.map(e=>({name:e.name,description:e.description,location:e.location}))}}),X.info(`skills loaded`,{sessionId:l,skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,agents:T.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),X.info(`custom agents loaded`,{sessionId:l,agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,requestedAgentName:O.requestedAgentName});let ee=await Gm({dataDir:e.dataDir,sessionId:l,eventDispatcher:r,enabled:e.autoSkills?.load?.enabled===!0}),A=e=>g.appendTranscriptEntry(e),j=await Wc({invocation:i,skills:w,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(j.kind===`completed`)return X.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!j.result.error,paused:!!j.result.paused,uiToolPending:!!j.result.uiToolPending,textLength:j.result.text.length}),j.result;let te=j.effectivePrompt;a=j.transcriptMessage;let ne=typeof te==`string`?te:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof te==`string`?`string`:`messages`,transcriptLength:a.length}}),X.info(`invocation resolved`,{sessionId:l,promptType:typeof te==`string`?`string`:`messages`,transcriptLength:a.length});let N=await yp({session:{runParams:k,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},runtimeInputs:{contextFiles:x,bootstrapWarnings:b,skills:w,autoSkillCategories:ee,effectivePromptText:ne,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:C,presetSystemPrompt:S.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>Wm(e,new zs),createModel:Er,abortSignal:v.signal}}),P=N.agent,F=N.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:F,historyMessageCount:N.historyMessages.length,pluginToolCount:h.pluginTools.length}}),X.info(`agent runtime created`,{sessionId:l,modelId:F,historyMessageCount:N.historyMessages.length,pluginToolCount:h.pluginTools.length}),v.signal.addEventListener(`abort`,()=>P.abort());let I=0,R=0,z=``,B,V=!1,H=new zt;await Bm(e.dataDir,l,H,{storeName:e.sessionStoreName});let re=()=>({input:I,output:R,total:I+R});try{if(zm(e)){let t=await Hm({params:e,agent:P,sessionId:l,eventDispatcher:r,appendEntry:A,abortSignal:v.signal});return z=t.text,Qs({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(a);V=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let i=await en(e.dataDir,l,te,{storeName:e.sessionStoreName});X.info(`first agent turn started`,{sessionId:l,modelId:F});let s=await ga({agent:P,message:i.prompt,continueFromHistory:!!e.uiToolResume,sessionId:l,channel:e.channel,modelId:F,historyMessages:N.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await A(e);for(let e of t)await A(e)}});z=s.text,I+=s.inputTokens,R+=s.outputTokens,s.error&&(B=s.error),i.hadObjectiveUpdatedSteering&&!s.error&&await tn(e.dataDir,l,{storeName:e.sessionStoreName}),await r.dispatchDiagnostic(l,{level:s.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!s.error,error:s.error,inputTokens:s.inputTokens,outputTokens:s.outputTokens}});let c={sessionId:l,hasError:!!s.error,error:s.error,inputTokens:s.inputTokens,outputTokens:s.outputTokens};s.error?X.warn(`first agent turn completed with error`,c):X.info(`first agent turn completed`,c);let d=await Vm(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`});d.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),X.info(`announce loop started`,{sessionId:l});let m=await Cp({agent:P,registry:t,sessionId:l,resolvedModelId:F,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,retry:e.llmRetry,appendEntry:A});if(m.text&&(z=m.text),I+=m.inputTokens,R+=m.outputTokens,m.error&&!B&&(B=m.error),await r.dispatchDiagnostic(l,{level:m.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!m.error,error:m.error,inputTokens:m.inputTokens,outputTokens:m.outputTokens}}),d=await Vm(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`}),d.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Yt()){let n=new Jt;n.reset();let i=!0,a=Ie;for(;i&&n.continuationCount<a&&!v.signal.aborted;)if(i=await Qt({agent:P,dataDir:e.dataDir,sessionId:l,sessionStoreName:e.sessionStoreName,state:n,accounting:H,abortSignal:v.signal,executeTurn:async t=>{let n=await ga({agent:P,message:t,continueFromHistory:!1,sessionId:l,channel:e.channel,modelId:F,historyMessages:[],eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,onTurnRecordProduced:async(e,t)=>{await $t(A,e,t)}});I+=n.inputTokens,R+=n.outputTokens,z=n.text||z,n.error&&!B&&(B=n.error);let i=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:i}},flushAccountingAfterTurn:async()=>{(await Vm(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),i){let e=await Cp({agent:P,registry:t,sessionId:l,resolvedModelId:F,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,appendEntry:A});I+=e.inputTokens,R+=e.outputTokens,e.text&&(z=e.text),e.error&&!B&&(B=e.error)}}let h={sessionId:l,hasError:!!m.error,error:m.error,inputTokens:m.inputTokens,outputTokens:m.outputTokens};m.error?X.warn(`announce loop completed with error`,h):X.info(`announce loop completed`,h)}catch(t){if(di(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await me(e.dataDir,o,s,i.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},i.toolContext),await r.dispatchProgress(o,{type:`hitl_requested`,request:s}),await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${i.request.kind} — ${i.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),X.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:I,output:R,total:I+R};return await Km({runtime:N,resolvedModelId:F,usage:c,currentUserEntryCoveredByUsage:V}),Qs({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(pi(t)){let i=t,o=i.request.outputSchema.properties??{};await Pm(e.dataDir,l,i.request,Q(e)),await r.dispatchProgress(l,{type:`ui_tool_request`,request:i.request}),await r.dispatchDiagnostic(l,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${i.request.toolName}`,details:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length}}),X.info(`agent paused for UI tool input`,{sessionId:l,requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchemaTitle:i.request.outputSchema.title,propertyCount:Object.keys(o).length});let s={input:I,output:R,total:I+R};return await Km({runtime:N,resolvedModelId:F,usage:s,currentUserEntryCoveredByUsage:V}),Qs({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z||``,usage:s,error:void 0,uiToolPending:{requestId:i.request.requestId,toolName:i.request.toolName,toolCallId:i.request.toolCallId,outputSchema:i.request.outputSchema,extra:i.request.extra}})}throw await Am({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),X.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{try{await Vm(e.dataDir,l,H,re(),r,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}H.clearActiveGoal(),Hs(l),g.stop()}let U={input:I,output:R,total:I+R};await r.dispatchDiagnostic(l,{level:B?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:U.input,outputTokens:U.output,totalTokens:U.total,hasError:!!B,error:B}});let ie={sessionId:l,durationMs:Date.now()-n,inputTokens:U.input,outputTokens:U.output,totalTokens:U.total,hasError:!!B,error:B};return B?X.warn(`agent run completed with error`,ie):X.info(`agent run completed`,ie),await Km({runtime:N,resolvedModelId:F,usage:U,currentUserEntryCoveredByUsage:V}),await vs({sessionId:l,runParams:k,eventDispatcher:r,transcriptStartIndex:_,result:{text:z,usage:U,durationMs:Date.now()-n,error:B}}),Qs({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:z,usage:U,error:B})}async function Gm(e){if(!e.enabled)return[];try{let t=await new or({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}async function Km(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 qm(e){ma(e.dataDir);let n=Date.now(),i=new Qr(e),a=Hc(e),o=a.transcriptMessage.trim()||`CRON task`,s=e.sessionStoreName;X.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:s,...Rm(e)});let c=a.requestedSessionId,l=!c;c?(await r(e.dataDir,c,{storeName:s})||(l=!0),await g(e.dataDir,c,{storeName:s})):c=await C(e.dataDir,e.channel,{storeName:s}),l&&await M(e.dataDir,kp({sessionId:c,title:Js(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:Lm});await i.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:u,task:o}),X.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:u,taskLength:o.length,taskPreview:ha(o)});let d={...e,sessionId:u,sessionStoreName:Lm,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await Wm(d,new zs),f.error&&(m=`error`)}catch(t){let r=t instanceof Error?t.message:String(t);f={sessionId:u,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:h(e.dataDir,u,{storeName:Lm}),toolResultsDir:S(e.dataDir,u,{storeName:Lm})}},m=`error`,X.error(`cron child run failed`,{parentSessionId:c,childSessionId:u,error:r})}await i.dispatchProgress(c,{type:`subagent_complete`,childSessionId:u,task:o,status:m}),X.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let _=cf({task:o,status:m,result:f.text,error:f.error}),v=new Date().toISOString();await p(e.dataDir,c,{role:`assistant`,content:_,timestamp:v,source:`cron`},{storeName:s});let y={task:o,status:m,content:_,childSessionId:u,createdAt:v};return await b(e.dataDir,c,y,{storeName:s}),await t(e.dataDir,c,e=>Jm(e,8),{storeName:s}),await x(e.dataDir,c,{},{storeName:s}),{...f,sessionId:c,context:{snapshotPath:h(e.dataDir,c,{storeName:s}),toolResultsDir:S(e.dataDir,c,{storeName:s})}}}function Jm(e,t){if(t<=0)return e.filter(e=>!Ym(e));let n=e.reduce((e,t,n)=>(Ym(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Ym(e)||r.has(t))}function Ym(e){return`source`in e&&e.source===`cron`}async function Xm(e,t){if(ma(e.dataDir),X.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,...Rm(e)}),e.channel===`CRON`&&!e.subagentContext)return qm(e);let n=t??new zs;try{return await Wm(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:km(t)}),X.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 Zm={"AGENTS.md":`---
121
122
  title: "AGENTS.md Template"
122
123
  summary: ".aimax template for AGENTS.md"
123
124
  read_when:
@@ -410,7 +411,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
410
411
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
411
412
 
412
413
  Add whatever helps you do your job. This is your cheat sheet.
413
- `},Rm=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function zm(e,t){try{if(!(await G.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 G.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Bm(e,t,n){try{if(!(await G.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 G.mkdir(K.dirname(e),{recursive:!0});try{await G.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 Vm(e){let t=_t(e);return[e,t,K.join(t,`skills`),K.join(t,`sessions`),K.join(t,`memory`),K.join(e,`workspace`)]}function Hm(e){let t=_t(e);return[...Rm.filter(e=>e!==`BOOTSTRAP.md`).map(e=>K.join(t,e)),K.join(t,`MEMORY.md`)]}function Um(e){return K.join(_t(e),`.bootstrapped`)}async function Wm(e){try{return(await G.stat(Um(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Gm(e){let t=Um(e);await G.mkdir(K.dirname(t),{recursive:!0}),await G.writeFile(t,``,{encoding:`utf-8`})}async function Km(e){let t=[],n=[];for(let n of Vm(e))try{(await G.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Hm(e))try{(await G.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 qm(e){return(await Km(e)).ready}async function Jm(e){if(await Wm(e))return{ready:!0,performedBootstrap:!1};if((await Km(e)).ready)return await Gm(e),{ready:!0,performedBootstrap:!1};let t=await Ym(e);return await Gm(e),{ready:!0,performedBootstrap:!0,result:t}}async function Ym(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=_t(e),r=K.join(e,`workspace`),i=K.join(n,`skills`),a=K.join(n,`sessions`),o=K.join(n,`memory`);await zm(e,t),await zm(n,t),await zm(i,t),await zm(a,t),await zm(o,t),await zm(r,t);for(let e of Rm){let r=Lm[e]??``;await Bm(K.join(n,e),r,t)}return await Bm(K.join(n,`MEMORY.md`),``,t),t}async function Xm(e){let t=K.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await G.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 Zm(e,t){let n=K.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 G.mkdir(K.dirname(n),{recursive:!0}),await G.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Qm(e,t){let n=await Xm(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 $m(e,t=7){let n=await Xm(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 Zm(e,n),i}var eh=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function th(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function nh(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await B(t,n,s);if(!l)return{action:`created`,goal:await R(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let u=(await H(t,n,l,s)).trim();if(u!==c){if(!a)throw new eh(`A different goal already exists for this session. Use --force to replace it.`,th(u));return{action:`replaced`,goal:await R(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})}}if(l.status===`complete`&&!a)throw new eh(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,th(u));if(a)return{action:`replaced`,goal:await R(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await L(t,n,d,{storeName:o,eventSource:`cli`})}}async function rh(e,t,n,r){let i=await ge(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Le(i.request)?(await fe(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 ih(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await he(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 rh(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await fe(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 ah={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 oh(e){return e.action===`timeout`?ah.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?ah.approval.summary.approved:ah.approval.summary.denied}function sh(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:oh(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function ch(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 lh(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 uh(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
414
+ `},Qm=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function $m(e,t){try{if(!(await W.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 W.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function eh(e,t,n){try{if(!(await W.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 W.mkdir(G.dirname(e),{recursive:!0});try{await W.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 th(e){let t=vt(e);return[e,t,G.join(t,`skills`),G.join(t,`sessions`),G.join(t,`memory`),G.join(e,`workspace`)]}function nh(e){let t=vt(e);return[...Qm.filter(e=>e!==`BOOTSTRAP.md`).map(e=>G.join(t,e)),G.join(t,`MEMORY.md`)]}function rh(e){return G.join(vt(e),`.bootstrapped`)}async function ih(e){try{return(await W.stat(rh(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function ah(e){let t=rh(e);await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,``,{encoding:`utf-8`})}async function oh(e){let t=[],n=[];for(let n of th(e))try{(await W.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of nh(e))try{(await W.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 sh(e){return(await oh(e)).ready}async function ch(e){if(await ih(e))return{ready:!0,performedBootstrap:!1};if((await oh(e)).ready)return await ah(e),{ready:!0,performedBootstrap:!1};let t=await lh(e);return await ah(e),{ready:!0,performedBootstrap:!0,result:t}}async function lh(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=vt(e),r=G.join(e,`workspace`),i=G.join(n,`skills`),a=G.join(n,`sessions`),o=G.join(n,`memory`);await $m(e,t),await $m(n,t),await $m(i,t),await $m(a,t),await $m(o,t),await $m(r,t);for(let e of Qm){let r=Zm[e]??``;await eh(G.join(n,e),r,t)}return await eh(G.join(n,`MEMORY.md`),``,t),t}async function uh(e){let t=G.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await W.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 dh(e,t){let n=G.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 W.mkdir(G.dirname(n),{recursive:!0}),await W.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function fh(e,t){let n=await uh(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 ph(e,t=7){let n=await uh(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 dh(e,n),i}var mh=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function hh(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function gh(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await z(t,n,s);if(!l)return{action:`created`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let u=(await V(t,n,l,s)).trim();if(u!==c){if(!a)throw new mh(`A different goal already exists for this session. Use --force to replace it.`,hh(u));return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})}}if(l.status===`complete`&&!a)throw new mh(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,hh(u));if(a)return{action:`replaced`,goal:await L(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`})};let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await I(t,n,d,{storeName:o,eventSource:`cli`})}}async function _h(e,t,n,r){let i=await _e(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Re(i.request)?(await pe(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 vh(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ge(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 _h(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await pe(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 yh={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 bh(e){return e.action===`timeout`?yh.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?yh.approval.summary.approved:yh.approval.summary.denied}function xh(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:bh(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Sh(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 Ch(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 wh(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
414
415
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
415
416
  `)):(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(`
416
- `))}export{ar as AutoSkillsLoader,gt as BOOTSTRAP_FILE_NAMES,mt as BOOTSTRAP_MAX_CHARS,ht as BOOTSTRAP_TOTAL_MAX_CHARS,qt as ContinuationState,ee as DEFAULT_SESSION_STORE_NAME,Kt as ENV_GOAL_CONTINUATION,Rt as GoalAccounting,eh as GoalConflictError,ah as HITL_MESSAGES,li as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,Ls as MAX_CHILDREN_PER_SESSION,Is as MAX_SUBAGENT_DEPTH,ae as MemoryIndexManager,Qp as PLUGIN_MANIFEST_FILENAME,$p as PLUGIN_MANIFEST_FILENAMES,Xr as PluginHookRegistry,Pf as PluginToolRegistry,Er as SYSTEM_AGENTS_DIR,Rs as SubagentRegistry,di as UiToolPauseSignal,Me as addAgent,Oe as addBinding,Or as agentDirCandidates,Ir as agentVisibility,_t as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,F as appendGoalEvent,Gu as appendRecentToMemory,o as appendSessionFile,Wu as appendToMemory,p as appendTranscriptEntry,nh as applyCliGoalBeforeRun,oh as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,Bn as autoSkillsDir,Ym as bootstrapMountLayout,Br as buildAgentDelegationPrompt,Vr as buildAgentTaskPrompt,xt as buildBootstrapContextFiles,Ht as buildBudgetLimitPrompt,Vt as buildContinuationPrompt,Wt as buildGoalContextItem,Ut as buildObjectiveUpdatedPrompt,uh as buildResumeNarration,Lt as buildSkillsPrompt,qd as buildSubagentAnnounceMessage,Mf as buildSystemPrompt,$m as cleanupOldSubagentRecords,_e as clearPendingHitl,Sm as clearPendingUiTool,k as collapseLogPath,en as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,Xt as continuationTurnHadMeaningfulOutput,Ar as createAgentDefinitionsContext,sf as createAgentTools,Cu as createApplyPatchTool,mo as createAutoSkillCategoriesTool,ho as createAutoSkillListTool,go as createAutoSkillSearchTool,_o as createAutoSkillViewTool,rr as createAutoSkillsLoader,iu as createBashTool,Zd as createBatchSubagentSpawnTool,re as createBuiltinMemoryProvider,jl as createContextManager,mu as createEditFileTool,Hl as createExecTool,rf as createImageTool,gu as createListDirTool,$u as createMemoryAppendTool,pd as createMemoryForgetTool,Zu as createMemoryGetTool,dd as createMemoryListTool,ld as createMemoryLogTool,Yu as createMemorySearchTool,hd as createMemoryUpdateTool,td as createMemoryWriteTool,pe as createPendingHitl,bm as createPendingUiTool,Yr as createPluginProgressEmitter,am as createPluginRuntime,Kl as createProcessTool,uu as createReadFileTool,C as createSession,il as createSessionContextStore,_d as createSessionSearchTool,Rd as createSkillListTool,zd as createSkillLoadTool,Xd as createSubagentSpawnTool,tf as createSubagentsTool,of as createUiTool,fu as createWriteFileTool,A as cronExecutionsPath,af as defaultUiToolInputSchema,U as deleteGoal,qu as deleteMemoryFile,Xp as discoverAIMaxPlugins,tn as emitGoalUpdatedProgress,Jm as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,Rr as filterSkillsForAgent,zr as filterToolsForAgent,Fr as findAgentDefinition,Pt as findSkillByName,zt as flushAccounting,sh as formatApprovalResolution,ch as formatClarifyResolution,lh as formatReviewResolution,Gs as generateSessionTitle,Te as getAgentConfig,Uu as getMemoryLines,P as goalEventsPath,z as goalObjectiveMdPath,V as goalPath,Wm as hasBootstrapSentinel,de as hitlHistoryPath,dm as initializePluginSystem,Km as inspectBootstrapMountLayout,D as inspectSession,qm as isBootstrapMountLayoutReady,Jt as isContinuationEnabled,Gt as isGoalContext,ui as isHitlPauseSignal,fi as isUiToolPauseSignal,ye as listAgents,cc as listAvailableSlashCommands,ke as listBindings,zu as listMemoryFiles,w as listSessionSummaries,y as listSessions,Qm as listSubagentRunsFromDisk,Nr as loadAgentDefinitionsFromDir,je as loadAgentsConfig,v as loadArtifactOperations,vt as loadBootstrapFiles,f as loadCronExecutionRecords,ge as loadPendingHitl,ge as readPendingHitl,ym as loadPendingUiTool,ym as readPendingUiTool,tm as loadPluginManifest,nm as loadPluginManifestRegistry,cm as loadPlugins,j as loadSessionContextSnapshot,N as loadSessionMetadata,It as loadSkillView,jt as loadSkills,Nt as loadSkillsFromDirs,Mt as loadSkillsWithPluginDirs,Xm as loadSubagentRegistryFromDisk,m as loadTranscript,Zt as maybeContinueGoalIfIdle,Fu as memoryDir,M as metadataPath,I as mirrorGoalStatusToSession,be as normalizeAgentId,Ep as normalizePluginsConfig,u as normalizeSessionStoreName,Pr as parseAgentDefinition,ue as pendingHitlPath,_m as pendingUiToolPath,$t as prependObjectiveUpdatedSteeringIfNeeded,Iu as primaryMemoryPath,Lr as publicAgentDefinitions,B as readGoal,me as readHitlHistory,Bu as readMemoryFile,Vu as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,W as registerEmbeddingProvider,ce as registerMemoryProvider,Ee as removeAgent,Ne as removeBindings,Ku as replaceMemoryFile,ne as resetEmbeddingProviderRegistryForTests,le as resetMemoryProviderRegistryForTests,Mr as resolveAgentDefinitionsContext,xe as resolveAgentDir,Se as resolveAgentIdByBinding,Ae as resolveAgentsConfigPath,De as resolveDefaultAgentId,ie as resolveEmbeddingProvider,H as resolveGoalObjective,ih as resolveHitlRequest,ih as resolvePendingHitl,se as resolveMemoryProvider,we as resolveModelFallbacks,Ce as resolveModelString,xm as resolvePendingUiTool,em as resolvePluginManifestPath,t as rewriteTranscript,Im as runAgent,ve as saveAgentsConfig,te as saveSessionMetadata,Zm as saveSubagentRegistryToDisk,kr as scanAgentDefinitions,Hu as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,Yt as shouldContinueGoal,Tt as skillsDir,S as toolResultsDir,e as transcriptPath,fe as transitionHitlStatus,Pe as updateAgentIdentity,L as updateGoal,x as updateSessionMetadata,Dp as validatePluginsConfig,rh as validateResume,If as wrapToolsWithHooks,R as writeGoal,a as writeSessionFile};
417
+ `))}export{or as AutoSkillsLoader,_t as BOOTSTRAP_FILE_NAMES,ht as BOOTSTRAP_MAX_CHARS,gt as BOOTSTRAP_TOTAL_MAX_CHARS,Jt as ContinuationState,ee as DEFAULT_SESSION_STORE_NAME,qt as ENV_GOAL_CONTINUATION,zt as GoalAccounting,mh as GoalConflictError,yh as HITL_MESSAGES,ui as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,Rs as MAX_CHILDREN_PER_SESSION,Ls as MAX_SUBAGENT_DEPTH,oe as MemoryIndexManager,fm as PLUGIN_MANIFEST_FILENAME,pm as PLUGIN_MANIFEST_FILENAMES,Zr as PluginHookRegistry,Jf as PluginToolRegistry,Dr as SYSTEM_AGENTS_DIR,zs as SubagentRegistry,fi as UiToolPauseSignal,Ne as addAgent,ke as addBinding,kr as agentDirCandidates,Lr as agentVisibility,vt as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,P as appendGoalEvent,ad as appendRecentToMemory,o as appendSessionFile,id as appendToMemory,p as appendTranscriptEntry,gh as applyCliGoalBeforeRun,bh as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,Vn as autoSkillsDir,lh as bootstrapMountLayout,Vr as buildAgentDelegationPrompt,Hr as buildAgentTaskPrompt,St as buildBootstrapContextFiles,Ut as buildBudgetLimitPrompt,Ht as buildContinuationPrompt,Gt as buildGoalContextItem,Wt as buildObjectiveUpdatedPrompt,wh as buildResumeNarration,Rt as buildSkillsPrompt,cf as buildSubagentAnnounceMessage,Kf as buildSystemPrompt,ph as cleanupOldSubagentRecords,ve as clearPendingHitl,Im as clearPendingUiTool,k as collapseLogPath,tn as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,Zt as continuationTurnHadMeaningfulOutput,jr as createAgentDefinitionsContext,xf as createAgentTools,Lu as createApplyPatchTool,ho as createAutoSkillCategoriesTool,go as createAutoSkillListTool,_o as createAutoSkillSearchTool,vo as createAutoSkillViewTool,ir as createAutoSkillsLoader,vu as createBashTool,ff as createBatchSubagentSpawnTool,ie as createBuiltinMemoryProvider,Gl as createContextManager,Ou as createEditFileTool,nu as createExecTool,vf as createImageTool,Au as createListDirTool,pd as createMemoryAppendTool,Dd as createMemoryForgetTool,dd as createMemoryGetTool,Td as createMemoryListTool,Cd as createMemoryLogTool,ld as createMemorySearchTool,kd as createMemoryUpdateTool,hd as createMemoryWriteTool,me as createPendingHitl,Pm as createPendingUiTool,Xr as createPluginProgressEmitter,ym as createPluginRuntime,ou as createProcessTool,wu as createReadFileTool,C as createSession,vl as createSessionContextStore,jd as createSessionSearchTool,Qd as createSkillListTool,$d as createSkillLoadTool,df as createSubagentSpawnTool,gf as createSubagentsTool,bf as createUiTool,Eu as createWriteFileTool,A as cronExecutionsPath,yf as defaultUiToolInputSchema,H as deleteGoal,sd as deleteMemoryFile,um as discoverAIMaxPlugins,nn as emitGoalUpdatedProgress,ch as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,zr as filterSkillsForAgent,Br as filterToolsForAgent,Ir as findAgentDefinition,Ft as findSkillByName,Bt as flushAccounting,xh as formatApprovalResolution,Sh as formatClarifyResolution,Ch as formatReviewResolution,Ks as generateSessionTitle,Ee as getAgentConfig,rd as getMemoryLines,N as goalEventsPath,R as goalObjectiveMdPath,B as goalPath,ih as hasBootstrapSentinel,fe as hitlHistoryPath,Tm as initializePluginSystem,oh as inspectBootstrapMountLayout,D as inspectSession,sh as isBootstrapMountLayoutReady,Yt as isContinuationEnabled,Kt as isGoalContext,di as isHitlPauseSignal,pi as isUiToolPauseSignal,be as listAgents,lc as listAvailableSlashCommands,Ae as listBindings,$u as listMemoryFiles,w as listSessionSummaries,y as listSessions,fh as listSubagentRunsFromDisk,Pr as loadAgentDefinitionsFromDir,Me as loadAgentsConfig,v as loadArtifactOperations,yt as loadBootstrapFiles,f as loadCronExecutionRecords,_e as loadPendingHitl,_e as readPendingHitl,Nm as loadPendingUiTool,Nm as readPendingUiTool,hm as loadPluginManifest,gm as loadPluginManifestRegistry,Sm as loadPlugins,j as loadSessionContextSnapshot,ne as loadSessionMetadata,Lt as loadSkillView,Mt as loadSkills,Pt as loadSkillsFromDirs,Nt as loadSkillsWithPluginDirs,uh as loadSubagentRegistryFromDisk,m as loadTranscript,Qt as maybeContinueGoalIfIdle,Yu as memoryDir,te as metadataPath,F as mirrorGoalStatusToSession,xe as normalizeAgentId,Bp as normalizePluginsConfig,u as normalizeSessionStoreName,Fr as parseAgentDefinition,de as pendingHitlPath,jm as pendingUiToolPath,en as prependObjectiveUpdatedSteeringIfNeeded,Xu as primaryMemoryPath,Rr as publicAgentDefinitions,z as readGoal,he as readHitlHistory,ed as readMemoryFile,td as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,U as registerEmbeddingProvider,le as registerMemoryProvider,De as removeAgent,Pe as removeBindings,od as replaceMemoryFile,re as resetEmbeddingProviderRegistryForTests,ue as resetMemoryProviderRegistryForTests,Nr as resolveAgentDefinitionsContext,Se as resolveAgentDir,Ce as resolveAgentIdByBinding,je as resolveAgentsConfigPath,Oe as resolveDefaultAgentId,ae as resolveEmbeddingProvider,V as resolveGoalObjective,vh as resolveHitlRequest,vh as resolvePendingHitl,ce as resolveMemoryProvider,Te as resolveModelFallbacks,we as resolveModelString,Fm as resolvePendingUiTool,mm as resolvePluginManifestPath,t as rewriteTranscript,Xm as runAgent,ye as saveAgentsConfig,M as saveSessionMetadata,dh as saveSubagentRegistryToDisk,Ar as scanAgentDefinitions,nd as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,Xt as shouldContinueGoal,Et as skillsDir,S as toolResultsDir,e as transcriptPath,pe as transitionHitlStatus,Fe as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,Vp as validatePluginsConfig,_h as validateResume,Xf as wrapToolsWithHooks,L as writeGoal,a as writeSessionFile};