@gencode/agents 0.9.3-preview.1 → 0.9.3-preview.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +108 -108
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,147 +1,147 @@
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-MBebUrjk.js";import{n as N,t as P}from"./goal-events-Og8bMhZU.js";import{a as F,c as I,l as L,n as re,o as R,r as z,s as B,t as V}from"./goal-store-C_Z3P5Cg.js";import{a as H,c as ie,i as ae,l as oe,n as se,o as ce,r as le,s as ue,u as U}from"./builtin-provider-PIpf9WYR.js";import{i as de,n as fe,r as pe}from"./provider-registry-Kh5nNG84.js";import{a as me,i as he,l as ge,n as _e,o as ve,r as ye,s as be,t as xe}from"./session-store-DYB18J4L.js";import{_ as Se,a as Ce,c as we,d as Te,f as Ee,g as De,h as Oe,i as ke,l as Ae,m as je,n as Me,o as Ne,p as Pe,s as Fe,t as Ie,u as Le,v as Re,y as ze}from"./config-DYv0xUdi.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Be,formatTaskForDisplay as Ve,isHitlExpired as He,isHitlTool as Ue,validateUiToolResult as We}from"@gencode/shared";import W,{readFile as Ge}from"node:fs/promises";import G,{join as Ke}from"node:path";import qe from"gray-matter";import{createHash as Je,randomUUID as Ye}from"node:crypto";import{TextDecoder as Xe}from"node:util";import{Agent as Ze}from"@mariozechner/pi-agent-core";import{AsyncLocalStorage as Qe}from"node:async_hooks";import K from"node:fs";import $e from"log4js";import et from"openai";import{Type as q,calculateCost as tt,getEnvApiKey as nt,parseStreamingJson as rt,registerApiProvider as it,registerBuiltInApiProviders as at,streamSimple as ot,supportsXhigh as st}from"@mariozechner/pi-ai";import{AssistantMessageEventStream as ct}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as lt}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as ut,hasCopilotVisionInput as dt}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as ft,clampReasoning as pt}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as mt}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import ht from"node:os";import{fileURLToPath as gt}from"node:url";import{spawn as _t}from"node:child_process";import{isBinaryFile as vt}from"isbinaryfile";import yt from"ajv";import{createJiti as bt}from"jiti";const xt=2e4,St=15e4,Ct=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function wt(e){return G.join(e,`.aimax`)}async function Tt(e){let t=wt(e),n=[];for(let e of Ct){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 Et(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
2
- `),s].join(`
3
- `),truncated:!0,originalLength:r.length}}function Dt(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Ot(e,t){let n=t?.maxChars??xt,r=Math.max(1,t?.totalMaxChars??Math.max(n,St)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Dt(`[MISSING] Expected at: ${a.path}`,r);if(!e)break;r=Math.max(0,r-e.length),i.push({path:a.path,content:e});continue}if(r<64){t?.warn?.(`remaining bootstrap budget is ${r} chars (<64); skipping additional files`);break}let e=Math.max(1,Math.min(n,r)),{result:o,truncated:s,originalLength:c}=Et(a.content??``,a.name,e),l=Dt(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 kt=`You are a personal assistant running inside AiMax.`;async function At(e){try{return{presetSystemPrompt:qe(await W.readFile(e,`utf-8`)).content.trim()||kt}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:kt};throw e}}async function jt(){return At(`/aimax_pvc/system_prompt.md`)}function Mt(e){return G.join(e,`.aimax`,`skills`)}function Nt(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Pt(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${Nt(n)}\n`)}function Ft(e){let t=qe(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 It(e){let t=qe(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 Lt(e){return(await W.stat(e)).mtime.toISOString()}async function Rt(e){return Bt([Mt(e)])}async function zt(e,t,n=[]){return Bt([...n,...t,Mt(e)])}async function Bt(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=Ft(i),o=It(i),s=await Lt(r)}catch(t){Pt(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 Vt(e,t){let n=t.trim();if(!n)return;let r=(await Bt(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:G.dirname(r.location)}}async function Ht(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=Ft(o),c=It(o),l=await Lt(a)}catch(e){Pt(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:G.dirname(a)}}async function Ut(e,t,n){let r=n?.trim()?await Ht(t,n):await Vt(e,t);if(!r)return;let i=await W.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Wt(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
- `)).join(`
6
- `)}\n</available_skills>`}var Gt=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 Kt(e,t,n,r,i){let a=await R(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 qt(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function Jt(e,t){let n=qt(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 Yt(e,t){let n=qt(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 Xt(e,t){let n=qt(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 Zt(e){return{role:`user`,content:e}}function Qt(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const $t=`AIMAX_GOAL_CONTINUATION`;var en=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};function tn(){let e=process.env[$t];return e===void 0||e===``||e!==`0`}async function nn(e,t,n,r){if(!tn()||n.continuationCount>=Be)return!1;let i=await R(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-DYB18J4L.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function rn(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function an(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await nn(n,r,a,{storeName:i}))return!1;let u=await R(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 B(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=Zt(p?Yt(u,f):Jt(u,f));a.continuationCount++;let h=await c(m.content);if(a.lastTurnHadOutput=rn(h),p&&(a.budgetWrapUpDone=!0),l&&await l({input:h.inputTokens,output:h.outputTokens,total:h.inputTokens+h.outputTokens}),a.continuationCount>=Be){let e=await R(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-C_Z3P5Cg.js`).then(e=>e.i),{appendGoalEvent:o}=await import(`./goal-events-Og8bMhZU.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 (${Be}), goal paused`)}}return!0}async function on(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function sn(e,t,n,r){let i=await R(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Zt(Xt(i,await B(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 cn(e,t,n){(await R(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await I(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}async function ln(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function un(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 ln(e,t,{action:n.action,goal:n.after??null})}function dn(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 fn(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(bn(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}xn(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 pn(e,t={}){let n=vn(t.limit,`limit`),r=yn(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!xn(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:_n(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function mn(e,t){let n=yn(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 hn(e,t=80){let n=yn(e,`totalEntryCount`),r=yn(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function gn(e,t){return e.slice(t.startIndex,t.endIndex)}function _n(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function vn(e,t){return e===void 0?1/0:yn(e,t)}function yn(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function bn(e){return e.role===`assistant`}function xn(e){return e.role===`tool_result`}const Sn=24e3;async function Cn(e){return jn({params:e,kind:`current_run`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function wn(e){return jn({params:e,kind:`recent_conversation`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Tn(e){return jn({params:e,kind:`transcript_range`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function En(e){let t=zn(e),n=await On(e),r=await Fn(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:kn(e.dataDir,e.sessionId,e.sessionOptions)}}function Dn(e){return{maxEntries:Bn(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Bn(e?.maxBytes??Sn,`limits.maxBytes`)}}async function On(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Mn(await Nn(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 Pn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function kn(t,n,r){return{transcriptPath:e(t,n,r),contextSnapshotPath:h(t,n,r),toolResultsDir:S(t,n,r)}}function An(e,t,n){let r=Vn(e.startIndex,`startIndex`),i=Vn(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 jn(e){let t=zn(e.params),n=An(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=In(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:kn(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Mn(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 Nn(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)Wn(e)&&e.toolResultRef?.sessionId===t&&a.set(Gn(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(Gn(e),e);return Array.from(a.values())}async function Pn(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(!Un(G.resolve(t),r))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Un(G.resolve(n),r))throw Error(`Referenced tool result is outside the session directory.`);let[i,a,o]=await Promise.all([Hn(t),Hn(n),Hn(r)]);if(!Un(i,o))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Un(a,o))throw Error(`Referenced tool result resolves outside the session directory.`);return o}async function Fn(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:Rn(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function In(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=Ln(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 Ln(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:Rn(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function Rn(e){let t=new Xe(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function zn(e){return Dn(e.limits)}function Bn(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function Vn(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function Hn(e){try{return await W.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Kn(e)}`)}}function Un(e,t){let n=G.relative(e,t);return n===``||!n.startsWith(`..`)&&!G.isAbsolute(n)}function Wn(e){return e.role===`tool_result`}function Gn(e){return`${e.toolCallId}\n${e.storagePath}`}function Kn(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function qn(e){return G.join(e,`.aimax`,`auto-skills`)}function Jn(e){return G.join(e,`categories.json`)}function Yn(e){return G.join(e,`.auto_skills_prompt_snapshot.json`)}const Xn=/^[a-z0-9][a-z0-9-]*$/,Zn=/^[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(!Xn.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Qn(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(`.`)||!Zn.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function $n(e,t){return`auto:${J(e)}/${Qn(t)}`}function er(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=Qn(n.slice(r+1));return{skillId:$n(i,a),categoryPath:i,skillName:a}}function tr(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function nr(e,t,n){let r=G.resolve(e),i=G.resolve(r,...J(t).split(`/`),Qn(n));return ir(r,i),i}function rr(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 ir(i,a),a}function ir(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 ar(e){let t=Jn(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=sr(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 or(e){return new Map(e.map(e=>[e.path,e]))}function sr(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 cr=32*1024,lr=new Map;function ur(e){return new fr(e)}async function dr(e){let t=G.resolve(e);for(let e of Array.from(lr.keys()))e.startsWith(`${t}|`)&&lr.delete(e);await W.rm(Yn(t),{force:!0}).catch(()=>{})}var fr=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??qn(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return mr(or((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?J(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>hr(e.categoryPath,t)).map(pr)}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:gr(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})=>({...pr(e),score:t}))}async autoSkillView(e){let t=er(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=rr(n.skillDir,e.filePath),r=await Tr(t,this.maxResourceBytes);return{...pr(n),status:n.status,content:r,path:Or(G.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Or(G.relative(n.skillDir,t))}}let r=await Tr(n.skillFile,this.maxSkillBytes);return{...pr(n),status:n.status,content:r,path:Or(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 _r(this.rootDir),i=lr.get(n);if(!e&&i&&Sr(i.manifest,r))return i;let a=e?void 0:await br(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return lr.set(n,e),e}let o=await ar(this.rootDir),s=or(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return lr.set(n,c),await xr(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 jr({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:cr})}async loadEntry(e){try{let t=G.dirname(e),n=Qn(G.basename(t)),r=Or(G.relative(this.rootDir,t)),i=J(G.posix.dirname(r)),a=$n(i,n),o=G.join(t,`metadata.json`),s=await Cr(o);if(s?.skillId&&er(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=tr(s?.status);return{skillId:a,name:n,description:Er(await wr(e,cr)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:Dr(s?.tags),relatedSkills:Dr(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}: ${kr(t)}\n`);return}}};function pr(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function mr(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function hr(e,t){return t?e===t:!0}function gr(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 _r(e){let t;try{t=await W.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await yr(G.join(e,`categories.json`),`categories`,n),await vr(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function vr(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 yr(t,`skill`,n),await yr(G.join(e,`metadata.json`),`metadata`,n),await yr(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 vr(t,i,n)}}async function yr(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 br(e,t,n){let r;try{r=await W.readFile(Yn(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)||!Sr(e.manifest,n)?void 0:e}catch{return}}async function xr(e,t){if(!await Ar(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(Yn(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function Sr(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 Cr(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 wr(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 Tr(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 Er(e){let t=qe(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 Dr(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Or(e){return e.split(G.sep).join(`/`)}function kr(e){return e instanceof Error?e.message:String(e)}async function Ar(e){try{return await W.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function jr(e){return Je(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Mr(e){return e??`openai-completions`}function Nr(e,t,n){let r={"Client-Code":`AIMax`,"X-Session-Id":e};return t&&(r[`X-Message-Id`]=t),n&&(r[`X-Channel`]=n),r}function Pr(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}}const Fr={apiFormat:`anthropic-messages`,createModel:Ir,buildRequest:Rr,normalizeResponse:zr};function Ir(e,t,n,r){return{id:e.model,name:e.model,api:`anthropic-messages`,provider:`anthropic`,baseUrl:Lr(e.baseUrl),reasoning:!1,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:Nr(t,n,r)}}function Lr(e){return e.replace(/\/+$/,``).replace(/\/v1$/,``)}function Rr(e,t,n,r){let i=e.baseUrl.replace(/\/+$/,``),a=[],o=[];for(let e of n){if(e.role===`system`){e.content.trim()&&o.push(e.content);continue}a.push({role:e.role,content:e.content})}let s={model:t,messages:a.length>0?a:[{role:`user`,content:``}],max_tokens:r.maxTokens??2048,stream:!1};return o.length>0&&(s.system=o.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 A,u as j,v as M,w as N,x as ee,y as P}from"./session-MBebUrjk.js";import{n as F,t as te}from"./goal-events-Og8bMhZU.js";import{a as ne,c as I,l as L,n as R,o as z,r as re,s as B,t as ie}from"./goal-store-C_Z3P5Cg.js";import{a as ae,c as oe,i as se,l as ce,n as le,o as ue,r as de,s as fe,u as pe}from"./builtin-provider-PIpf9WYR.js";import{i as me,n as he,r as ge}from"./provider-registry-Kh5nNG84.js";import{a as _e,i as ve,l as ye,n as be,o as xe,r as Se,s as Ce,t as we}from"./session-store-DYB18J4L.js";import{_ as Te,a as Ee,c as De,d as Oe,f as ke,g as Ae,h as je,i as Me,l as Ne,m as Pe,n as Fe,o as Ie,p as Le,s as Re,t as ze,u as Be,v as Ve,y as He}from"./config-DYv0xUdi.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Ue,formatTaskForDisplay as We,isHitlExpired as Ge,isHitlTool as Ke,validateUiToolResult as qe}from"@gencode/shared";import V,{readFile as Je}from"node:fs/promises";import H,{join as Ye}from"node:path";import{createHash as Xe,randomUUID as Ze}from"node:crypto";import{TextDecoder as Qe}from"node:util";import $e from"gray-matter";import{Agent as et}from"@mariozechner/pi-agent-core";import{AsyncLocalStorage as tt}from"node:async_hooks";import U from"node:fs";import nt from"log4js";import rt from"openai";import{Type as W,calculateCost as it,getEnvApiKey as at,parseStreamingJson as ot,registerApiProvider as st,registerBuiltInApiProviders as ct,streamSimple as lt,supportsXhigh as ut}from"@mariozechner/pi-ai";import{AssistantMessageEventStream as dt}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as ft}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as pt,hasCopilotVisionInput as mt}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as ht,clampReasoning as gt}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as _t}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import vt from"node:os";import{fileURLToPath as yt}from"node:url";import{spawn as bt}from"node:child_process";import{isBinaryFile as xt}from"isbinaryfile";import St from"ajv";import{createJiti as Ct}from"jiti";var wt=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 Tt(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 Et(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function Dt(e,t){let n=Et(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(`
2
+ `)}function Ot(e,t){let n=Et(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(`
3
+ `)}function kt(e,t){let n=Et(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(`
4
+ `)}function At(e){return{role:`user`,content:e}}function jt(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Mt=`AIMAX_GOAL_CONTINUATION`;var Nt=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};function Pt(){let e=process.env[Mt];return e===void 0||e===``||e!==`0`}async function Ft(e,t,n,r){if(!Pt()||n.continuationCount>=Ue)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-DYB18J4L.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function It(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Lt(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await Ft(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 B(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=At(p?Ot(u,f):Dt(u,f));a.continuationCount++;let h=await c(m.content);if(a.lastTurnHadOutput=It(h),p&&(a.budgetWrapUpDone=!0),l&&await l({input:h.inputTokens,output:h.outputTokens,total:h.inputTokens+h.outputTokens}),a.continuationCount>=Ue){let e=await z(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-C_Z3P5Cg.js`).then(e=>e.i),{appendGoalEvent:o}=await import(`./goal-events-Og8bMhZU.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 (${Ue}), goal paused`)}}return!0}async function Rt(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function zt(e,t,n,r){let i=await z(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=At(kt(i,await B(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 Bt(e,t,n){(await z(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await I(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}function Vt(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 Ht(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(Xt(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}Zt(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 Ut(e,t={}){let n=Jt(t.limit,`limit`),r=Yt(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!Zt(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:qt(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Wt(e,t){let n=Yt(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 Gt(e,t=80){let n=Yt(e,`totalEntryCount`),r=Yt(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Kt(e,t){return e.slice(t.startIndex,t.endIndex)}function qt(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Jt(e,t){return e===void 0?1/0:Yt(e,t)}function Yt(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function Xt(e){return e.role===`assistant`}function Zt(e){return e.role===`tool_result`}const Qt=24e3;async function $t(e){return cn({params:e,kind:`current_run`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function en(e){return cn({params:e,kind:`recent_conversation`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function tn(e){return cn({params:e,kind:`transcript_range`,transcript:await m(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function nn(e){let t=gn(e),n=await an(e),r=await fn(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:on(e.dataDir,e.sessionId,e.sessionOptions)}}function rn(e){return{maxEntries:_n(e?.maxEntries??80,`limits.maxEntries`),maxBytes:_n(e?.maxBytes??Qt,`limits.maxBytes`)}}async function an(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=ln(await un(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 on(t,n,r){return{transcriptPath:e(t,n,r),contextSnapshotPath:h(t,n,r),toolResultsDir:S(t,n,r)}}function sn(e,t,n){let r=vn(e.startIndex,`startIndex`),i=vn(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 cn(e){let t=gn(e.params),n=sn(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=pn(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:on(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function ln(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 un(e,t,n){let[r,i]=await Promise.all([m(e,t,n),M(e,t,n)]),a=new Map;for(let e of r)xn(e)&&e.toolResultRef?.sessionId===t&&a.set(Sn(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(Sn(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(H.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=H.resolve(e.dataDir,e.reference.storagePath);if(!bn(H.resolve(t),r))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!bn(H.resolve(n),r))throw Error(`Referenced tool result is outside the session directory.`);let[i,a,o]=await Promise.all([yn(t),yn(n),yn(r)]);if(!bn(i,o))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!bn(a,o))throw Error(`Referenced tool result resolves outside the session directory.`);return o}async function fn(e,t){let n=await V.stat(e),r=await V.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:hn(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function pn(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=mn(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 mn(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:hn(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function hn(e){let t=new Qe(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function gn(e){return rn(e.limits)}function _n(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function vn(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function yn(e){try{return await V.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Cn(e)}`)}}function bn(e,t){let n=H.relative(e,t);return n===``||!n.startsWith(`..`)&&!H.isAbsolute(n)}function xn(e){return e.role===`tool_result`}function Sn(e){return`${e.toolCallId}\n${e.storagePath}`}function Cn(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function wn(e){return H.join(e,`.aimax`,`auto-skills`)}function Tn(e){return H.join(e,`categories.json`)}function En(e){return H.join(e,`.auto_skills_prompt_snapshot.json`)}const Dn=/^[a-z0-9][a-z0-9-]*$/,On=/^[a-z0-9][a-z0-9-]*$/;function G(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(`\\`)||H.win32.isAbsolute(t)||H.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(!Dn.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(`.`)||!On.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function An(e,t){return`auto:${G(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=G(n.slice(0,r)),a=kn(n.slice(r+1));return{skillId:An(i,a),categoryPath:i,skillName:a}}function Mn(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Nn(e,t,n){let r=H.resolve(e),i=H.resolve(r,...G(t).split(`/`),kn(n));return Fn(r,i),i}function Pn(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||H.win32.isAbsolute(n)||H.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=H.resolve(e),a=H.resolve(i,...r);return Fn(i,a),a}function Fn(e,t){let n=H.resolve(e),r=H.resolve(t),i=H.relative(n,r);if(i.startsWith(`..`)||H.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function In(e){let t=Tn(e),n;try{n=await V.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=G(e),r=Rn(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 Ln(e){return new Map(e.map(e=>[e.path,e]))}function Rn(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 zn=32*1024,Bn=new Map;function Vn(e){return new K(e)}async function Hn(e){let t=H.resolve(e);for(let e of Array.from(Bn.keys()))e.startsWith(`${t}|`)&&Bn.delete(e);await V.rm(En(t),{force:!0}).catch(()=>{})}var K=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=H.resolve(e.rootDir??wn(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Wn(Ln((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?G(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Gn(e.categoryPath,t)).map(Un)}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:Kn(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})=>({...Un(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=Pn(n.skillDir,e.filePath),r=await tr(t,this.maxResourceBytes);return{...Un(n),status:n.status,content:r,path:ir(H.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:ir(H.relative(n.skillDir,t))}}let r=await tr(n.skillFile,this.maxSkillBytes);return{...Un(n),status:n.status,content:r,path:ir(H.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 qn(this.rootDir),i=Bn.get(n);if(!e&&i&&Qn(i.manifest,r))return i;let a=e?void 0:await Xn(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return Bn.set(n,e),e}let o=await In(this.rootDir),s=Ln(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return Bn.set(n,c),await Zn(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 sr({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:zn})}async loadEntry(e){try{let t=H.dirname(e),n=kn(H.basename(t)),r=ir(H.relative(this.rootDir,t)),i=G(H.posix.dirname(r)),a=An(i,n),o=H.join(t,`metadata.json`),s=await $n(o);if(s?.skillId&&jn(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&G(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=Mn(s?.status);return{skillId:a,name:n,description:nr(await er(e,zn)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:rr(s?.tags),relatedSkills:rr(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}: ${ar(t)}\n`);return}}};function Un(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Wn(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Gn(e,t){return t?e===t:!0}function Kn(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 qn(e){let t;try{t=await V.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await Yn(H.join(e,`categories.json`),`categories`,n),await Jn(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Jn(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=H.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await Yn(t,`skill`,n),await Yn(H.join(e,`metadata.json`),`metadata`,n),await Yn(H.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await V.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Jn(t,i,n)}}async function Yn(e,t,n){try{let r=await V.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 Xn(e,t,n){let r;try{r=await V.readFile(En(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)||!Qn(e.manifest,n)?void 0:e}catch{return}}async function Zn(e,t){if(!await or(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await V.writeFile(En(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function Qn(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 $n(e){try{let t=await V.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 er(e,t){let n=await V.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 tr(e,t){if((await V.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return V.readFile(e,`utf-8`)}function nr(e){let t=$e(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
5
+ `)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function rr(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function ir(e){return e.split(H.sep).join(`/`)}function ar(e){return e instanceof Error?e.message:String(e)}async function or(e){try{return await V.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function sr(e){return Xe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function cr(e){return e??`openai-completions`}function lr(e,t,n){let r={"Client-Code":`AIMax`,"X-Session-Id":e};return t&&(r[`X-Message-Id`]=t),n&&(r[`X-Channel`]=n),r}function ur(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}}const dr={apiFormat:`anthropic-messages`,createModel:fr,buildRequest:mr,normalizeResponse:hr};function fr(e,t,n,r){return{id:e.model,name:e.model,api:`anthropic-messages`,provider:`anthropic`,baseUrl:pr(e.baseUrl),reasoning:!1,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:lr(t,n,r)}}function pr(e){return e.replace(/\/+$/,``).replace(/\/v1$/,``)}function mr(e,t,n,r){let i=e.baseUrl.replace(/\/+$/,``),a=[],o=[];for(let e of n){if(e.role===`system`){e.content.trim()&&o.push(e.content);continue}a.push({role:e.role,content:e.content})}let s={model:t,messages:a.length>0?a:[{role:`user`,content:``}],max_tokens:r.maxTokens??2048,stream:!1};return o.length>0&&(s.system=o.join(`
11
6
 
12
- `)),typeof r.temperature==`number`&&(s.temperature=r.temperature),{url:i.endsWith(`/v1`)?`${i}/messages`:`${i}/v1/messages`,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`,"Client-Code":`AIMax`},body:s}}function zr(e){let t=e,n=t.content?.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``)??``,r=(t.usage?.input_tokens??0)+(t.usage?.cache_read_input_tokens??0)+(t.usage?.cache_creation_input_tokens??0),i=t.usage?.output_tokens??0;return{text:n,usage:{input:r,output:i,total:r+i},raw:e}}const Br={apiFormat:`openai-completions`,createModel:Vr,buildRequest:Hr,normalizeResponse:Ur};function Vr(e,t,n,r){return{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:Nr(t,n,r),compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}function Hr(e,t,n,r){let i={model:t,messages:n,stream:!1};return typeof r.temperature==`number`&&(i.temperature=r.temperature),typeof r.maxTokens==`number`&&(i.max_tokens=r.maxTokens),{url:`${e.baseUrl.replace(/\/+$/,``)}/chat/completions`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:i}}function Ur(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:Pr(t.usage),raw:e}}const Wr={"openai-completions":Br,"anthropic-messages":Fr};function Gr(e){return Wr[e]}function Kr(e,t,n,r){return Gr(Mr(e.apiFormat)).createModel(e,t,n,r)}const qr=`/aimax/agents`,Jr=/^[a-z]+(?:-[a-z]+)*$/;function Yr(e){let t=[{dir:e.systemAgentsDir??qr,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 Xr(e){let t=new Map;for(let n of Yr(e)){let e=await ei(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function Zr(e={}){let t=e.allAgents??e.availableAgents??[],n=ii(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>ni(n,e),findAny:e=>ni(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function Qr(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 $r(e){return Qr(e.agentPolicy)?e.agentPolicy:Zr({allAgents:await Xr(e)})}async function ei(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=ti(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 ti(e,t){let n=qe(e),r=li(n.data.name)?.trim(),i=li(n.data.description)?.trim();if(!r||!Jr.test(r)||!i)return;let a=li(n.data.model)?.trim(),o=li(n.data.initPrompt)?.trim()??li(n.data.initialPrompt)?.trim(),s=ui(n.data.maxTurns),c=di(n.data.tools),l=di(n.data.disallowedTools),u=di(n.data.skills),d=fi(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 ni(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||ri(e)===`public`))}function ri(e){return e.visibility??`public`}function ii(e){return e.filter(e=>ri(e)===`public`)}function ai(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function oi(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(pi)):void 0,r=new Set((t.disallowedTools??[]).map(pi));return e.filter(e=>{let t=typeof e.name==`string`?pi(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function si(e){let t=ii(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(`
7
+ `)),typeof r.temperature==`number`&&(s.temperature=r.temperature),{url:i.endsWith(`/v1`)?`${i}/messages`:`${i}/v1/messages`,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`,"Client-Code":`AIMax`},body:s}}function hr(e){let t=e,n=t.content?.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``)??``,r=(t.usage?.input_tokens??0)+(t.usage?.cache_read_input_tokens??0)+(t.usage?.cache_creation_input_tokens??0),i=t.usage?.output_tokens??0;return{text:n,usage:{input:r,output:i,total:r+i},raw:e}}const gr={apiFormat:`openai-completions`,createModel:_r,buildRequest:vr,normalizeResponse:yr};function _r(e,t,n,r){return{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:lr(t,n,r),compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}function vr(e,t,n,r){let i={model:t,messages:n,stream:!1};return typeof r.temperature==`number`&&(i.temperature=r.temperature),typeof r.maxTokens==`number`&&(i.max_tokens=r.maxTokens),{url:`${e.baseUrl.replace(/\/+$/,``)}/chat/completions`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:i}}function yr(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:ur(t.usage),raw:e}}const br={"openai-completions":gr,"anthropic-messages":dr};function xr(e){return br[e]}function Sr(e,t,n,r){return xr(cr(e.apiFormat)).createModel(e,t,n,r)}const Cr=`/aimax/agents`,wr=/^[a-z]+(?:-[a-z]+)*$/;function Tr(e){let t=[{dir:e.systemAgentsDir??Cr,source:`system`},{dir:H.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:H.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function Er(e){let t=new Map;for(let n of Tr(e)){let e=await Ar(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function Dr(e={}){let t=e.allAgents??e.availableAgents??[],n=Pr(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Mr(n,e),findAny:e=>Mr(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function Or(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 kr(e){return Or(e.agentPolicy)?e.agentPolicy:Dr({allAgents:await Er(e)})}async function Ar(e,t){let n;try{n=await V.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=H.join(e,i.name),a=jr(await V.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function jr(e,t){let n=$e(e),r=zr(n.data.name)?.trim(),i=zr(n.data.description)?.trim();if(!r||!wr.test(r)||!i)return;let a=zr(n.data.model)?.trim(),o=zr(n.data.initPrompt)?.trim()??zr(n.data.initialPrompt)?.trim(),s=Br(n.data.maxTurns),c=Vr(n.data.tools),l=Vr(n.data.disallowedTools),u=Vr(n.data.skills),d=Hr(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 Mr(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Nr(e)===`public`))}function Nr(e){return e.visibility??`public`}function Pr(e){return e.filter(e=>Nr(e)===`public`)}function Fr(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Ir(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Ur)):void 0,r=new Set((t.disallowedTools??[]).map(Ur));return e.filter(e=>{let t=typeof e.name==`string`?Ur(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Lr(e){let t=Pr(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(`
13
8
  `),``].join(`
14
- `)}function ci(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function li(e){return typeof e==`string`?e:void 0}function ui(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function di(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 fi(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function pi(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 mi=new Qe;async function hi(e,t){return await mi.run(e,t)}function gi(e){return{async emit(t){let n=mi.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 _i=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 hi({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};function vi(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 yi(e=new Date){let t=vi(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let bi=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),xi=null;function Si(){return yi()}function Ci(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 wi(e){return G.join(e,`.aimax`)}function Ti(e){return{appLogPath:G.join(e,`app.log`),errorLogPath:G.join(e,`errors.log`)}}function Ei(e){let{appLogPath:t,errorLogPath:n}=Ti(e);$e.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 Di(e,t,n){return`[${Si()}] [${e}] ${t}${Ci(n)}`}function Oi(e,t,n){process.stderr.write(`${Di(e,t,n)}\n`)}function ki(e,t,n){if(!xi){Oi(e,t,n);return}let r=Di(e,t,n),i=$e.getLogger();if(e===bi.ERROR){i.error(r);return}if(e===bi.WARN){i.warn(r);return}i.info(r)}function Ai(e){let t=wi(e);xi?.dataDir!==e&&(K.mkdirSync(t,{recursive:!0}),Ei(t),xi={dataDir:e,logDir:t})}const Y={info:(e,t)=>ki(bi.INFO,e,t),warn:(e,t)=>ki(bi.WARN,e,t),error:(e,t)=>ki(bi.ERROR,e,t)};function ji(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))}...`}var Mi=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}:{}};try{await this.params.onProgress?.(n)}catch(n){Y.warn(`progress handler failed; event dropped`,{sessionId:e,eventType:t.type,error:n instanceof Error?n.message:String(n)})}}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}},X=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 Ni(e){return{async chat(t){let n=Fi(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await Li(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:Ii(n),historyMessages:n},e.hookCtx);let i=Gr(Mr(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=Ri(t.signal,t.timeoutMs);try{let t;try{t=await fetch(a.url,{method:`POST`,headers:a.headers,body:JSON.stringify(a.body),signal:o})}catch(e){throw Bi(e,c())}if(!t.ok){let e=await zi(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new X({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:Hi(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw Pi(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await Li(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:l?[l]:[],durationMs:d,usage:u},e.hookCtx),{text:l,usage:u,raw:s}}finally{s()}}}}function Pi(e,t){return Vi(e)&&t?new X({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):Vi(e)?new X({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new X({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function Fi(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 Ii(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
15
- `)}async function Li(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function Ri(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 zi(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function Bi(e,t){return e instanceof X?e:Vi(e)?t?new X({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new X({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function Vi(e){return e instanceof Error&&e.name===`AbortError`}function Hi(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 Wi(e){return!!(e instanceof Ui||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var Gi=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 Ki(e){return!!(e instanceof Gi||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const qi=new Qe;function Ji(){return{}}async function Yi(e,t){return await qi.run(e,t)}function Xi(e){let t=qi.getStore();!t||t.signal||(t.signal=e)}const Zi=new Qe;function Qi(){return{}}async function $i(e,t){return await Zi.run(e,t)}function ea(e){let t=Zi.getStore();!t||t.signal||(t.signal=e)}function ta(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function na(e){if(!ta(e))return null;let t=e,n=ra(t.message),r=aa(n?.code)??aa(t.code),i=aa(n?.type)??aa(t.type),a=aa(n?.message)??ia(t.error)??aa(t.message)??`Unknown upstream error`;return{message:oa(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:sa(r,i),raw:e}}function ra(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 ia(e){if(!(!e||typeof e!=`object`))return aa(e.message)}function aa(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function oa(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function sa(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 ca=(e,t,n)=>{let r=new ct;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=da(e,t,n?.apiKey||nt(e.provider)||``,n?.headers),o=fa(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=rt(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=na(t);if(n)throw new X({message: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}},tt(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=va(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=rt(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 X&&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},la=(e,t,n)=>{let r=n?.apiKey||nt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=ft(e,n,r),a=st(e)?n?.reasoning:pt(n?.reasoning);return ca(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function ua(e,t,n){return fa(e,t,n)}function da(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=dt(t.messages);Object.assign(i,ut({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new et({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function fa(e,t,n){let r=ba(e),i=ga(e,t,r);ha(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=_a(t.tools,r):pa(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 pa(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 ma(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 ha(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 ga(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return ma(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=mt(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:lt(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:lt(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:lt(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=>lt(e.text)).join(``):a.map(e=>({type:`text`,text:lt(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(`
9
+ `)}function Rr(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function zr(e){return typeof e==`string`?e:void 0}function Br(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Vr(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 Hr(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Ur(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 Wr=new tt;async function Gr(e,t){return await Wr.run(e,t)}function Kr(e){return{async emit(t){let n=Wr.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 qr=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 Gr({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};function Jr(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 Yr(e=new Date){let t=Jr(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let Xr=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Zr=null;function Qr(){return Yr()}function $r(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 ei(e){return H.join(e,`.aimax`)}function ti(e){return{appLogPath:H.join(e,`app.log`),errorLogPath:H.join(e,`errors.log`)}}function ni(e){let{appLogPath:t,errorLogPath:n}=ti(e);nt.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 ri(e,t,n){return`[${Qr()}] [${e}] ${t}${$r(n)}`}function ii(e,t,n){process.stderr.write(`${ri(e,t,n)}\n`)}function ai(e,t,n){if(!Zr){ii(e,t,n);return}let r=ri(e,t,n),i=nt.getLogger();if(e===Xr.ERROR){i.error(r);return}if(e===Xr.WARN){i.warn(r);return}i.info(r)}function oi(e){let t=ei(e);Zr?.dataDir!==e&&(U.mkdirSync(t,{recursive:!0}),ni(t),Zr={dataDir:e,logDir:t})}const q={info:(e,t)=>ai(Xr.INFO,e,t),warn:(e,t)=>ai(Xr.WARN,e,t),error:(e,t)=>ai(Xr.ERROR,e,t)};function si(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))}...`}var ci=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}:{}};try{await this.params.onProgress?.(n)}catch(n){q.warn(`progress handler failed; event dropped`,{sessionId:e,eventType:t.type,error:n instanceof Error?n.message:String(n)})}}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}},J=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 li(e){return{async chat(t){let n=di(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await pi(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:fi(n),historyMessages:n},e.hookCtx);let i=xr(cr(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=mi(t.signal,t.timeoutMs);try{let t;try{t=await fetch(a.url,{method:`POST`,headers:a.headers,body:JSON.stringify(a.body),signal:o})}catch(e){throw gi(e,c())}if(!t.ok){let e=await hi(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new J({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:vi(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw ui(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await pi(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:l?[l]:[],durationMs:d,usage:u},e.hookCtx),{text:l,usage:u,raw:s}}finally{s()}}}}function ui(e,t){return _i(e)&&t?new J({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):_i(e)?new J({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new J({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function di(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 fi(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
10
+ `)}async function pi(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function mi(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 hi(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function gi(e,t){return e instanceof J?e:_i(e)?t?new J({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new J({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function _i(e){return e instanceof Error&&e.name===`AbortError`}function vi(e){return e===408||e===409||e===425||e===429||e>=500}var yi=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 bi(e){return!!(e instanceof yi||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var xi=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 Si(e){return!!(e instanceof xi||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Ci=new tt;function wi(){return{}}async function Ti(e,t){return await Ci.run(e,t)}function Ei(e){let t=Ci.getStore();!t||t.signal||(t.signal=e)}const Di=new tt;function Oi(){return{}}async function ki(e,t){return await Di.run(e,t)}function Ai(e){let t=Di.getStore();!t||t.signal||(t.signal=e)}function ji(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Mi(e){if(!ji(e))return null;let t=e,n=Ni(t.message),r=Fi(n?.code)??Fi(t.code),i=Fi(n?.type)??Fi(t.type),a=Fi(n?.message)??Pi(t.error)??Fi(t.message)??`Unknown upstream error`;return{message:Ii(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Li(r,i),raw:e}}function Ni(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 Pi(e){if(!(!e||typeof e!=`object`))return Fi(e.message)}function Fi(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Ii(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Li(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 Ri=(e,t,n)=>{let r=new dt;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=Vi(e,t,n?.apiKey||at(e.provider)||``,n?.headers),o=Hi(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=ot(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=Mi(t);if(n)throw new J({message: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}},it(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=Ji(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=ot(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 J&&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},zi=(e,t,n)=>{let r=n?.apiKey||at(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=ht(e,n,r),a=ut(e)?n?.reasoning:gt(n?.reasoning);return Ri(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function Bi(e,t,n){return Hi(e,t,n)}function Vi(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=mt(t.messages);Object.assign(i,pt({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new rt({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Hi(e,t,n){let r=Xi(e),i=Ki(e,t,r);Gi(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=qi(t.tools,r):Ui(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 Ui(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 Wi(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 Gi(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 Ki(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Wi(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=_t(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:ft(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:ft(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:ft(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=>ft(e.text)).join(``):a.map(e=>({type:`text`,text:ft(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(`
16
11
 
17
12
  `);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(`
18
13
  `))}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(`
19
- `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:lt(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 _a(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function va(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 ya(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 ba(e){let t=ya(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 xa=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Sa=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),Ca=[`llmrequesterror`];function wa(e){let t=Oa(e?.maxAttempts,3),n=ka(e?.initialDelayMs,250),r=ka(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Ta(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Ea(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 Da(e){if(Ma(e))return!1;let t=Aa(e),n=ja(e);if(t?.statusCode!==void 0)return Pa(t.statusCode);if(t?.providerCode!==void 0)return Na(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(xa.has(e))return!0;if(Sa.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=t?.message??n,i=Fa(r);if(i!==void 0)return Pa(i);let a=Ia(r);return a===void 0?La(r)?!0:t?.retryable===!0:a}function Oa(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function ka(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Aa(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 ja(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 Ma(e){return Aa(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function Na(e){return/^\d+$/.test(e)?Pa(Number(e)):!1}function Pa(e){return e===408||e===409||e===425||e===429||e>=500}function Fa(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function Ia(e){if(!e)return;let t=Ra(e);for(let e of Sa)if(t.includes(e))return!1;for(let e of xa)if(t.includes(e))return!0}function La(e){if(!e)return!1;let t=Ra(e);return Ca.some(e=>t.includes(e))}function Ra(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const za=[`请求上下文过大`,`context_length_exceeded`,`context length exceeded`,`maximum context length`,`context window`,`reduce the length of the messages`,`prompt is too long`,`too many tokens`,`context limit`,`token limit`,`input too long`,`request too large`,`上下文`,`token`,`超限`],Ba=[/exceed.*context/i,/超出.*长度/],Va=[`authentication`,`invalid_api_key`,`permission`,`model_not_found`,`content_policy`,`safety`,`moderation`],Ha=[`Emergency compaction after a context-limit error.`,`Preserve: active thread goal requirements, acceptance criteria, file paths, test commands, and unfinished work.`,`Preserve skill names/paths that were loaded.`,`Drop redundant tool output and stale exploration.`].join(` `);var Ua=class{runRecoveriesUsedCount=0;turnRecoveryUsed=!1;turnRecoverySucceeded=!1;resetTurnSlot(){this.turnRecoveryUsed=!1}canAttemptRecovery(){return this.runRecoveriesUsedCount<2&&!this.turnRecoveryUsed}beginTurnRecovery(){return this.canAttemptRecovery()?(this.turnRecoveryUsed=!0,this.runRecoveriesUsedCount+=1,!0):!1}markTurnRecoverySucceeded(){this.turnRecoverySucceeded=!0}wasTurnRecoverySucceeded(){return this.turnRecoverySucceeded}get runRecoveriesUsed(){return this.runRecoveriesUsedCount}};function Wa(e){let t=[],n=e=>{if(typeof e!=`string`)return;let n=e.trim();n&&(t.push(n),Ga(n,t))};if(e instanceof X)n(e.providerMessage),n(e.message);else if(e instanceof Error)n(e.message);else if(typeof e==`string`)n(e);else if(e&&typeof e==`object`){let t=e;n(t.providerMessage),n(t.message)}return t.join(`
20
- `)}function Ga(e,t){let n=e.trim();if(!(!n.startsWith(`{`)||!n.endsWith(`}`)))try{let e=JSON.parse(n);typeof e.message==`string`&&e.message.trim()&&t.push(e.message.trim())}catch{}}function Ka(e){let t=e.toLowerCase();return Va.some(e=>t.includes(e.toLowerCase()))&&!za.some(e=>t.includes(e.toLowerCase()))?!1:za.some(e=>t.includes(e.toLowerCase()))?!0:Ba.some(t=>t.test(e))}function qa(e){if(e instanceof X&&e.statusCode!==void 0)return e.statusCode;if(e&&typeof e==`object`){let t=e.statusCode;if(typeof t==`number`&&Number.isFinite(t))return t;let n=e.code;if(typeof n==`number`&&n===400||typeof n==`string`&&n===`400`)return 400}return Fa(Wa(e))}function Ja(e){if(e&&typeof e==`object`){let t=e,n=Wa(e);if(t.retryable===!1&&!Ka(n))return!1}let t=Wa(e),n=qa(e);return t.includes(`请求上下文过大`)?n===void 0||n===400:n===400?Ka(t):!1}function Ya(e,t){return t?[`LLM context limit exceeded (HTTP 400). Emergency compaction was attempted but the request still failed.`,`Try /compact, reduce tool output size, or start a new session.`,`Original: ${e}`].join(` `):e}async function Xa(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,contextLimitRecovery:f,onTurnRecordProduced:p}=e;f?.budget.resetTurnSlot();let m=``,h=``,g=``,_=0,v=0,y,b,x=0,S=0,C=[],w=new Map,T=new Map,E=new Set,D=Ji(),O=Qi(),k=new Set,ee=Promise.resolve(),A,j=!1,M=!1,te=e=>{k.add(e),e.catch(e=>{A??=e}).finally(()=>{k.delete(e)})},ne=async()=>{for(;k.size>0;)await Promise.allSettled([...k]);if(A)throw A},N=t.subscribe(e=>{let t=ee.then(()=>P(e));ee=t.catch(()=>{}),te(t)});async function P(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(S===0&&(t.type===`text_delta`||t.type===`done`)&&(S=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=yo(`partial`in t?t.partial:void 0)??yo(`message`in t?t.message:void 0)??yo(`message`in e?e.message:void 0),a=bo(t.delta,r,h);r?(h=r,g=r):a&&(g+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){m=``,h=``,g=``,e.usage&&(_=e.usage.input,v=e.usage.output);return}m=go(e);let r=bo(``,m,g||h);h=m,g=m,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(_=e.usage.input,v=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(_=t.usage.input,v=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=go(e);!m&&n&&(m=n),await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:t.usage?{input:_,output:v,total:_+v}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(b=io(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:mo(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 T.values())!o.has(e.toolCallId)&&a.has(e.toolCallId)&&r.push(e);for(let e of r)T.delete(e.toolCallId);if(C.push({message:t,toolResults:r}),p&&!n){let e=!!D.signal,n=!!O.signal;if(e&&D.signal.transparentPause||await p(fo(uo(t),e||n),n?[]:r.map(po)),e||n)return}return}if(e.type===`tool_execution_start`){g=``,w.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=vo(e.result),r=_o(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:mo(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.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 F=wa(d),I=F.enabled?F.maxAttempts:1;f&&(I=Math.max(I,2));try{Za({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=I;e++){let d=C.length;b=void 0,y=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`);Y.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,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}),x=Date.now(),await Yi(D,async()=>{await $i(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await ne();let f=D.signal;if(f)throw f;let p=O.signal;if(p)throw p;let h=C.some(e=>e.message.content.some(e=>e.type===`toolCall`||e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0));!b&&C.length>0&&!h&&m.trim().length===0&&(Y.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,turnRecordCount:C.length}),b={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let g=typeof t.state.error==`string`?t.state.error:void 0,S=b??g;if(S){if(y=xo(S),Y.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,error:y}),await re(S,y,e,d)||await R(S,d))continue;await z(Ya(y,j),S),await s.dispatchProgress(i,{type:`error`,message:Ya(y,j)})}y||Y.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await ne(),Wi(t)||Ki(t))throw t;if(y=xo(t),Y.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,error:y}),await re(t,y,e,d)||await R(t,d))continue;await z(Ya(y,j),t),await s.dispatchProgress(i,{type:`error`,message:Ya(y,j)});break}}}finally{N()}function L(){m=``,h=``,g=``}async function re(e,n,r,a){if(!eo({error:e,attempt:r,maxAttempts:I,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g}))return!1;let o=Ta(r,F);return Y.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:I,delayMs:o,error:n}),await so({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:I,message:n,delayMs:o}),C.length=a,L(),co(t),await Ea(o,u),!0}async function R(e,n){if(!f||u?.aborted||!Ja(e)||!f.budget.beginTurnRecovery())return!1;j=!0,await f.onPhase(`context_limit_recovery_started`,{turnKind:f.turnKind,runRecoveriesUsed:f.budget.runRecoveriesUsed});let r=await f.reloadHistory();if(r.status!==`compacted`)return await f.onPhase(`context_limit_recovery_skipped`,{turnKind:f.turnKind,reason:r.status===`skipped`?r.reason:`reload_failed`}),!1;await f.onPhase(`context_limit_recovery_ready`,{turnKind:f.turnKind}),C.length=n,L(),co(t);let i=t.state;return typeof i.error==`string`&&(i.error=void 0),y=void 0,b=void 0,!0}async function z(e,t){p&&await p(no(e,t),[])}let B=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:B,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let V=(O.signal?``:C.length>0?go(C[C.length-1].message):``)||m||ro(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;return p&&!to(C)&&!y&&m.trim().length>0&&await p({role:`assistant`,content:m,timestamp:new Date().toISOString()},[]),!y&&j?(await f?.onPhase(`context_limit_recovery_succeeded`,{turnKind:f.turnKind}),f.budget.markTurnRecoverySucceeded(),M=!0):y&&j&&await f?.onPhase(`context_limit_recovery_failed`,{turnKind:f.turnKind,error:y}),{text:V,inputTokens:_,outputTokens:v,error:y?Ya(y,j):void 0,turnRecords:C,contextLimitRecoverySucceeded:M}}function Za(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:Qa(i,e.message),o=$a(t?.tools);try{let t=ua(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 Qa(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function $a(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 eo(e){return e.attempt>=e.maxAttempts||!Da(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&&go(e.message).trim().length===0)}function to(e){return e.some(e=>uo(e.message)!==null||e.toolResults.length>0)}function no(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 ro(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 io(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:ao(t.errorCode),statusCode:oo(t.statusCode),providerCode:ao(t.providerCode),providerType:ao(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function ao(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function oo(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function so(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 co(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&lo(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function lo(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function uo(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 fo(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function po(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 mo(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:ho(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function ho(e){let t=e.indexOf(`
14
+ `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:ft(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 qi(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function Ji(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 Yi(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 Xi(e){let t=Yi(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 Zi=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Qi=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),$i=[`llmrequesterror`];function ea(e){let t=ia(e?.maxAttempts,3),n=aa(e?.initialDelayMs,250),r=aa(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function ta(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function na(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 ra(e){if(ca(e))return!1;let t=oa(e),n=sa(e);if(t?.statusCode!==void 0)return ua(t.statusCode);if(t?.providerCode!==void 0)return la(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Zi.has(e))return!0;if(Qi.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=t?.message??n,i=da(r);if(i!==void 0)return ua(i);let a=fa(r);return a===void 0?pa(r)?!0:t?.retryable===!0:a}function ia(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function aa(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function oa(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 sa(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 ca(e){return oa(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function la(e){return/^\d+$/.test(e)?ua(Number(e)):!1}function ua(e){return e===408||e===409||e===425||e===429||e>=500}function da(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function fa(e){if(!e)return;let t=ma(e);for(let e of Qi)if(t.includes(e))return!1;for(let e of Zi)if(t.includes(e))return!0}function pa(e){if(!e)return!1;let t=ma(e);return $i.some(e=>t.includes(e))}function ma(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const ha=[`请求上下文过大`,`context_length_exceeded`,`context length exceeded`,`maximum context length`,`context window`,`reduce the length of the messages`,`prompt is too long`,`too many tokens`,`context limit`,`token limit`,`input too long`,`request too large`,`上下文`,`token`,`超限`],ga=[/exceed.*context/i,/超出.*长度/],_a=[`authentication`,`invalid_api_key`,`permission`,`model_not_found`,`content_policy`,`safety`,`moderation`],va=[`Emergency compaction after a context-limit error.`,`Preserve: active thread goal requirements, acceptance criteria, file paths, test commands, and unfinished work.`,`Preserve skill names/paths that were loaded.`,`Drop redundant tool output and stale exploration.`].join(` `);var ya=class{runRecoveriesUsedCount=0;turnRecoveryUsed=!1;turnRecoverySucceeded=!1;resetTurnSlot(){this.turnRecoveryUsed=!1}canAttemptRecovery(){return this.runRecoveriesUsedCount<2&&!this.turnRecoveryUsed}beginTurnRecovery(){return this.canAttemptRecovery()?(this.turnRecoveryUsed=!0,this.runRecoveriesUsedCount+=1,!0):!1}markTurnRecoverySucceeded(){this.turnRecoverySucceeded=!0}wasTurnRecoverySucceeded(){return this.turnRecoverySucceeded}get runRecoveriesUsed(){return this.runRecoveriesUsedCount}};function ba(e){let t=[],n=e=>{if(typeof e!=`string`)return;let n=e.trim();n&&(t.push(n),xa(n,t))};if(e instanceof J)n(e.providerMessage),n(e.message);else if(e instanceof Error)n(e.message);else if(typeof e==`string`)n(e);else if(e&&typeof e==`object`){let t=e;n(t.providerMessage),n(t.message)}return t.join(`
15
+ `)}function xa(e,t){let n=e.trim();if(!(!n.startsWith(`{`)||!n.endsWith(`}`)))try{let e=JSON.parse(n);typeof e.message==`string`&&e.message.trim()&&t.push(e.message.trim())}catch{}}function Sa(e){let t=e.toLowerCase();return _a.some(e=>t.includes(e.toLowerCase()))&&!ha.some(e=>t.includes(e.toLowerCase()))?!1:ha.some(e=>t.includes(e.toLowerCase()))?!0:ga.some(t=>t.test(e))}function Ca(e){if(e instanceof J&&e.statusCode!==void 0)return e.statusCode;if(e&&typeof e==`object`){let t=e.statusCode;if(typeof t==`number`&&Number.isFinite(t))return t;let n=e.code;if(typeof n==`number`&&n===400||typeof n==`string`&&n===`400`)return 400}return da(ba(e))}function wa(e){if(e&&typeof e==`object`){let t=e,n=ba(e);if(t.retryable===!1&&!Sa(n))return!1}let t=ba(e),n=Ca(e);return t.includes(`请求上下文过大`)?n===void 0||n===400:n===400?Sa(t):!1}function Ta(e,t){return t?[`LLM context limit exceeded (HTTP 400). Emergency compaction was attempted but the request still failed.`,`Try /compact, reduce tool output size, or start a new session.`,`Original: ${e}`].join(` `):e}async function Ea(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,contextLimitRecovery:f,onTurnRecordProduced:p}=e;f?.budget.resetTurnSlot();let m=``,h=``,g=``,_=0,v=0,y,b,x=0,S=0,C=[],w=new Map,T=new Map,E=new Set,D=wi(),O=Oi(),k=new Set,A=Promise.resolve(),j,M=!1,N=!1,ee=e=>{k.add(e),e.catch(e=>{j??=e}).finally(()=>{k.delete(e)})},P=async()=>{for(;k.size>0;)await Promise.allSettled([...k]);if(j)throw j},F=t.subscribe(e=>{let t=A.then(()=>te(e));A=t.catch(()=>{}),ee(t)});async function te(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(S===0&&(t.type===`text_delta`||t.type===`done`)&&(S=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=Ja(`partial`in t?t.partial:void 0)??Ja(`message`in t?t.message:void 0)??Ja(`message`in e?e.message:void 0),a=Ya(t.delta,r,h);r?(h=r,g=r):a&&(g+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){m=``,h=``,g=``,e.usage&&(_=e.usage.input,v=e.usage.output);return}m=Ga(e);let r=Ya(``,m,g||h);h=m,g=m,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(_=e.usage.input,v=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(_=t.usage.input,v=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ga(e);!m&&n&&(m=n),await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:t.usage?{input:_,output:v,total:_+v}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(b=Pa(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:Ua(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 T.values())!o.has(e.toolCallId)&&a.has(e.toolCallId)&&r.push(e);for(let e of r)T.delete(e.toolCallId);if(C.push({message:t,toolResults:r}),p&&!n){let e=!!D.signal,n=!!O.signal;if(e&&D.signal.transparentPause||await p(Va(Ba(t),e||n),n?[]:r.map(Ha)),e||n)return}return}if(e.type===`tool_execution_start`){g=``,w.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=qa(e.result),r=Ka(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Ua(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.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=ea(d),I=ne.enabled?ne.maxAttempts:1;f&&(I=Math.max(I,2));try{Da({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=I;e++){let d=C.length;b=void 0,y=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`);q.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,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}),x=Date.now(),await Ti(D,async()=>{await ki(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await P();let f=D.signal;if(f)throw f;let p=O.signal;if(p)throw p;let h=C.some(e=>e.message.content.some(e=>e.type===`toolCall`||e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0));!b&&C.length>0&&!h&&m.trim().length===0&&(q.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,turnRecordCount:C.length}),b={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let g=typeof t.state.error==`string`?t.state.error:void 0,S=b??g;if(S){if(y=Xa(S),q.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,error:y}),await R(S,y,e,d)||await z(S,d))continue;await re(Ta(y,M),S),await s.dispatchProgress(i,{type:`error`,message:Ta(y,M)})}y||q.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await P(),bi(t)||Si(t))throw t;if(y=Xa(t),q.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,error:y}),await R(t,y,e,d)||await z(t,d))continue;await re(Ta(y,M),t),await s.dispatchProgress(i,{type:`error`,message:Ta(y,M)});break}}}finally{F()}function L(){m=``,h=``,g=``}async function R(e,n,r,a){if(!Aa({error:e,attempt:r,maxAttempts:I,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g}))return!1;let o=ta(r,ne);return q.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:I,delayMs:o,error:n}),await La({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:I,message:n,delayMs:o}),C.length=a,L(),Ra(t),await na(o,u),!0}async function z(e,n){if(!f||u?.aborted||!wa(e)||!f.budget.beginTurnRecovery())return!1;M=!0,await f.onPhase(`context_limit_recovery_started`,{turnKind:f.turnKind,runRecoveriesUsed:f.budget.runRecoveriesUsed});let r=await f.reloadHistory();if(r.status!==`compacted`)return await f.onPhase(`context_limit_recovery_skipped`,{turnKind:f.turnKind,reason:r.status===`skipped`?r.reason:`reload_failed`}),!1;await f.onPhase(`context_limit_recovery_ready`,{turnKind:f.turnKind}),C.length=n,L(),Ra(t);let i=t.state;return typeof i.error==`string`&&(i.error=void 0),y=void 0,b=void 0,!0}async function re(e,t){p&&await p(Ma(e,t),[])}let B=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:B,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let ie=(O.signal?``:C.length>0?Ga(C[C.length-1].message):``)||m||Na(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;return p&&!ja(C)&&!y&&m.trim().length>0&&await p({role:`assistant`,content:m,timestamp:new Date().toISOString()},[]),!y&&M?(await f?.onPhase(`context_limit_recovery_succeeded`,{turnKind:f.turnKind}),f.budget.markTurnRecoverySucceeded(),N=!0):y&&M&&await f?.onPhase(`context_limit_recovery_failed`,{turnKind:f.turnKind,error:y}),{text:ie,inputTokens:_,outputTokens:v,error:y?Ta(y,M):void 0,turnRecords:C,contextLimitRecoverySucceeded:N}}function Da(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:Oa(i,e.message),o=ka(t?.tools);try{let t=Bi(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 Oa(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function ka(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 Aa(e){return e.attempt>=e.maxAttempts||!ra(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&&Ga(e.message).trim().length===0)}function ja(e){return e.some(e=>Ba(e.message)!==null||e.toolResults.length>0)}function Ma(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 Na(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 Pa(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:Fa(t.errorCode),statusCode:Ia(t.statusCode),providerCode:Fa(t.providerCode),providerType:Fa(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function Fa(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Ia(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function La(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 Ra(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&za(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function za(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function Ba(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function Va(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Ha(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function Ua(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:Wa(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Wa(e){let t=e.indexOf(`
21
16
  Preview:
22
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function go(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function _o(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return vo(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):vo(e)}function vo(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function yo(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 bo(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function xo(e){let t=So(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 So(e){if(e instanceof X)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:ao(t.code),statusCode:oo(t.statusCode),statusText:ao(t.statusText),providerMessage:ao(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 Co(e){let t=ko(e.toolResultPreviewChars),n=Ao(e.systemPrompt,e.agentDefinition),r=Mo(e.model,e.agentDefinition),i=oi(e.tools??[],e.agentDefinition),a=jo(e.message,e.agentDefinition),o=await Xa({agent:new Ze({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:wo({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new _i,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:Eo(o.turnRecords),toolResults:Do(o.turnRecords,t)}}function wo(e){let t=e.phasePrefix??`silent_agent`;return new Mi({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await To(e.diagnosticDispatcher,t,n)}})}async function To(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 Eo(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 Do(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Oo(e.content,t)})))}function Oo(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function ko(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 Ao(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
17
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Ga(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Ka(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return qa(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):qa(e)}function qa(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function Ja(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 Ya(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Xa(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 J)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:Fa(t.code),statusCode:Ia(t.statusCode),statusText:Fa(t.statusText),providerMessage:Fa(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 Qa(e){let t=io(e.toolResultPreviewChars),n=ao(e.systemPrompt,e.agentDefinition),r=so(e.model,e.agentDefinition),i=Ir(e.tools??[],e.agentDefinition),a=oo(e.message,e.agentDefinition),o=await Ea({agent:new et({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:$a({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new qr,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:to(o.turnRecords),toolResults:no(o.turnRecords,t)}}function $a(e){let t=e.phasePrefix??`silent_agent`;return new ci({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await eo(e.diagnosticDispatcher,t,n)}})}async function eo(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 to(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 no(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:ro(e.content,t)})))}function ro(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function io(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 ao(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
23
18
 
24
- `)}function jo(e,t){return!t?.initPrompt||typeof e!=`string`?e:ci(t,e)}function Mo(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}var No=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=G.resolve(e.rootDir??qn(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=J(e.path),n=zo(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 dr(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:Jn(this.rootDir)}}async createSkill(e){let t=Qn(e.name),n=J(e.categoryPath),r=zo(e.description,`auto-skill description`),i=Bo(e.body);await this.assertCategoryExists(n);let a=$n(n,t),o=nr(this.rootDir,n,t);if(await Lo(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:Vo(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:Ho(e.evidence,s)};return await W.mkdir(o,{recursive:!0}),await W.writeFile(c,Po(t,r,i),`utf-8`),await Ro(l,u),await dr(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=er(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=nr(this.rootDir,t.categoryPath,t.skillName),r=G.join(n,`SKILL.md`),i=G.join(n,`metadata.json`),a=await Fo(r),o=await Io(i),s=e.description===void 0?a.description:zo(e.description,`auto-skill description`),c=e.body===void 0?a.body:Bo(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?Vo(o.tags):Vo(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:{},...Ho(e.evidence,l)}};return await W.writeFile(r,Po(t.skillName,s,c),`utf-8`),await Ro(i,u),await dr(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=er(e.skillId),n=nr(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 Io(r),o=this.now().toISOString();return await Ro(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...Ho(e.evidence,o)}}),await dr(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=Jn(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 Ro(Jn(this.rootDir),t)}};function Po(e,t,n){return[`---`,`name: ${Uo(e)}`,`description: ${Uo(t)}`,`---`,``,n.trim(),``].join(`
25
- `)}async function Fo(e){let t=qe(await W.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Io(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 Lo(e){try{return await W.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Ro(e,t){await W.mkdir(G.dirname(e),{recursive:!0}),await W.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function zo(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function Bo(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 Vo(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Ho(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Uo(e){return JSON.stringify(e)}const Wo=[`create`,`update`,`archive`,`create_category`],Go=q.Object({}),Ko=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.`}))}),qo=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.`}))}),Jo=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.`}))}),Yo=q.Object({action:q.Union(Wo.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 Xo(e){let t=new fr({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:Go,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:ns(e)})}}}}function Zo(e){let t=new fr({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:Ko,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:ns(e)})}}}}function Qo(e){let t=new fr({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:qo,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:ns(e)})}}}}function $o(e){let t=new fr({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:Jo,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:ns(e)})}}}}function es(e){let t=new No({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:Yo,async execute(e,n){try{return Z(await ts(t,n))}catch(e){return Z({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:ns(e)})}}}}async function ts(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 ns(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const rs=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 is(e){let t=Dn({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??Sn}),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:rs,async execute(r,i){try{return i.kind===`tool_result`?os(await En({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?os(await Cn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?os(await wn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?os({...await Tn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):os(await Tn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:as(i),limits:t}))}catch(r){return os({kind:i.kind,error:ss(r),limits:t,contextFiles:kn(e.dataDir,e.sessionId,n)})}}}}function as(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 os(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function ss(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function cs(e){let t=[Zo(e.dataDir),Qo(e.dataDir),$o(e.dataDir),is({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(es(e.dataDir)),t}const ls=`auto-skill-reviewer`;async function us(e){let t=e.createModel??Kr,n=e.tools??cs({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 Co({sessionId:e.sessionId,systemPrompt:ds(e.mode),message:fs(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=ps(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 ds(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(`
26
- `)}function fs(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(`
27
- `)}function ps(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=ms(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 ms(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const hs=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],gs=hs,_s={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}},vs=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function ys(e){let t=xs(e.gates),n={session:Cs(`session`,e.sessionTranscript,t.session),currentRun:Cs(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:Cs(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Ds(e.reviewState?.reviewCount,0),i=Ds(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return ks(n,a,r,i,o,`run_error`);if(e.result?.paused)return ks(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return ks(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return ks(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 bs(e,t={}){let n=fn(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??hs),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(As(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}js(t)&&Ms(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 xs(e){return{session:Ss(e?e.session:_s.session),currentRun:Ss(e?e.currentRun:_s.currentRun),reviewWindow:Ss(e?e.reviewWindow:_s.reviewWindow)}}function Ss(e){let t={};for(let n of vs){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?gs:void 0;if(typeof r==`number`){let e=Es(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Es(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:Os(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:Os(r.toolNames,i)})}return t}function Cs(e,t,n){let r=bs(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=vs.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];ws(t,o,r)?i.push({code:t,description:Ts(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 ws(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 Ts(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 Es(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Ds(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Os(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function ks(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 As(e){return e.role===`assistant`}function js(e){return e.role===`tool_result`}function Ms(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:Ns(e.content)?.success===!1}function Ns(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function Ps(e){let t=mn(e.transcript.length,e.transcriptStartIndex),n=hn(e.transcript.length,e.recentEntryLimit),r=mn(e.transcript.length,e.reviewWindowStartIndex??void 0),i=mn(e.transcript.length,0),a=gn(e.transcript,t),o=gn(e.transcript,r),s=bs(e.transcript),c=bs(a),l=bs(o),u=dn(e.transcript),d=dn(a),f=dn(o),p=a.filter(Is),m=a.filter(Ls);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:Fs(p[0]?.content??``,800),finalResponse:Fs(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:pn(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 Fs(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Is(e){return e.role===`user`}function Ls(e){return e.role===`assistant`}function Rs(e,t,n){return G.join(d(e,t,n),`auto-skill-review-state.json`)}function zs(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function Bs(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 zs(t);throw e}return Gs(JSON.parse(i),t)}async function Vs(e,t,n){let r=Rs(e,t.sessionId,n);await W.mkdir(G.dirname(r),{recursive:!0}),await W.writeFile(r,`${JSON.stringify(Gs(t,t.sessionId),null,2)}\n`,`utf-8`)}async function Hs(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await Vs(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Us(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 Vs(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Ws(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await Vs(e.dataDir,t,{storeName:e.sessionStoreName}),t}function Gs(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:Js(n.reviewCount,0),lastAttemptedReviewAt:Ks(n.lastAttemptedReviewAt),lastCompletedReviewAt:Ks(n.lastCompletedReviewAt),lastFailedReviewAt:Ks(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:qs(n.lastReviewedTranscriptEndIndex)}}function Ks(e){return typeof e==`string`&&e.trim()?e:null}function qs(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function Js(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function Ys(e){return G.join(qn(e),`.reviews`,`run-log.jsonl`)}async function Xs(e,t){let n=Ys(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 Zs=`write`,Qs=new Set([`off`,`gate`,`dry_run`,`write`]);async function $s(e){let t=ec(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=nc(e);if(n){await oc(e,t,n);return}let r,i;try{let n=await m(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=rc(n,e.transcriptStartIndex),o=await Bs(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=ic(o.lastReviewedTranscriptEndIndex,n.length),c=rc(n,s);await sc(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=ys({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await sc(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 cc(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await sc(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new fr({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=Ps({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:kn(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await sc(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await cc(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(ls);if(!p){Y.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:ls}),await oc(e,t,`reviewer_agent_missing`,{reviewerAgentName:ls});return}i={mode:f,decision:l,packet:d},r=await Hs({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??us,g=cs({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 Ws({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await lc(e.runParams.dataDir,i,{status:`failed`,curatorResult:_,error:_.error,reviewState:r});await ac(e,_.error,{mode:t.mode,usage:_.usage,toolCalls:uc(_.toolCalls),toolResults:_c(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewRunLogPath:n});return}r=await Us({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let v=await lc(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:gc(_.text,2e3),toolCalls:uc(_.toolCalls),toolResults:_c(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewState:r,reviewRunLogPath:v}})}catch(t){let n=t instanceof Error?t.message:String(t),a;r&&(r=await Ws({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await lc(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await ac(e,n,a?{reviewRunLogPath:a}:void 0)}}function ec(e){return{mode:tc(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function tc(e){if(e==null)return Zs;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?Qs.has(t)?t:`off`:Zs}function nc(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 rc(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function ic(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function ac(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 oc(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 sc(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function cc(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:hc(n),...i.packet?{packet:i.packet}:{}}})}async function lc(e,t,n){return Xs(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?fc(n.curatorResult.text):void 0,conclusionText:n.curatorResult?pc(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?uc(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?_c(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 uc(e){return e.map(e=>({...e,arguments:dc(e.name,e.arguments)}))}function dc(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 fc(e){let t=mc(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function pc(e){return fc(e)?void 0:gc(e,8e3)}function mc(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 hc(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 gc(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function _c(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}const vc=2,yc=5;var bc=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),Y.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:ji(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&&Y.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`){Y.info(`subagent status changed`,t);return}if(e.status===`killed`){Y.warn(`subagent status changed`,t);return}Y.error(`subagent status changed`,t)}};const xc=new Map;function Sc(e){let t=xc.get(e);return t||(t={},xc.set(e,t)),t}function Cc(e){xc.delete(e)}let wc=!1;function Tc(){wc||=(at(),it({api:`openai-completions`,stream:ca,streamSimple:la}),!0)}const Ec=[`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(`
28
- `);async function Dc(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o,onFallback:s}=e,c=t.trim().replace(/\s+/g,` `);if(!c)return`New session`;if(!r.flashModel)return Mc(c);let l=Mc(c),u=r.flashModel,d=Ni({apiFormat:r.apiFormat,baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:u,hooks:a,hookCtx:o}),f=[{role:`user`,content:c}];n&&f.push({role:`assistant`,content:n});let p=kc(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await d.chat({system:Ec,user:JSON.stringify(f),temperature:0,maxTokens:100,signal:p.signal})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(Ac(t)){if(p.didTimeout())return s?.(`timeout`),l;throw t}e<3&&await Oc(500*e,p.signal)}}catch(e){if(Ac(e)&&p.didTimeout())return s?.(`timeout`),l;throw e}finally{p.clear()}return s?.(`error`),l}function Oc(e,t){return t?t.aborted?Promise.reject(jc()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(jc())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function kc(e,t){let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},t);return e?.aborted?n.abort():e?.addEventListener(`abort`,()=>n.abort(),{once:!0}),{signal:n.signal,clear:()=>clearTimeout(i),didTimeout:()=>r}}function Ac(e){return e instanceof Error&&e.name===`AbortError`}function jc(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function Mc(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 Nc(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 Pc(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 Fc(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 Lc({sessionId:n,titleSource:i.trim()?i:`New session`,text:e.replyText,runParams:o,hookRegistry:s,hookContext: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 Y.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 Pc({sessionId:n,result:g,runParams:o,hookRegistry:s,hookContext:c,eventDispatcher:d}),g}async function Ic(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 Lc({sessionId:t,titleSource:r,text:e.text,runParams:i,hookRegistry:a,hookContext:o,logLifecycle:!0});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?Y.warn(`agent run finalized with error`,g):Y.info(`agent run finalized`,g),await Pc({sessionId:t,result:m,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:p}),m}async function Lc(e){let t=Mc(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&Y.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await Dc({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,onFallback:e=>{n=e}});return n?Y.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&Y.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return Y.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const Rc=new Set([`pause`,`resume`,`clear`,`help`]),zc=`/goal
19
+ `)}function oo(e,t){return!t?.initPrompt||typeof e!=`string`?e:Rr(t,e)}function so(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}var co=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=H.resolve(e.rootDir??wn(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=G(e.path),n=ho(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 Hn(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:Tn(this.rootDir)}}async createSkill(e){let t=kn(e.name),n=G(e.categoryPath),r=ho(e.description,`auto-skill description`),i=go(e.body);await this.assertCategoryExists(n);let a=An(n,t),o=Nn(this.rootDir,n,t);if(await po(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=H.join(o,`SKILL.md`),l=H.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:_o(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:vo(e.evidence,s)};return await V.mkdir(o,{recursive:!0}),await V.writeFile(c,lo(t,r,i),`utf-8`),await mo(l,u),await Hn(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=Nn(this.rootDir,t.categoryPath,t.skillName),r=H.join(n,`SKILL.md`),i=H.join(n,`metadata.json`),a=await uo(r),o=await fo(i),s=e.description===void 0?a.description:ho(e.description,`auto-skill description`),c=e.body===void 0?a.body:go(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?_o(o.tags):_o(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:{},...vo(e.evidence,l)}};return await V.writeFile(r,lo(t.skillName,s,c),`utf-8`),await mo(i,u),await Hn(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=Nn(this.rootDir,t.categoryPath,t.skillName),r=H.join(n,`metadata.json`),i=H.join(n,`SKILL.md`);await V.access(i);let a=await fo(r),o=this.now().toISOString();return await mo(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...vo(e.evidence,o)}}),await Hn(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=Tn(this.rootDir),t;try{t=await V.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=G(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 V.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await mo(Tn(this.rootDir),t)}};function lo(e,t,n){return[`---`,`name: ${yo(e)}`,`description: ${yo(t)}`,`---`,``,n.trim(),``].join(`
20
+ `)}async function uo(e){let t=$e(await V.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function fo(e){let t;try{t=await V.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 po(e){try{return await V.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function mo(e,t){await V.mkdir(H.dirname(e),{recursive:!0}),await V.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function ho(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function go(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 _o(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function vo(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function yo(e){return JSON.stringify(e)}const bo=[`create`,`update`,`archive`,`create_category`],xo=W.Object({}),So=W.Object({categoryPath:W.Optional(W.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:W.Optional(W.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),Co=W.Object({query:W.String({description:`Search query for learned auto-skills.`}),limit:W.Optional(W.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),wo=W.Object({skillId:W.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:W.Optional(W.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),To=W.Object({action:W.Union(bo.map(e=>W.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:W.Optional(W.String({description:`Exact auto-skill id for update/archive.`})),name:W.Optional(W.String({description:`Auto-skill slug for create.`})),categoryPath:W.Optional(W.String({description:`Existing single-level category slug for create.`})),newCategory:W.Optional(W.Object({path:W.String({description:`New single-level category slug to create.`}),description:W.String({description:`New category description.`})})),description:W.Optional(W.String({description:`Auto-skill description for create/update.`})),tags:W.Optional(W.Array(W.String({description:`Auto-skill tag.`}))),confidence:W.Optional(W.Number({description:`Optional confidence score from 0 to 1.`})),body:W.Optional(W.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:W.Optional(W.Object({sessionId:W.String({description:`Source session id.`}),reason:W.String({description:`Why this auto-skill write is justified.`}),toolCallCount:W.Optional(W.Number({description:`Tool calls observed in source run.`})),loadedSkills:W.Optional(W.Array(W.String({description:`Skill loaded during source run.`})))}))});function Eo(e){let t=new K({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:xo,async execute(){try{let e=await t.autoSkillCategories();return Y({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return Y({categories:[],count:0,error:Mo(e)})}}}}function Do(e){let t=new K({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:So,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return Y({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Y({skills:[],count:0,error:Mo(e)})}}}}function Oo(e){let t=new K({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:Co,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return Y({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Y({skills:[],count:0,error:Mo(e)})}}}}function ko(e){let t=new K({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:wo,async execute(e,n){try{return Y({...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 Y({skillId:n.skillId,error:Mo(e)})}}}}function Ao(e){let t=new co({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:To,async execute(e,n){try{return Y(await jo(t,n))}catch(e){return Y({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:Mo(e)})}}}}async function jo(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 Y(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Mo(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const No=W.Object({kind:W.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>W.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:W.Optional(W.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:W.Optional(W.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:W.Optional(W.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:W.Optional(W.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function Po(e){let t=rn({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??Qt}),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:No,async execute(r,i){try{return i.kind===`tool_result`?Io(await nn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?Io(await $t({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?Io(await en({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?Io({...await tn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):Io(await tn({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:Fo(i),limits:t}))}catch(r){return Io({kind:i.kind,error:Lo(r),limits:t,contextFiles:on(e.dataDir,e.sessionId,n)})}}}}function Fo(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 Io(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Lo(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ro(e){let t=[Do(e.dataDir),Oo(e.dataDir),ko(e.dataDir),Po({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(Ao(e.dataDir)),t}const zo=`auto-skill-reviewer`;async function Bo(e){let t=e.createModel??Sr,n=e.tools??Ro({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 Qa({sessionId:e.sessionId,systemPrompt:Vo(e.mode),message:Ho(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=Uo(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 Vo(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(`
21
+ `)}function Ho(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(`
22
+ `)}function Uo(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=Wo(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 Wo(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const Go=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Ko=Go,qo={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}},Jo=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Yo(e){let t=Zo(e.gates),n={session:$o(`session`,e.sessionTranscript,t.session),currentRun:$o(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:$o(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=rs(e.reviewState?.reviewCount,0),i=rs(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return as(n,a,r,i,o,`run_error`);if(e.result?.paused)return as(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return as(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return as(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 Xo(e,t={}){let n=Ht(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??Go),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(os(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}ss(t)&&cs(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:Qo(e?e.session:qo.session),currentRun:Qo(e?e.currentRun:qo.currentRun),reviewWindow:Qo(e?e.reviewWindow:qo.reviewWindow)}}function Qo(e){let t={};for(let n of Jo){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Ko:void 0;if(typeof r==`number`){let e=ns(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=ns(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:is(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:is(r.toolNames,i)})}return t}function $o(e,t,n){let r=Xo(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=Jo.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];es(t,o,r)?i.push({code:t,description:ts(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 es(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 ts(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 ns(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function rs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function is(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function as(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 os(e){return e.role===`assistant`}function ss(e){return e.role===`tool_result`}function cs(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:ls(e.content)?.success===!1}function ls(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function us(e){let t=Wt(e.transcript.length,e.transcriptStartIndex),n=Gt(e.transcript.length,e.recentEntryLimit),r=Wt(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Wt(e.transcript.length,0),a=Kt(e.transcript,t),o=Kt(e.transcript,r),s=Xo(e.transcript),c=Xo(a),l=Xo(o),u=Vt(e.transcript),d=Vt(a),f=Vt(o),p=a.filter(fs),m=a.filter(ps);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:ds(p[0]?.content??``,800),finalResponse:ds(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:Ut(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 ds(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function fs(e){return e.role===`user`}function ps(e){return e.role===`assistant`}function ms(e,t,n){return H.join(d(e,t,n),`auto-skill-review-state.json`)}function hs(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function gs(e,t,n){let r=ms(e,t,n),i;try{i=await V.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return hs(t);throw e}return xs(JSON.parse(i),t)}async function _s(e,t,n){let r=ms(e,t.sessionId,n);await V.mkdir(H.dirname(r),{recursive:!0}),await V.writeFile(r,`${JSON.stringify(xs(t,t.sessionId),null,2)}\n`,`utf-8`)}async function vs(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await _s(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function ys(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 _s(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function bs(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await _s(e.dataDir,t,{storeName:e.sessionStoreName}),t}function xs(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:ws(n.reviewCount,0),lastAttemptedReviewAt:Ss(n.lastAttemptedReviewAt),lastCompletedReviewAt:Ss(n.lastCompletedReviewAt),lastFailedReviewAt:Ss(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:Cs(n.lastReviewedTranscriptEndIndex)}}function Ss(e){return typeof e==`string`&&e.trim()?e:null}function Cs(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function ws(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function Ts(e){return H.join(wn(e),`.reviews`,`run-log.jsonl`)}async function Es(e,t){let n=Ts(e);await V.mkdir(H.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await V.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const Ds=`write`,Os=new Set([`off`,`gate`,`dry_run`,`write`]);async function ks(e){let t=As(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=Ms(e);if(n){await Is(e,t,n);return}let r,i;try{let n=await m(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=Ns(n,e.transcriptStartIndex),o=await gs(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=Ps(o.lastReviewedTranscriptEndIndex,n.length),c=Ns(n,s);await Ls(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=Yo({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await Ls(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 Rs(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await Ls(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new K({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=us({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:on(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await Ls(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await Rs(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(zo);if(!p){q.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:zo}),await Is(e,t,`reviewer_agent_missing`,{reviewerAgentName:zo});return}i={mode:f,decision:l,packet:d},r=await vs({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??Bo,g=Ro({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 bs({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await zs(e.runParams.dataDir,i,{status:`failed`,curatorResult:_,error:_.error,reviewState:r});await Fs(e,_.error,{mode:t.mode,usage:_.usage,toolCalls:Bs(_.toolCalls),toolResults:qs(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewRunLogPath:n});return}r=await ys({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let v=await zs(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:Ks(_.text,2e3),toolCalls:Bs(_.toolCalls),toolResults:qs(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewState:r,reviewRunLogPath:v}})}catch(t){let n=t instanceof Error?t.message:String(t),a;r&&(r=await bs({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await zs(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await Fs(e,n,a?{reviewRunLogPath:a}:void 0)}}function As(e){return{mode:js(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function js(e){if(e==null)return Ds;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?Os.has(t)?t:`off`:Ds}function Ms(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 Ns(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function Ps(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function Fs(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 Is(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 Ls(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function Rs(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:Gs(n),...i.packet?{packet:i.packet}:{}}})}async function zs(e,t,n){return Es(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?Hs(n.curatorResult.text):void 0,conclusionText:n.curatorResult?Us(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?Bs(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?qs(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 Bs(e){return e.map(e=>({...e,arguments:Vs(e.name,e.arguments)}))}function Vs(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 Hs(e){let t=Ws(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function Us(e){return Hs(e)?void 0:Ks(e,8e3)}function Ws(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 Gs(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 Ks(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function qs(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}const Js=2,Ys=5;var Xs=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),q.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:si(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&&q.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`){q.info(`subagent status changed`,t);return}if(e.status===`killed`){q.warn(`subagent status changed`,t);return}q.error(`subagent status changed`,t)}};const Zs=new Map;function Qs(e){let t=Zs.get(e);return t||(t={},Zs.set(e,t)),t}function $s(e){Zs.delete(e)}let ec=!1;function tc(){ec||=(ct(),st({api:`openai-completions`,stream:Ri,streamSimple:zi}),!0)}const nc=[`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(`
23
+ `);async function rc(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o,onFallback:s}=e,c=t.trim().replace(/\s+/g,` `);if(!c)return`New session`;if(!r.flashModel)return cc(c);let l=cc(c),u=r.flashModel,d=li({apiFormat:r.apiFormat,baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:u,hooks:a,hookCtx:o}),f=[{role:`user`,content:c}];n&&f.push({role:`assistant`,content:n});let p=ac(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await d.chat({system:nc,user:JSON.stringify(f),temperature:0,maxTokens:100,signal:p.signal})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(oc(t)){if(p.didTimeout())return s?.(`timeout`),l;throw t}e<3&&await ic(500*e,p.signal)}}catch(e){if(oc(e)&&p.didTimeout())return s?.(`timeout`),l;throw e}finally{p.clear()}return s?.(`error`),l}function ic(e,t){return t?t.aborted?Promise.reject(sc()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(sc())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function ac(e,t){let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},t);return e?.aborted?n.abort():e?.addEventListener(`abort`,()=>n.abort(),{once:!0}),{signal:n.signal,clear:()=>clearTimeout(i),didTimeout:()=>r}}function oc(e){return e instanceof Error&&e.name===`AbortError`}function sc(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function cc(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 X(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}async function lc(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 uc(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,{...X(r)});await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs},a,{eventDispatcher:e.eventDispatcher})}async function dc(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=X(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 pc({sessionId:n,titleSource:i.trim()?i:`New session`,text:e.replyText,runParams:o,hookRegistry:s,hookContext: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,X(o)),toolResultsDir:S(o.dataDir,n,X(o))}};return q.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 uc({sessionId:n,result:g,runParams:o,hookRegistry:s,hookContext:c,eventDispatcher:d}),g}async function fc(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=X(i),s=await pc({sessionId:t,titleSource:r,text:e.text,runParams:i,hookRegistry:a,hookContext:o,logLifecycle:!0});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,X(i)),toolResultsDir:S(i.dataDir,t,X(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?q.warn(`agent run finalized with error`,g):q.info(`agent run finalized`,g),await uc({sessionId:t,result:m,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:p}),m}async function pc(e){let t=cc(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&q.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await rc({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,onFallback:e=>{n=e}});return n?q.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&q.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return q.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const mc=new Set([`pause`,`resume`,`clear`,`help`]),hc=`/goal
29
24
  【目标】:把 src/auth 目录下重复的参数校验逻辑抽离成公共函数。
30
25
  【范围】:只处理 src/auth 目录,不扩散到用户模块或订单模块。
31
26
  【约束】:保持现有 API 兼容,不引入新依赖,不要改变数据库结构。
32
27
  【验证】:每次改动后请自主运行 npm test auth 以及 npm run typecheck。如果测试失败,请定位原因并修复。
33
- 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function Bc(){return[`/goal 命令`,` /goal <目标内容> 设置或替换 /goal 目标(设为进行中)`,` /goal --token-budget <n> <目标内容> 设置带 Token 预算的 /goal 目标(0 表示不限)`,` /goal 查看当前 /goal 目标摘要`,` /goal pause 暂停 /goal 目标继续执行`,` /goal resume 恢复已暂停的 /goal 目标`,` /goal clear 清除 /goal 目标`,``,`多行结构化示例(/goal 后换行;Console 用 Shift+Enter 换行,Enter 发送):`,zc].join(`
34
- `)}function Vc(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,zc,``,`正文(写入 objective.txt 供 --goal-file):`,zc.replace(/^\/goal\s+/,``)].join(`
35
- `)}async function Hc(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await R(e.dataDir,e.sessionId,t);if(!r)return{action:`created`,goal:await L(e.dataDir,e.sessionId,{goalId:Ye(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource})};if((await B(e.dataDir,e.sessionId,r,t)).trim()!==n)return{action:`replaced`,goal:await L(e.dataDir,e.sessionId,{goalId:Ye(),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 Uc(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(Rc.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 必须是正整数,或使用 0 表示不限。`);r=(a[2]??``).trim()}if(!r)throw Error(`用法:/goal <目标内容> 或 /goal --token-budget <n> <目标内容>`);return{action:`set`,objective:r,tokenBudget:i}}function Wc(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function Gc(e,t){let n=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`;return[`/goal 目标`,`状态:${Wc(e.status)}`,`目标内容:${t.length>200?`${t.slice(0,200)}...`:t}`,n,`已用时:${e.timeUsedSeconds} 秒`,``,Kc(e.status)].join(`
36
- `)}function Kc(e){switch(e){case`active`:return`可用命令:/goal pause、/goal clear`;case`paused`:return`可用命令:/goal resume、/goal clear`;case`budget_limited`:return`/goal 目标已触达预算限制。可用命令:/goal clear(不要仅因预算耗尽就判定为已完成)`;case`complete`:return`/goal 目标已完成。可用命令:/goal clear`;default:return`可用命令:/goal <目标内容>、/goal pause、/goal resume、/goal clear`}}async function qc(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:Bc()};if(e.action===`get`){let e=await R(t.dataDir,t.sessionId,n);return e?{replyText:Gc(e,await B(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
37
- `)}}if(e.action===`set`){let r=await Hc({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await B(t.dataDir,t.sessionId,r.goal,n);return r.action===`unchanged`?{replyText:r.goal.status===`complete`?`/goal 目标已完成。\n\n${Gc(r.goal,i)}`:`/goal 目标未变化。\n\n${Gc(r.goal,i)}`}:{replyText:`${r.action===`resumed`?`/goal 目标已恢复(进行中)。`:r.action===`updated`?`/goal 目标已更新。`:`/goal 目标已设置(进行中)。`}\n\n${Gc(r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await R(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await I(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${Gc(r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await R(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能恢复。`);if(e.status===`budget_limited`)throw Error(`/goal 目标已触达预算限制,不能恢复;请使用 /goal clear 清除,或重新设置新的 /goal 目标。`);if(e.status===`active`)return{replyText:`/goal 目标已处于进行中状态。\n\n${Gc(e,await B(t.dataDir,t.sessionId,e,n))}`};let r=await I(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${Gc(r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await V(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const Jc=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`},{name:`/goal`,description:`设置或查看 /goal 目标`},{name:`/goal pause`,description:`暂停 /goal 目标`},{name:`/goal resume`,description:`恢复 /goal 目标`},{name:`/goal clear`,description:`清除 /goal 目标`}];function Yc(){return Jc.map(e=>({...e}))}function Xc(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Zc(e){let t=new Set,n=[];for(let r of e){let e=Xc(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Qc(e){let t=Yc(),n=Zc(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function $c(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 el(e){let t=$c(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 tl(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 nl(e,t){let n=el(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=Uc(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:Xc(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Zc(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 rl=new Set([`/new`,`/reset`,`/compact`]),il=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),al=new Set([`/help`]);function ol(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function sl(e){if(e.length===0)return[];let t=e.map(ol),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function cl(e){let t=Qc(e.skills),n=t.builtin.filter(e=>rl.has(e.name)),r=t.builtin.filter(e=>il.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>al.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...sl(n)),s.push(``),s.push(`目标命令`),s.push(...sl(r)),s.push(``),s.push(`技能命令`),s.push(...sl(i)),o.length>0?(s.push(...sl(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...sl(a)),{kind:`reply`,text:s.join(`
38
- `)}}function ll(e,t){let n=t.trim().toLowerCase();return n&&Zc(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function ul(e){let t=ll(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(`
39
-
40
- `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function dl(e){let t=nl(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?cl(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?ul({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||`用法:/goal <目标内容> | /goal pause | /goal resume | /goal clear`}:{kind:`pass`,message:e.message}}function fl(e){return Math.ceil(e.length/4*1.2)}function pl(e){if(e.role===`user`)return fl(e.content);if(e.role===`assistant`){let t=fl(e.content);e.errorMessage&&(t+=fl(e.errorMessage));for(let n of e.toolCalls??[])t+=fl(n.name)+fl(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(`
41
- `):e.content;return fl(e.toolName)+fl(t)}function $(e){return e.reduce((e,t)=>e+pl(t),0)}const ml=[`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(`
42
- `);async function hl(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=_l(t,r,i),l,u=Ni({apiFormat:n.apiFormat,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:ml,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 gl(500*e)}throw l}function gl(e){return new Promise(t=>setTimeout(t,e))}function _l(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`?vl(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(`
43
- `):t.content,i=n.length>2e3?`${n.slice(0,2e3)}… [truncated]`:n;r.push(`Tool(${t.toolName})[${e}]: ${i}`)}return r.join(`
44
- `)}function vl(e){let t=yl(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(`
45
- `)}function yl(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 xl(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=pl(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function Sl(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 Cl(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=wl(t),l=c>=0?t[c].content:void 0,u=Sl(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}=xl(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 hl({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 wl(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Tl=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
46
- `),El=[`.aimax/new.txt`];async function Dl(e){try{return(await Ge(e,`utf-8`)).trim()||null}catch{return null}}async function Ol(e){for(let t of El){let n=await Dl(Ke(e,t));if(n)return n}return await Dl(`/aimax_pvc/new.txt`)||Tl}async function kl(e){return{kind:`reply`,text:await Ol(e)}}function Al(){return{kind:`reply`,text:`✅ Session reset.`}}function jl(e){let t=Pl(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Fl(r):null,a=n??i?.text,o=a?tl(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Il(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Ll(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Ml(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=nl(e.slashCommandSource,t);if(n.kind===`goal`)return{kind:`goal`,action:n.action,objective:n.objective,tokenBudget:n.tokenBudget,transcriptMessage:e.transcriptMessage};let r=dl({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:Il(e.promptInput,r.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Ll(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Nl(e){let t=Ml(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 Fc({replyText:(t.action===`reset`?Al():await kl(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 Fc({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 qc({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 错误:${e.message}`}}return n.goalUpdate&&(await ln(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),Rl(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await B(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await Fc({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 Cl({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 Fc({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 Pl(e){return typeof e.message==`string`}function Fl(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 Il(e,t){let n=Fl(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 Ll(e){return typeof e==`string`?e:JSON.stringify(e)}function Rl(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}function zl(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 Bl=[`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.`],Vl={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Hl(e,t){return e.map(e=>Ul(e,t))}function Ul(e,t){let n=new Date(e.timestamp).getTime();if(Wl(e))return{role:`user`,content:e.content,timestamp:n};if(Gl(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:Vl,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:Kl(r)}],isError:r.isError,timestamp:n}}function Wl(e){return e.role===`user`}function Gl(e){return e.role===`assistant`}function Kl(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:`,...Bl];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
47
- `)}async function ql(e){return Yl((await Ni({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:Ql,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.segments},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}async function Jl(e){return Xl((await Ni({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:$l,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedTurns:e.maxSelectedTurns,turns:e.turns},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}function Yl(e){let t=Zl(e);if(t.version!==1||!Array.isArray(t.selectedSegmentIds))throw Error(`Topic segment selection decision has invalid schema.`);return{version:1,selectedSegmentIds:t.selectedSegmentIds.filter(e=>typeof e==`string`),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function Xl(e){let t=Zl(e);if(t.version!==1||!Array.isArray(t.selectedTurns))throw Error(`Topic turn selection decision has invalid schema.`);return{version:1,selectedTurns:t.selectedTurns.filter(e=>!!(e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:typeof e.topicLabel==`string`?e.topicLabel.trim():void 0,keywords:Array.isArray(e.keywords)?e.keywords.filter(e=>typeof e==`string`&&e.trim().length>0):void 0})),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function Zl(e){let t=e.trim();if(!t)throw Error(`Topic segmentation model returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t;return JSON.parse(r)}[`You maintain SeCom-style conversation segments for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"action":"merge|split","reason":"...","topicLabel":"optional","summary":"...","compressedSummary":"...","keywords":["..."]}`,`Task: compare the active segment with the new user turn.`,`Use action=merge only when the new turn continues the same topic, task, artifact, bug, document, or refinement thread.`,`Use action=split when the new turn starts a different topic.`,`Always provide summary, compressedSummary, and concise keywords for the resulting segment after your decision.`,`Do not answer the user.`].join(`
48
- `);const Ql=[`You select relevant conversation segments for an IM assistant before final turn-level topic classification.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedSegmentIds":["..."],"reason":"...","confidence":"high|medium|low"}`,`Task: choose which prior segments are relevant to the current user message.`,`Relevant includes same task continuation, explicit topic return, reuse of prior artifact, correction, or combining multiple earlier topics.`,`Prefer recall over over-pruning when the user explicitly refers to older topics by name.`,`Do not answer the user.`].join(`
49
- `),$l=[`You select relevant historical conversation turns for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurns":[{"turnId":"...","summary":"...","topicLabel":"optional","keywords":["..."]}],"reason":"...","confidence":"high|medium|low"}`,`Task: from the provided turns, select any turn that may be relevant to the current user message.`,`This is recall-first. It is better to include possibly relevant turns than to miss a relevant one.`,`Select turns for same task continuation, explicit old-topic return, reuse of prior artifact, corrections, or combinations of multiple earlier topics.`,`For every selected turn, provide a concise reusable summary, an optional topicLabel, and short keywords.`,`Prefer the provided summary/topicLabel fields when they exist; use raw user/assistant content only when needed.`,`Do not answer the user.`].join(`
50
- `);async function eu(e){let t=au(e);if(t)try{let e=await W.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(xu);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function tu(e){let t=au(e);t&&(await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function nu(e){let t=ou(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||su(t,e)){r.push(e);continue}n.push(lu(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(lu(r,n.length+1,!0)),n}function ru(e,t){let n=ou(t);if(n.length===0)return[];if(!e||e.length===0)return nu(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return nu(t);if(r.length===n.length)return e;let a=e.map(e=>({...e,turnIds:[...e.turnIds],toolNames:[...e.toolNames],keywords:[...e.keywords]})),o=n.slice(r.length);for(let e of o){let t=a[a.length-1];if(t&&cu(t,e)){a[a.length-1]=mu(t,e);continue}t&&(t.status=`closed`),a.push(lu([e],a.length+1,!0))}if(a.length>1){for(let e=0;e<a.length-1;e+=1)a[e]={...a[e],status:`closed`};a[a.length-1]={...a[a.length-1],status:`active`}}return a}function iu(e,t){if(!e||e.length===0||t.length===0)return e??[];let n=new Map(t.map(e=>[e.turnId,e])),r=!1,i=e.map(e=>{let t=new Map((e.turnMemories??[]).map(e=>[e.turnId,e])),i=!1;for(let r of e.turnIds){let e=n.get(r);if(!e)continue;let a=t.get(r);(!a||a.summary!==e.summary||a.topicLabel!==e.topicLabel||a.keywords.join(`|`)!==e.keywords.join(`|`))&&(t.set(r,e),i=!0)}if(!i)return e;r=!0;let a=[...t.values()].sort((e,t)=>e.turnId.localeCompare(t.turnId)),o=a.find(t=>e.turnIds.includes(t.turnId)),s=[...new Set([...e.keywords,...a.flatMap(e=>e.keywords)])];return{...e,keywords:s,topicLabel:o?.topicLabel??e.topicLabel,turnMemories:a,updatedAt:o?.updatedAt??e.updatedAt}});return r?i:e}function au(e){if(!(!e.dataDir||!e.sessionId))return G.join(d(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function ou(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,user:a.content,timestamp:a.timestamp,toolNames:[]};continue}if(n){if(n.endIndex=i,a.role===`assistant`){let e=(a.content||a.errorMessage||``).trim();e&&(n.assistant=e);for(let e of a.toolCalls??[])n.toolNames.push(e.name);continue}a.role===`tool_result`&&n.toolNames.push(a.toolName)}}return r(),t.map(e=>({...e,toolNames:[...new Set(e.toolNames)].sort()}))}function su(e,t){return _u(gu(e.user,e.assistant),gu(t.user,t.assistant))>0}function cu(e,t){return _u(gu(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),gu(t.user,t.assistant,t.toolNames.join(` `)))>0}function lu(e,t,n){return uu(e,t,n)}function uu(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=du(e,o),c=bu(r?.summary||s),l=hu(r?.keywords,c,o),u=bu(r?.compressedSummary||pu(c,o));return{version:1,segmentId:`segment-${t}`,turnIds:e.map(e=>e.turnId),startTurnId:i.turnId,endTurnId:a.turnId,startIndex:i.startIndex,endIndex:a.endIndex,userSummary:e.map(e=>e.user).join(`
28
+ 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function gc(){return[`/goal 命令`,` /goal <目标内容> 设置或替换 /goal 目标(设为进行中)`,` /goal --token-budget <n> <目标内容> 设置带 Token 预算的 /goal 目标(0 表示不限)`,` /goal 查看当前 /goal 目标摘要`,` /goal pause 暂停 /goal 目标继续执行`,` /goal resume 恢复已暂停的 /goal 目标`,` /goal clear 清除 /goal 目标`,``,`多行结构化示例(/goal 后换行;Console 用 Shift+Enter 换行,Enter 发送):`,hc].join(`
29
+ `)}function _c(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,hc,``,`正文(写入 objective.txt 供 --goal-file):`,hc.replace(/^\/goal\s+/,``)].join(`
30
+ `)}async function vc(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await z(e.dataDir,e.sessionId,t);if(!r)return{action:`created`,goal:await L(e.dataDir,e.sessionId,{goalId:Ze(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource})};if((await B(e.dataDir,e.sessionId,r,t)).trim()!==n)return{action:`replaced`,goal:await L(e.dataDir,e.sessionId,{goalId:Ze(),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 yc(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(mc.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 必须是正整数,或使用 0 表示不限。`);r=(a[2]??``).trim()}if(!r)throw Error(`用法:/goal <目标内容> 或 /goal --token-budget <n> <目标内容>`);return{action:`set`,objective:r,tokenBudget:i}}function bc(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function xc(e,t){let n=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`;return[`/goal 目标`,`状态:${bc(e.status)}`,`目标内容:${t.length>200?`${t.slice(0,200)}...`:t}`,n,`已用时:${e.timeUsedSeconds} 秒`,``,Sc(e.status)].join(`
31
+ `)}function Sc(e){switch(e){case`active`:return`可用命令:/goal pause、/goal clear`;case`paused`:return`可用命令:/goal resume、/goal clear`;case`budget_limited`:return`/goal 目标已触达预算限制。可用命令:/goal clear(不要仅因预算耗尽就判定为已完成)`;case`complete`:return`/goal 目标已完成。可用命令:/goal clear`;default:return`可用命令:/goal <目标内容>、/goal pause、/goal resume、/goal clear`}}async function Cc(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:gc()};if(e.action===`get`){let e=await z(t.dataDir,t.sessionId,n);return e?{replyText:xc(e,await B(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
32
+ `)}}if(e.action===`set`){let r=await vc({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await B(t.dataDir,t.sessionId,r.goal,n);return r.action===`unchanged`?{replyText:r.goal.status===`complete`?`/goal 目标已完成。\n\n${xc(r.goal,i)}`:`/goal 目标未变化。\n\n${xc(r.goal,i)}`}:{replyText:`${r.action===`resumed`?`/goal 目标已恢复(进行中)。`:r.action===`updated`?`/goal 目标已更新。`:`/goal 目标已设置(进行中)。`}\n\n${xc(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(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await I(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${xc(r,await B(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(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能恢复。`);if(e.status===`budget_limited`)throw Error(`/goal 目标已触达预算限制,不能恢复;请使用 /goal clear 清除,或重新设置新的 /goal 目标。`);if(e.status===`active`)return{replyText:`/goal 目标已处于进行中状态。\n\n${xc(e,await B(t.dataDir,t.sessionId,e,n))}`};let r=await I(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${xc(r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ie(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const wc=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`},{name:`/goal`,description:`设置或查看 /goal 目标`},{name:`/goal pause`,description:`暂停 /goal 目标`},{name:`/goal resume`,description:`恢复 /goal 目标`},{name:`/goal clear`,description:`清除 /goal 目标`}];function Tc(){return wc.map(e=>({...e}))}function Ec(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Dc(e){let t=new Set,n=[];for(let r of e){let e=Ec(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Oc(e){let t=Tc(),n=Dc(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function kc(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 Ac(e){let t=kc(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 jc(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 Mc(e,t){let n=Ac(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=yc(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:Ec(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Dc(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 Nc=new Set([`/new`,`/reset`,`/compact`]),Pc=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),Fc=new Set([`/help`]);function Ic(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function Lc(e){if(e.length===0)return[];let t=e.map(Ic),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Rc(e){let t=Oc(e.skills),n=t.builtin.filter(e=>Nc.has(e.name)),r=t.builtin.filter(e=>Pc.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>Fc.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...Lc(n)),s.push(``),s.push(`目标命令`),s.push(...Lc(r)),s.push(``),s.push(`技能命令`),s.push(...Lc(i)),o.length>0?(s.push(...Lc(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...Lc(a)),{kind:`reply`,text:s.join(`
33
+ `)}}function zc(e,t){let n=t.trim().toLowerCase();return n&&Dc(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function Bc(e){let t=zc(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(`
34
+
35
+ `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function Vc(e){let t=Mc(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Rc(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||`用法:/goal <目标内容> | /goal pause | /goal resume | /goal clear`}:{kind:`pass`,message:e.message}}function Hc(e){return Math.ceil(e.length/4*1.2)}function Uc(e){if(e.role===`user`)return Hc(e.content);if(e.role===`assistant`){let t=Hc(e.content);e.errorMessage&&(t+=Hc(e.errorMessage));for(let n of e.toolCalls??[])t+=Hc(n.name)+Hc(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(`
36
+ `):e.content;return Hc(e.toolName)+Hc(t)}function Z(e){return e.reduce((e,t)=>e+Uc(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(`
37
+ `);async function Gc(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=qc(t,r,i,a),u=Jc(a),d,f=li({apiFormat:n.apiFormat,baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:n.model,hooks:s,hookCtx:c});for(let e=1;e<=3;e++)try{let e=(await f.chat({system:Wc,user:l,temperature:0,maxTokens:u,signal:o})).text.trim();if(!e)throw Error(`LLM summarisation returned empty content`);return e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;d=t,e<3&&await Kc(500*e)}throw d}function Kc(e){return new Promise(t=>setTimeout(t,e))}function qc(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${Qc(t.trim(),Yc(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=Xc(e,t,n,r),o=Zc(t,n,r);for(let[t,n]of e.entries()){if(o<=0){i.push(`[${e.length-t} entries omitted because the summarisation input budget was exhausted]`);break}let r=``;if(n.role===`user`)r=`User: ${Qc(n.content,Math.min(a,o))}`;else if(n.role===`assistant`)r=`Assistant:${n.toolCalls&&n.toolCalls.length>0?` [called tools: ${n.toolCalls.map(e=>e.name).join(`, `)}]`:``} ${Qc(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?$c(n):n.toolResultRef?[`[tool result persisted] ${n.toolResultRef.toolName} (${n.toolResultRef.originalChars} chars).`,`Full output: ${n.toolResultRef.storagePath}`,n.toolResultRef.preview.trim()?`Preview:\n${n.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
38
+ `):n.content;r=`Tool(${n.toolName})[${e}]: ${Qc(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
39
+ `)}function Jc(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function Yc(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function Xc(e,t,n,r){let i=Zc(t,n,r);if(!r||r<=0)return 2e3;let a=Jc(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=Wc.length+(t?.length??0)+(n?.length??0)+1e3,c=Math.max(1e3,o*4-s);return Math.max(120,Math.min(2e3,i,Math.floor(c/Math.max(1,e.length))))}function Zc(e,t,n){if(!n||n<=0)return 1/0;let r=Jc(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=Wc.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function Qc(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function $c(e){let t=el(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(`
40
+ `)}function el(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=tl(t);if(e.name||e.path)return e}return{}}function tl(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 nl(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Uc(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function rl(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 il(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=al(t),l=c>=0?t[c].content:void 0,u=rl(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}=nl(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:Z(u)}:{status:`compacted`,entry:{role:`compaction`,content:await Gc({entries:f,llm:r,previousSummary:l,instructions:i,contextWindowTokens:n,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:Z(d)}}function al(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const ol=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
41
+ `),sl=[`.aimax/new.txt`];async function cl(e){try{return(await Je(e,`utf-8`)).trim()||null}catch{return null}}async function ll(e){for(let t of sl){let n=await cl(Ye(e,t));if(n)return n}return await cl(`/aimax_pvc/new.txt`)||ol}async function ul(e){return{kind:`reply`,text:await ll(e)}}function dl(){return{kind:`reply`,text:`✅ Session reset.`}}async function fl(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function pl(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 fl(e,t,{action:n.action,goal:n.after??null})}function ml(e){let t=_l(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?vl(r):null,a=n??i?.text,o=a?jc(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?yl(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:bl(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function hl(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=Mc(e.slashCommandSource,t);if(n.kind===`goal`)return{kind:`goal`,action:n.action,objective:n.objective,tokenBudget:n.tokenBudget,transcriptMessage:e.transcriptMessage};let r=Vc({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:yl(e.promptInput,r.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:bl(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function gl(e){let t=hl(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 dc({replyText:(t.action===`reset`?dl():await ul(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 dc({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 Cc({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 错误:${e.message}`}}return n.goalUpdate&&(await fl(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),xl(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await B(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await dc({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 il({entries:e.runParams.channel===`CRON`?[]:await m(e.runParams.dataDir,e.sessionId,X(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 dc({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 _l(e){return typeof e.message==`string`}function vl(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 yl(e,t){let n=vl(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 bl(e){return typeof e==`string`?e:JSON.stringify(e)}function xl(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}function Sl(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 Cl=[`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.`],wl={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Tl(e,t){return e.map(e=>El(e,t))}function El(e,t){let n=new Date(e.timestamp).getTime();if(Dl(e))return{role:`user`,content:e.content,timestamp:n};if(Ol(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:wl,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:kl(r)}],isError:r.isError,timestamp:n}}function Dl(e){return e.role===`user`}function Ol(e){return e.role===`assistant`}function kl(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:`,...Cl];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
42
+ `)}async function Al(e){return Ml((await li({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:Fl,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.segments},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}async function jl(e){return Nl((await li({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:Il,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedTurns:e.maxSelectedTurns,turns:e.turns},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}function Ml(e){let t=Pl(e);if(t.version!==1||!Array.isArray(t.selectedSegmentIds))throw Error(`Topic segment selection decision has invalid schema.`);return{version:1,selectedSegmentIds:t.selectedSegmentIds.filter(e=>typeof e==`string`),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function Nl(e){let t=Pl(e);if(t.version!==1||!Array.isArray(t.selectedTurns))throw Error(`Topic turn selection decision has invalid schema.`);return{version:1,selectedTurns:t.selectedTurns.filter(e=>!!(e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:typeof e.topicLabel==`string`?e.topicLabel.trim():void 0,keywords:Array.isArray(e.keywords)?e.keywords.filter(e=>typeof e==`string`&&e.trim().length>0):void 0})),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function Pl(e){let t=e.trim();if(!t)throw Error(`Topic segmentation model returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t;return JSON.parse(r)}[`You maintain SeCom-style conversation segments for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"action":"merge|split","reason":"...","topicLabel":"optional","summary":"...","compressedSummary":"...","keywords":["..."]}`,`Task: compare the active segment with the new user turn.`,`Use action=merge only when the new turn continues the same topic, task, artifact, bug, document, or refinement thread.`,`Use action=split when the new turn starts a different topic.`,`Always provide summary, compressedSummary, and concise keywords for the resulting segment after your decision.`,`Do not answer the user.`].join(`
43
+ `);const Fl=[`You select relevant conversation segments for an IM assistant before final turn-level topic classification.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedSegmentIds":["..."],"reason":"...","confidence":"high|medium|low"}`,`Task: choose which prior segments are relevant to the current user message.`,`Relevant includes same task continuation, explicit topic return, reuse of prior artifact, correction, or combining multiple earlier topics.`,`Prefer recall over over-pruning when the user explicitly refers to older topics by name.`,`Do not answer the user.`].join(`
44
+ `),Il=[`You select relevant historical conversation turns for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurns":[{"turnId":"...","summary":"...","topicLabel":"optional","keywords":["..."]}],"reason":"...","confidence":"high|medium|low"}`,`Task: from the provided turns, select any turn that may be relevant to the current user message.`,`This is recall-first. It is better to include possibly relevant turns than to miss a relevant one.`,`Select turns for same task continuation, explicit old-topic return, reuse of prior artifact, corrections, or combinations of multiple earlier topics.`,`For every selected turn, provide a concise reusable summary, an optional topicLabel, and short keywords.`,`Prefer the provided summary/topicLabel fields when they exist; use raw user/assistant content only when needed.`,`Do not answer the user.`].join(`
45
+ `);async function Ll(e){let t=Hl(e);if(t)try{let e=await V.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(iu);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function Rl(e){let t=Hl(e);t&&(await V.mkdir(H.dirname(t),{recursive:!0}),await V.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function zl(e){let t=Ul(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||Wl(t,e)){r.push(e);continue}n.push(Kl(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(Kl(r,n.length+1,!0)),n}function Bl(e,t){let n=Ul(t);if(n.length===0)return[];if(!e||e.length===0)return zl(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return zl(t);if(r.length===n.length)return e;let a=e.map(e=>({...e,turnIds:[...e.turnIds],toolNames:[...e.toolNames],keywords:[...e.keywords]})),o=n.slice(r.length);for(let e of o){let t=a[a.length-1];if(t&&Gl(t,e)){a[a.length-1]=Zl(t,e);continue}t&&(t.status=`closed`),a.push(Kl([e],a.length+1,!0))}if(a.length>1){for(let e=0;e<a.length-1;e+=1)a[e]={...a[e],status:`closed`};a[a.length-1]={...a[a.length-1],status:`active`}}return a}function Vl(e,t){if(!e||e.length===0||t.length===0)return e??[];let n=new Map(t.map(e=>[e.turnId,e])),r=!1,i=e.map(e=>{let t=new Map((e.turnMemories??[]).map(e=>[e.turnId,e])),i=!1;for(let r of e.turnIds){let e=n.get(r);if(!e)continue;let a=t.get(r);(!a||a.summary!==e.summary||a.topicLabel!==e.topicLabel||a.keywords.join(`|`)!==e.keywords.join(`|`))&&(t.set(r,e),i=!0)}if(!i)return e;r=!0;let a=[...t.values()].sort((e,t)=>e.turnId.localeCompare(t.turnId)),o=a.find(t=>e.turnIds.includes(t.turnId)),s=[...new Set([...e.keywords,...a.flatMap(e=>e.keywords)])];return{...e,keywords:s,topicLabel:o?.topicLabel??e.topicLabel,turnMemories:a,updatedAt:o?.updatedAt??e.updatedAt}});return r?i:e}function Hl(e){if(!(!e.dataDir||!e.sessionId))return H.join(d(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function Ul(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,user:a.content,timestamp:a.timestamp,toolNames:[]};continue}if(n){if(n.endIndex=i,a.role===`assistant`){let e=(a.content||a.errorMessage||``).trim();e&&(n.assistant=e);for(let e of a.toolCalls??[])n.toolNames.push(e.name);continue}a.role===`tool_result`&&n.toolNames.push(a.toolName)}}return r(),t.map(e=>({...e,toolNames:[...new Set(e.toolNames)].sort()}))}function Wl(e,t){return eu($l(e.user,e.assistant),$l(t.user,t.assistant))>0}function Gl(e,t){return eu($l(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),$l(t.user,t.assistant,t.toolNames.join(` `)))>0}function Kl(e,t,n){return ql(e,t,n)}function ql(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=Jl(e,o),c=ru(r?.summary||s),l=Ql(r?.keywords,c,o),u=ru(r?.compressedSummary||Xl(c,o));return{version:1,segmentId:`segment-${t}`,turnIds:e.map(e=>e.turnId),startTurnId:i.turnId,endTurnId:a.turnId,startIndex:i.startIndex,endIndex:a.endIndex,userSummary:e.map(e=>e.user).join(`
51
46
  `),assistantSummary:e.map(e=>e.assistant).filter(Boolean).join(`
52
- `)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function du(e,t){return fu(e.map(e=>e.user.trim()).filter(Boolean).slice(0,2).join(` / `),e.map(e=>e.assistant?.trim()).filter(Boolean).slice(-2).join(` / `)||void 0,t)}function fu(e,t,n){let r=yu(e,220),i=t?yu(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return bu(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function pu(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return bu(`Relevant prior segment: ${yu(e,280)}${n}`)}function mu(e,t,n){let r=[...new Set([...e.toolNames,...t.toolNames])].sort(),i=`${e.userSummary}\n${t.user}`.trim(),a=[e.assistantSummary,t.assistant].filter(Boolean).join(`
53
- `)||void 0,o=fu(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:bu(n?.summary||o),compressedSummary:bu(n?.compressedSummary||pu(n?.summary||o,r)),keywords:hu(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function hu(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:vu(t,n)}function gu(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||n.length>64||/^(.)\1{15,}$/u.test(n)||t.add(n)}return t}function _u(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function vu(e,t){let n=new Set([`the`,`and`,`for`,`with`,`this`,`that`,`from`,`user`,`intents`,`outcomes`,`tools`,`prior`,`segment`,`relevant`,`继续`,`刚才`,`这个`]),r=new Map;for(let i of gu(e,t.join(` `)))n.has(i)||r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,8).map(([e])=>e)}function yu(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function bu(e){return e.replace(/\s+/g,` `).trim()}function xu(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.segmentId==`string`&&Array.isArray(t.turnIds)&&typeof t.startTurnId==`string`&&typeof t.endTurnId==`string`&&typeof t.startIndex==`number`&&typeof t.endIndex==`number`&&typeof t.userSummary==`string`&&typeof t.summary==`string`&&typeof t.compressedSummary==`string`&&Array.isArray(t.keywords)&&Array.isArray(t.toolNames)&&(t.turnMemories===void 0||Array.isArray(t.turnMemories)&&t.turnMemories.every(e=>!!e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`&&Array.isArray(e.keywords)&&typeof e.updatedAt==`string`))&&(t.status===`active`||t.status===`closed`)&&typeof t.updatedAt==`string`}function Su(e){let t=Eu(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Du(t,n,r,e.segments.length,e.vectorScores)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.segment.startIndex-e.segment.startIndex:t.score-e.score:e.forced?-1:1).slice(0,e.maxSegments)}function Cu(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function wu(e){let t=new Set(e.selectedTurnIds),n=new Set(e.recentProtectedTurnIds),r=[];for(let i of e.segments){let a=i.turnIds.some(e=>t.has(e)),o=i.turnIds.some(e=>n.has(e));!a||o||i.status!==`closed`||r.push({role:`assistant`,content:Tu(i.compressedSummary),timestamp:e.timestamp})}return r}function Tu(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function Eu(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Du(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=Eu(t.summary,t.compressedSummary,t.keywords.join(` `),t.topicLabel,a),s=0;for(let t of e)o.has(t)&&(s+=1);let c=Math.max(0,i?.get(t.segmentId)??0),l=(n+1)/Math.max(r,1);return c*30+s*10+l}const Ou=`Xenova/bge-small-zh-v1.5`;let ku,Au;const ju=new Map;async function Mu(e,t){if(e.length===0)return[];let n=Lu(t),r=await Fu({embeddingModelDir:n}),i=[];for(let t of e){let e=t.trim();if(!e){i.push([]);continue}let a=`${n}\0${e}`,o=ju.get(a);if(o){i.push(o);continue}let s=await r(e,{pooling:`mean`,normalize:!0}),c=Array.from(s.data??[]);ju.set(a,c),i.push(c)}return i}async function Nu(e,t){let[n]=await Mu([e],t);return n??[]}function Pu(){return Ou}async function Fu(e){let t=Lu(e);return(!ku||Au!==t)&&(Au=t,ku=Iu(t)),ku}async function Iu(e){let{env:t,pipeline:n}=await import(`@huggingface/transformers`);return t.allowRemoteModels=!1,t.localModelPath=e,await n(`feature-extraction`,Ou,{dtype:`q8`})}function Lu(e){let t=e?.embeddingModelDir?.trim();if(t)return t;let n=process.env.AIMAX_TOPIC_SEGMENTATION_MODEL_DIR?.trim();if(n)return n;let r=G.dirname(gt(import.meta.url)),i=G.resolve(r,`../../../../../model`);if(K.existsSync(i))return i;let a=G.resolve(process.cwd(),`model`);return K.existsSync(a)?a:i}const Ru=`topic_segments_vec`,zu=`topic_segments_meta`,Bu=`topic_segment_embedding_cache`;async function Vu(e){let t=Uu(e);if(!t)return;await W.mkdir(G.dirname(t),{recursive:!0});let n=ue(t,{allowExtension:!0});try{let t=await Gu(n),r=n.prepare(`SELECT segment_id, content_hash FROM ${zu}`).all(),i=new Map(r.map(e=>[e.segment_id,e.content_hash])),a=Pu(),o=new Set(e.segments.map(e=>e.segmentId)),s=e.segments.filter(e=>{let t=oe(Wu(e));return i.get(e.segmentId)!==t}),c=s.length>0?await Mu(s.map(e=>Wu(e)),{embeddingModelDir:e.embeddingModelDir}):[];n.exec(`BEGIN`);try{for(let r of e.segments){let e=Wu(r),i=oe(e),o=s.findIndex(e=>e.segmentId===r.segmentId),l=o>=0?c[o]??[]:Xu(n,r.segmentId);Ju(n,{segment:r,contentText:e,contentHash:i,embeddingModel:a}),l.length>0?(Yu(n,{segmentId:r.segmentId,contentHash:i,embeddingModel:a,embedding:l}),t.vectorAvailable&&(qu(n,t,l.length),n.prepare(`DELETE FROM ${Ru} WHERE segment_id = ?`).run(r.segmentId),n.prepare(`INSERT INTO ${Ru} (segment_id, embedding) VALUES (?, ?)`).run(r.segmentId,nd(l)))):t.vectorAvailable&&n.prepare(`DELETE FROM ${Ru} WHERE segment_id = ?`).run(r.segmentId)}for(let e of r)o.has(e.segment_id)||(n.prepare(`DELETE FROM ${zu} WHERE segment_id = ?`).run(e.segment_id),n.prepare(`DELETE FROM ${Bu} WHERE segment_id = ?`).run(e.segment_id),t.vectorAvailable&&n.prepare(`DELETE FROM ${Ru} WHERE segment_id = ?`).run(e.segment_id));n.exec(`COMMIT`)}catch(e){throw n.exec(`ROLLBACK`),e}}finally{n.close()}}async function Hu(e){if(!e.query.trim()||e.limit<=0)return new Map;let t=Uu(e);if(!t)return new Map;try{await W.access(t)}catch{return new Map}let n=await $u(e.query,{embeddingModelDir:e.embeddingModelDir});if(n.length===0)return new Map;let r=ue(t,{allowExtension:!0});try{let t=await Gu(r),i=Pu(),a=t.vectorAvailable&&t.vectorDims===n.length?Zu(r,i,n,e.limit):Qu(r,i,n,e.limit);return new Map(a.map(e=>[e.segment_id,Math.max(0,e.score??0)]))}finally{r.close()}}function Uu(e){if(!(!e.dataDir||!e.sessionId))return G.join(d(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function Wu(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
54
- `)}async function Gu(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${zu} (\n segment_id TEXT PRIMARY KEY,\n version INTEGER NOT NULL,\n content_text TEXT NOT NULL,\n content_hash TEXT NOT NULL,\n embedding_model TEXT,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE TABLE IF NOT EXISTS ${Bu} (\n segment_id TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n embedding_model TEXT NOT NULL,\n embedding TEXT NOT NULL,\n dims INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${zu}_hash ON ${zu}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Bu}_hash ON ${Bu}(content_hash)`),{vectorAvailable:(await ie({db:e})).ok,vectorDims:Ku(e)}}function Ku(e){let t=e.prepare(`SELECT dims FROM ${Bu} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function qu(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${Ru}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${Ru} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function Ju(e,t){e.prepare(`INSERT INTO ${zu} (\n segment_id, version, content_text, content_hash, embedding_model, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n version = excluded.version,\n content_text = excluded.content_text,\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n updated_at = excluded.updated_at`).run(t.segment.segmentId,1,t.contentText,t.contentHash,t.embeddingModel,t.segment.updatedAt)}function Yu(e,t){e.prepare(`INSERT INTO ${Bu} (\n segment_id, content_hash, embedding_model, embedding, dims, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n embedding = excluded.embedding,\n dims = excluded.dims,\n updated_at = excluded.updated_at`).run(t.segmentId,t.contentHash,t.embeddingModel,JSON.stringify(t.embedding),t.embedding.length,new Date().toISOString())}function Xu(e,t){let n=e.prepare(`SELECT embedding FROM ${Bu} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function Zu(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${Ru} v\n JOIN ${zu} m ON m.segment_id = v.segment_id\n WHERE m.embedding_model = ?\n ORDER BY vec_distance_cosine(v.embedding, ?) ASC\n LIMIT ?`).all(nd(n),t,nd(n),r)}function Qu(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${Bu} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:td(n,ed(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function $u(e,t){try{return await Nu(e,t)}catch{return[]}}function ed(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function td(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a]??0,s=t[a]??0;n+=o*s,r+=o*o,i+=s*s}return r<=0||i<=0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function nd(e){return Buffer.from(new Float32Array(e).buffer)}const rd=8e3,id=new Map;function ad(e){return{enabled:e?.enabled!==!1,embeddingModelDir:vd(e?.embeddingModelDir),minUserTurns:e?.minUserTurns??4,minEstimatedTokens:e?.minEstimatedTokens??4e3,recentProtectedTurnCount:e?.recentProtectedTurnCount??2,maxCandidates:e?.maxCandidates??40,maxSelectedTurns:e?.maxSelectedTurns??8,maxShortlistCandidates:e?.maxShortlistCandidates??12,maxShortlistSegments:e?.maxShortlistSegments??6,maxCandidateUserChars:e?.maxCandidateUserChars??600,maxCandidateAssistantChars:e?.maxCandidateAssistantChars??1e3,timeoutMs:e?.timeoutMs??2e4,maxTokens:e?.maxTokens??4096}}function od(e){let t=fd(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=new Set;if(e.useCompressedSegmentMemory!==!1&&e.segmentRecords)for(let t of e.segmentRecords){let e=t.turnIds.some(e=>n.has(e)),r=t.turnIds.some(e=>i.includes(e));if(!(!e||r||t.status!==`closed`))for(let e of t.turnIds)a.add(e)}let o=[],s=[],c=[];for(let e of t){if(!n.has(e.turnId)){c.push(e.turnId);continue}o.push({turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex}),!a.has(e.turnId)&&s.push(...e.entries)}return{entries:[...e.useCompressedSegmentMemory!==!1&&e.segmentRecords?wu({selectedTurnIds:[...n],segments:e.segmentRecords,recentProtectedTurnIds:i,timestamp:new Date().toISOString()}):[],...s],recentTurnIds:i,selectedRanges:o,droppedTurnIds:c}}function sd(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=yd(e.currentUserMessage),n=new Set(e.recentProtectedTurnCount>0?e.candidates.slice(-e.recentProtectedTurnCount).map(e=>e.turnId):[]);return e.candidates.map((r,i)=>({candidate:r,index:i,forced:n.has(r.turnId),score:xd(t,r,i,e.candidates.length)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.index-e.index:t.score-e.score:e.forced?-1:1).slice(0,e.maxShortlist).map(e=>e.candidate).sort((e,t)=>e.startIndex-t.startIndex)}async function cd(e){let t=ad(e.config),n=()=>wd({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){Y.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){Y.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){Y.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=fd(e.entries),i=$(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){Y.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>pd(e,t)),o=e.llm.flashModel||e.llm.model,s=await ld({entries:e.entries,candidates:a,pendingUserMessage:e.pendingUserMessage,config:t,llm:{apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,model:o,timeoutMs:t.timeoutMs,maxTokens:t.maxTokens},dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.config.embeddingModelDir,signal:e.signal}),c=s.segmentRecords,l=new Set(a.map(e=>e.turnId)),u=new Date().toISOString(),d=Date.now();Y.info(`topic segmentation classify started`,wd({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=hd({currentUserMessage:e.pendingUserMessage,allCandidates:a,shortlistedCandidates:s.candidates,selectedSegmentIds:s.selectedSegmentIds,supplementalTurnIds:s.supplementalTurnIds,segmentRecords:c,recentProtectedTurnCount:t.recentProtectedTurnCount,maxSelectedTurns:t.maxSelectedTurns}),p=f.selectedTurnIds.filter(e=>!l.has(e));if(p.length>0)throw Error(`Local topic segmentation returned unknown turn ids: ${p.join(`, `)}`);let m=Date.now()-d,h=od({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=md({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:$(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await gd(e,g),Y.info(`topic segmentation classify succeeded`,{...wd({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}),durationMs:m,selectedTurnCount:f.selectedTurnIds.length,confidence:f.confidence,tokenEstimateAfter:g.tokenEstimate?.after,droppedTurnCount:h.droppedTurnIds.length}),{entries:h.entries,audit:g}}async function ld(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await ud({entries:e.entries,llm:e.llm,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,signal:e.signal}),n=e.config.recentProtectedTurnCount>0?e.candidates.slice(-e.config.recentProtectedTurnCount).map(e=>e.turnId):[],r=Date.now(),i=[],a=e.candidates,o=t,s=[],c=[];if(t){let o=await Hu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.config.embeddingModelDir,query:e.pendingUserMessage,limit:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2)}),l=Su({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=Ed(l,e.config.maxShortlistSegments),d=dd({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:rd});if(d&&Md({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await Fd({currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,retrieved:l,llm:{...e.llm,timeoutMs:d},maxSelectedSegments:e.config.maxShortlistSegments,signal:e.signal});t.length>0&&(u=t)}s=u,i=u.map(e=>e.segment.segmentId),a=Cu({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Dd({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:rd,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await tu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),Id({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.config.embeddingModelDir,segments:l.updatedSegments})));let u=jd(a,l.selectedCandidates),d=sd({currentUserMessage:e.pendingUserMessage,candidates:u.length>0?u:a,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxShortlist:Math.min(e.config.maxCandidates,e.config.maxShortlistCandidates)});return{candidates:d.length>0?d:e.candidates,selectedSegmentIds:i,supplementalTurnIds:l.selectedTurnIds,segmentRecords:o}}async function ud(e){let t=await eu(e);if(!t){let t=nu(e.entries);return t.length===0?void 0:(await tu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),Id({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),t)}let n=ru(t,e.entries);return n.length>0&&(await tu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),Id({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n})),n}function dd(e){let t=Math.max(0,(e.nowMs??Date.now())-e.budgetStartedAtMs),n=Math.max(0,e.budgetMs-t);if(!(n<=0))return Math.min(e.requestTimeoutMs,n)}function fd(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 pd(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}Cd(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:_d(e.user,t.maxCandidateUserChars),assistant:n?_d((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function md(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:_d(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,shortlistCount:e.shortlistedCandidates.candidates.length,selectedSegmentIds:e.selectedSegmentIds,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 hd(e){let t=new Set(e.allCandidates.map(e=>e.turnId)),n=new Set;if(e.segmentRecords&&e.selectedSegmentIds.length>0){let r=e.segmentRecords.filter(t=>e.selectedSegmentIds.includes(t.segmentId));for(let e of r)for(let r of e.turnIds)t.has(r)&&n.add(r)}for(let r of e.supplementalTurnIds)t.has(r)&&n.add(r);if(n.size===0){let t=yd(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:xd(t,n,r,e.shortlistedCandidates.length)})).sort((e,t)=>t.score-e.score),i=r[0]?.score??0,a=Math.max(8,i>=8?i*.7:1/0);for(let t of r)if(!(t.score<a)&&(n.add(t.candidate.turnId),n.size>=e.maxSelectedTurns))break}return{version:1,selectedTurnIds:[...n].slice(0,e.maxSelectedTurns),reason:e.selectedSegmentIds.length>0||e.supplementalTurnIds.length>0?`local segment retrieval matched prior segments`:`local candidate scoring matched recent turns`,confidence:`high`}}async function gd(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 _d(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function vd(e){return e?.trim()||void 0}function yd(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function bd(e){return[...yd(e)].slice(0,8)}function xd(e,t,n,r){let i=Sd(e,yd(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Sd(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Cd(e){return e.role===`tool_result`}function wd(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Td(e.params.llm.baseUrl),timeoutMs:e.config.timeoutMs,maxTokens:e.config.maxTokens,minUserTurns:e.config.minUserTurns,minEstimatedTokens:e.config.minEstimatedTokens,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxCandidates:e.config.maxCandidates,maxSelectedTurns:e.config.maxSelectedTurns,transcriptEntryCount:e.params.fullTranscript.length,workingEntryCount:e.params.entries.length,pendingUserMessageChars:e.params.pendingUserMessage?.length,candidateCount:e.candidates?.length,shortlistCount:e.shortlistedCandidates?.length,tokenEstimateBefore:e.tokenEstimateBefore,extraPromptChars:e.extraPromptChars}}function Td(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function Ed(e,t){if(e.length===0)return[];let n=e.slice().sort((e,t)=>t.score-e.score),r=n[0]?.score??0,i=Math.max(8,r>=8?r*.7:1/0);return n.filter(e=>e.forced||e.score>=i).slice(0,t)}async function Dd(e){if(!Od(e))return{selectedCandidates:[],selectedTurnIds:[]};let t=new Set(e.segmentFilteredCandidates.map(e=>e.turnId)),n=new Set(e.recentProtectedTurnIds),r=e.allCandidates.filter(e=>!t.has(e.turnId)&&!n.has(e.turnId));if(r.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let i=kd(Ad(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=dd({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await Jl({currentUserMessage:e.currentUserMessage,turns:i,maxSelectedTurns:e.config.maxSelectedTurns,recentProtectedTurnIds:e.recentProtectedTurnIds,llm:{...e.llm,timeoutMs:a},signal:e.signal}),n=[...new Set(t.selectedTurns.map(e=>e.turnId))].filter(e=>r.some(t=>t.turnId===e));if(n.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let o=r.filter(e=>n.includes(e.turnId)),s=t.selectedTurns.filter(e=>n.includes(e.turnId)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:e.topicLabel?.trim()||void 0,keywords:(e.keywords??bd(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?iu(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Od(e){let t=e.selectedSegments.filter(e=>!e.forced);return Nd(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:Pd(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function kd(e,t){let n=new Map;for(let e of t??[])for(let t of e.turnIds)n.set(t,e);return e.map(e=>{let t=n.get(e.turnId),r=t?.turnMemories?.find(t=>t.turnId===e.turnId);return{turnId:e.turnId,user:e.user,assistant:e.assistant,toolNames:e.toolNames,hasErrors:e.hasErrors,summary:r?.summary??t?.summary,topicLabel:r?.topicLabel??t?.topicLabel,keywords:r?.keywords??t?.keywords}})}function Ad(e,t,n){let r=Math.max(n.length,1),i=yd(t);return e.map(e=>({candidate:e,score:xd(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function jd(...e){let t=new Map;for(let n of e)for(let e of n)t.has(e.turnId)||t.set(e.turnId,e);return[...t.values()].sort((e,t)=>e.startIndex-t.startIndex)}function Md(e){if(e.retrieved.length<2||!Nd(e.currentUserMessage))return!1;let t=new Set(e.selected.map(e=>e.segment.segmentId));if(e.selected.filter(e=>!e.forced).length>=2||e.retrieved.filter(e=>!e.forced).length<2)return!1;let n=new Set(e.selected.flatMap(e=>e.segment.turnIds));return e.recentProtectedTurnIds.length>0&&[...n].every(t=>e.recentProtectedTurnIds.includes(t))||t.size<2}function Nd(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function Pd(e){let t=e.toLowerCase();return/(回到|刚才|前面|之前|上次|那个|前一个|最早|继续刚才)/u.test(t)?!0:/\b(back to|earlier|previous|that earlier|the earlier)\b/i.test(t)}async function Fd(e){try{let t=await ql({currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.retrieved.map(e=>({segmentId:e.segment.segmentId,turnIds:e.segment.turnIds,summary:e.segment.summary,compressedSummary:e.segment.compressedSummary,keywords:e.segment.keywords,toolNames:e.segment.toolNames,topicLabel:e.segment.topicLabel})),llm:e.llm,signal:e.signal}),n=new Set(t.selectedSegmentIds);return n.size===0?[]:e.retrieved.filter(e=>n.has(e.segment.segmentId))}catch{return[]}}function Id(e){let t=Ld(e);if(!t||id.has(t))return;let n=Vu(e).catch(()=>{}).finally(()=>{id.delete(t)});id.set(t,n)}function Ld(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`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(`
55
- `);const Rd=[`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 zd(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 Wd(t);for(let e of p.readStates)n.set(Bd(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=Bd(e,t,r),a=n.get(i);if(!a)return null;let o=await Hd(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:Ud(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await Hd(e.path)??Date.now()};return n.set(Bd(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())Vd(i.path)===Vd(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=Jd(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:qd(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 Yd(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 Bd(e,t,n){return`${Vd(e)}::${t??``}::${n??``}`}function Vd(e){return G.normalize(e)}async function Hd(e){try{return(await W.stat(e)).mtimeMs}catch{return null}}function Ud(e){return Je(`sha1`).update(e).digest(`hex`)}async function Wd(e){try{let t=await l(e);if(t===null)return Gd();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?Gd():{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:Kd(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 Gd()}}function Gd(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Kd(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 qd(e){let t=e.preview.length<e.originalChars?`
56
- ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...Rd,`Preview:`,e.preview+t].join(`
57
- `)}function Jd(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
58
- `),r=n>t*.5?n:t;return e.slice(0,r)}async function Yd(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 Xd=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Zd(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=uf(t),x=b>=0?t.slice(b+1):t;b>=0&&(y=t[b].content);let S=t.length,C=Sl(zl(x,a)),w=[],T=(await cd({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 Qd({entries:T,existingSummary:y,llm:i,contextStore:f,signal:l,hooks:u,hookCtx:d}));let E=T;if(E=await $d({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:w}),E=await ef({entries:E,contextStore:f,compactionEvents:w}),E=await tf({entries:E,contextStore:f,compactionEvents:w,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g}),!o)return{messages:Hl(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=df({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:D?.compaction.modelUsage}).projectedInputTokens>=O,ee=D?.compaction.consecutiveAutocompactFailures??0;if(!k||ee>=3)return{messages:Hl(E,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:E.length,estimatedTokens:$(E),compacted:!1},compactionEvents:w};let{toKeep:A,toSummarise:j}=xl(E,r);if(j.length===0)return{messages:Hl(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 hl({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:Hl(Sl(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:Hl(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 Qd(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&&lf(t)>=3;if(!u&&!d)return n??l?.summary;let f=await hl({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 $d(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(rf).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(!rf(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=af(n)?of(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
59
- `);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}),Sl(l.reverse())}async function ef(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(!rf(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=af(r)?of(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(`
60
- `);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}),$d({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function tf(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(rf).filter(e=>Xd.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=nf(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:Ye(),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 ff(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 nf(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(`
47
+ `)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function Jl(e,t){return Yl(e.map(e=>e.user.trim()).filter(Boolean).slice(0,2).join(` / `),e.map(e=>e.assistant?.trim()).filter(Boolean).slice(-2).join(` / `)||void 0,t)}function Yl(e,t,n){let r=nu(e,220),i=t?nu(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return ru(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function Xl(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return ru(`Relevant prior segment: ${nu(e,280)}${n}`)}function Zl(e,t,n){let r=[...new Set([...e.toolNames,...t.toolNames])].sort(),i=`${e.userSummary}\n${t.user}`.trim(),a=[e.assistantSummary,t.assistant].filter(Boolean).join(`
48
+ `)||void 0,o=Yl(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:ru(n?.summary||o),compressedSummary:ru(n?.compressedSummary||Xl(n?.summary||o,r)),keywords:Ql(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Ql(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:tu(t,n)}function $l(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||n.length>64||/^(.)\1{15,}$/u.test(n)||t.add(n)}return t}function eu(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function tu(e,t){let n=new Set([`the`,`and`,`for`,`with`,`this`,`that`,`from`,`user`,`intents`,`outcomes`,`tools`,`prior`,`segment`,`relevant`,`继续`,`刚才`,`这个`]),r=new Map;for(let i of $l(e,t.join(` `)))n.has(i)||r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,8).map(([e])=>e)}function nu(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function ru(e){return e.replace(/\s+/g,` `).trim()}function iu(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.segmentId==`string`&&Array.isArray(t.turnIds)&&typeof t.startTurnId==`string`&&typeof t.endTurnId==`string`&&typeof t.startIndex==`number`&&typeof t.endIndex==`number`&&typeof t.userSummary==`string`&&typeof t.summary==`string`&&typeof t.compressedSummary==`string`&&Array.isArray(t.keywords)&&Array.isArray(t.toolNames)&&(t.turnMemories===void 0||Array.isArray(t.turnMemories)&&t.turnMemories.every(e=>!!e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`&&Array.isArray(e.keywords)&&typeof e.updatedAt==`string`))&&(t.status===`active`||t.status===`closed`)&&typeof t.updatedAt==`string`}function au(e){let t=lu(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:uu(t,n,r,e.segments.length,e.vectorScores)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.segment.startIndex-e.segment.startIndex:t.score-e.score:e.forced?-1:1).slice(0,e.maxSegments)}function ou(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function su(e){let t=new Set(e.selectedTurnIds),n=new Set(e.recentProtectedTurnIds),r=[];for(let i of e.segments){let a=i.turnIds.some(e=>t.has(e)),o=i.turnIds.some(e=>n.has(e));!a||o||i.status!==`closed`||r.push({role:`assistant`,content:cu(i.compressedSummary),timestamp:e.timestamp})}return r}function cu(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function lu(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function uu(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=lu(t.summary,t.compressedSummary,t.keywords.join(` `),t.topicLabel,a),s=0;for(let t of e)o.has(t)&&(s+=1);let c=Math.max(0,i?.get(t.segmentId)??0),l=(n+1)/Math.max(r,1);return c*30+s*10+l}const du=`Xenova/bge-small-zh-v1.5`;let fu,pu;const mu=new Map;async function hu(e,t){if(e.length===0)return[];let n=bu(t),r=await vu({embeddingModelDir:n}),i=[];for(let t of e){let e=t.trim();if(!e){i.push([]);continue}let a=`${n}\0${e}`,o=mu.get(a);if(o){i.push(o);continue}let s=await r(e,{pooling:`mean`,normalize:!0}),c=Array.from(s.data??[]);mu.set(a,c),i.push(c)}return i}async function gu(e,t){let[n]=await hu([e],t);return n??[]}function _u(){return du}async function vu(e){let t=bu(e);return(!fu||pu!==t)&&(pu=t,fu=yu(t)),fu}async function yu(e){let{env:t,pipeline:n}=await import(`@huggingface/transformers`);return t.allowRemoteModels=!1,t.localModelPath=e,await n(`feature-extraction`,du,{dtype:`q8`})}function bu(e){let t=e?.embeddingModelDir?.trim();if(t)return t;let n=process.env.AIMAX_TOPIC_SEGMENTATION_MODEL_DIR?.trim();if(n)return n;let r=H.dirname(yt(import.meta.url)),i=H.resolve(r,`../../../../../model`);if(U.existsSync(i))return i;let a=H.resolve(process.cwd(),`model`);return U.existsSync(a)?a:i}const xu=`topic_segments_vec`,Su=`topic_segments_meta`,Q=`topic_segment_embedding_cache`;async function Cu(e){let t=Tu(e);if(!t)return;await V.mkdir(H.dirname(t),{recursive:!0});let n=fe(t,{allowExtension:!0});try{let t=await Du(n),r=n.prepare(`SELECT segment_id, content_hash FROM ${Su}`).all(),i=new Map(r.map(e=>[e.segment_id,e.content_hash])),a=_u(),o=new Set(e.segments.map(e=>e.segmentId)),s=e.segments.filter(e=>{let t=ce(Eu(e));return i.get(e.segmentId)!==t}),c=s.length>0?await hu(s.map(e=>Eu(e)),{embeddingModelDir:e.embeddingModelDir}):[];n.exec(`BEGIN`);try{for(let r of e.segments){let e=Eu(r),i=ce(e),o=s.findIndex(e=>e.segmentId===r.segmentId),l=o>=0?c[o]??[]:Mu(n,r.segmentId);Au(n,{segment:r,contentText:e,contentHash:i,embeddingModel:a}),l.length>0?(ju(n,{segmentId:r.segmentId,contentHash:i,embeddingModel:a,embedding:l}),t.vectorAvailable&&(ku(n,t,l.length),n.prepare(`DELETE FROM ${xu} WHERE segment_id = ?`).run(r.segmentId),n.prepare(`INSERT INTO ${xu} (segment_id, embedding) VALUES (?, ?)`).run(r.segmentId,Ru(l)))):t.vectorAvailable&&n.prepare(`DELETE FROM ${xu} WHERE segment_id = ?`).run(r.segmentId)}for(let e of r)o.has(e.segment_id)||(n.prepare(`DELETE FROM ${Su} WHERE segment_id = ?`).run(e.segment_id),n.prepare(`DELETE FROM ${Q} WHERE segment_id = ?`).run(e.segment_id),t.vectorAvailable&&n.prepare(`DELETE FROM ${xu} WHERE segment_id = ?`).run(e.segment_id));n.exec(`COMMIT`)}catch(e){throw n.exec(`ROLLBACK`),e}}finally{n.close()}}async function wu(e){if(!e.query.trim()||e.limit<=0)return new Map;let t=Tu(e);if(!t)return new Map;try{await V.access(t)}catch{return new Map}let n=await Fu(e.query,{embeddingModelDir:e.embeddingModelDir});if(n.length===0)return new Map;let r=fe(t,{allowExtension:!0});try{let t=await Du(r),i=_u(),a=t.vectorAvailable&&t.vectorDims===n.length?Nu(r,i,n,e.limit):Pu(r,i,n,e.limit);return new Map(a.map(e=>[e.segment_id,Math.max(0,e.score??0)]))}finally{r.close()}}function Tu(e){if(!(!e.dataDir||!e.sessionId))return H.join(d(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function Eu(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
49
+ `)}async function Du(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${Su} (\n segment_id TEXT PRIMARY KEY,\n version INTEGER NOT NULL,\n content_text TEXT NOT NULL,\n content_hash TEXT NOT NULL,\n embedding_model TEXT,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE TABLE IF NOT EXISTS ${Q} (\n segment_id TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n embedding_model TEXT NOT NULL,\n embedding TEXT NOT NULL,\n dims INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Su}_hash ON ${Su}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Q}_hash ON ${Q}(content_hash)`),{vectorAvailable:(await oe({db:e})).ok,vectorDims:Ou(e)}}function Ou(e){let t=e.prepare(`SELECT dims FROM ${Q} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function ku(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${xu}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${xu} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function Au(e,t){e.prepare(`INSERT INTO ${Su} (\n segment_id, version, content_text, content_hash, embedding_model, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n version = excluded.version,\n content_text = excluded.content_text,\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n updated_at = excluded.updated_at`).run(t.segment.segmentId,1,t.contentText,t.contentHash,t.embeddingModel,t.segment.updatedAt)}function ju(e,t){e.prepare(`INSERT INTO ${Q} (\n segment_id, content_hash, embedding_model, embedding, dims, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n embedding = excluded.embedding,\n dims = excluded.dims,\n updated_at = excluded.updated_at`).run(t.segmentId,t.contentHash,t.embeddingModel,JSON.stringify(t.embedding),t.embedding.length,new Date().toISOString())}function Mu(e,t){let n=e.prepare(`SELECT embedding FROM ${Q} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function Nu(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${xu} v\n JOIN ${Su} m ON m.segment_id = v.segment_id\n WHERE m.embedding_model = ?\n ORDER BY vec_distance_cosine(v.embedding, ?) ASC\n LIMIT ?`).all(Ru(n),t,Ru(n),r)}function Pu(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${Q} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:Lu(n,Iu(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function Fu(e,t){try{return await gu(e,t)}catch{return[]}}function Iu(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Lu(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a]??0,s=t[a]??0;n+=o*s,r+=o*o,i+=s*s}return r<=0||i<=0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function Ru(e){return Buffer.from(new Float32Array(e).buffer)}const zu=8e3,Bu=new Map;function Vu(e){return{enabled:e?.enabled!==!1,embeddingModelDir:ed(e?.embeddingModelDir),minUserTurns:e?.minUserTurns??4,minEstimatedTokens:e?.minEstimatedTokens??4e3,recentProtectedTurnCount:e?.recentProtectedTurnCount??2,maxCandidates:e?.maxCandidates??40,maxSelectedTurns:e?.maxSelectedTurns??8,maxShortlistCandidates:e?.maxShortlistCandidates??12,maxShortlistSegments:e?.maxShortlistSegments??6,maxCandidateUserChars:e?.maxCandidateUserChars??600,maxCandidateAssistantChars:e?.maxCandidateAssistantChars??1e3,timeoutMs:e?.timeoutMs??2e4,maxTokens:e?.maxTokens??4096}}function Hu(e){let t=Ju(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=new Set;if(e.useCompressedSegmentMemory!==!1&&e.segmentRecords)for(let t of e.segmentRecords){let e=t.turnIds.some(e=>n.has(e)),r=t.turnIds.some(e=>i.includes(e));if(!(!e||r||t.status!==`closed`))for(let e of t.turnIds)a.add(e)}let o=[],s=[],c=[];for(let e of t){if(!n.has(e.turnId)){c.push(e.turnId);continue}o.push({turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex}),!a.has(e.turnId)&&s.push(...e.entries)}return{entries:[...e.useCompressedSegmentMemory!==!1&&e.segmentRecords?su({selectedTurnIds:[...n],segments:e.segmentRecords,recentProtectedTurnIds:i,timestamp:new Date().toISOString()}):[],...s],recentTurnIds:i,selectedRanges:o,droppedTurnIds:c}}function Uu(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=td(e.currentUserMessage),n=new Set(e.recentProtectedTurnCount>0?e.candidates.slice(-e.recentProtectedTurnCount).map(e=>e.turnId):[]);return e.candidates.map((r,i)=>({candidate:r,index:i,forced:n.has(r.turnId),score:rd(t,r,i,e.candidates.length)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.index-e.index:t.score-e.score:e.forced?-1:1).slice(0,e.maxShortlist).map(e=>e.candidate).sort((e,t)=>e.startIndex-t.startIndex)}async function Wu(e){let t=Vu(e.config),n=()=>od({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){q.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){q.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){q.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=Ju(e.entries),i=Z(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){q.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>Yu(e,t)),o=e.llm.flashModel||e.llm.model,s=await Gu({entries:e.entries,candidates:a,pendingUserMessage:e.pendingUserMessage,config:t,llm:{apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,model:o,timeoutMs:t.timeoutMs,maxTokens:t.maxTokens},dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.config.embeddingModelDir,signal:e.signal}),c=s.segmentRecords,l=new Set(a.map(e=>e.turnId)),u=new Date().toISOString(),d=Date.now();q.info(`topic segmentation classify started`,od({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Zu({currentUserMessage:e.pendingUserMessage,allCandidates:a,shortlistedCandidates:s.candidates,selectedSegmentIds:s.selectedSegmentIds,supplementalTurnIds:s.supplementalTurnIds,segmentRecords:c,recentProtectedTurnCount:t.recentProtectedTurnCount,maxSelectedTurns:t.maxSelectedTurns}),p=f.selectedTurnIds.filter(e=>!l.has(e));if(p.length>0)throw Error(`Local topic segmentation returned unknown turn ids: ${p.join(`, `)}`);let m=Date.now()-d,h=Hu({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=Xu({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:Z(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await Qu(e,g),q.info(`topic segmentation classify succeeded`,{...od({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}),durationMs:m,selectedTurnCount:f.selectedTurnIds.length,confidence:f.confidence,tokenEstimateAfter:g.tokenEstimate?.after,droppedTurnCount:h.droppedTurnIds.length}),{entries:h.entries,audit:g}}async function Gu(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await Ku({entries:e.entries,llm:e.llm,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,signal:e.signal}),n=e.config.recentProtectedTurnCount>0?e.candidates.slice(-e.config.recentProtectedTurnCount).map(e=>e.turnId):[],r=Date.now(),i=[],a=e.candidates,o=t,s=[],c=[];if(t){let o=await wu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.config.embeddingModelDir,query:e.pendingUserMessage,limit:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2)}),l=au({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=cd(l,e.config.maxShortlistSegments),d=qu({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:zu});if(d&&md({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await _d({currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,retrieved:l,llm:{...e.llm,timeoutMs:d},maxSelectedSegments:e.config.maxShortlistSegments,signal:e.signal});t.length>0&&(u=t)}s=u,i=u.map(e=>e.segment.segmentId),a=ou({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await ld({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:zu,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await Rl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),vd({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.config.embeddingModelDir,segments:l.updatedSegments})));let u=pd(a,l.selectedCandidates),d=Uu({currentUserMessage:e.pendingUserMessage,candidates:u.length>0?u:a,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxShortlist:Math.min(e.config.maxCandidates,e.config.maxShortlistCandidates)});return{candidates:d.length>0?d:e.candidates,selectedSegmentIds:i,supplementalTurnIds:l.selectedTurnIds,segmentRecords:o}}async function Ku(e){let t=await Ll(e);if(!t){let t=zl(e.entries);return t.length===0?void 0:(await Rl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),vd({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),t)}let n=Bl(t,e.entries);return n.length>0&&(await Rl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),vd({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n})),n}function qu(e){let t=Math.max(0,(e.nowMs??Date.now())-e.budgetStartedAtMs),n=Math.max(0,e.budgetMs-t);if(!(n<=0))return Math.min(e.requestTimeoutMs,n)}function Ju(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 Yu(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}ad(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:$u(e.user,t.maxCandidateUserChars),assistant:n?$u((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function Xu(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:$u(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,shortlistCount:e.shortlistedCandidates.candidates.length,selectedSegmentIds:e.selectedSegmentIds,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 Zu(e){let t=new Set(e.allCandidates.map(e=>e.turnId)),n=new Set;if(e.segmentRecords&&e.selectedSegmentIds.length>0){let r=e.segmentRecords.filter(t=>e.selectedSegmentIds.includes(t.segmentId));for(let e of r)for(let r of e.turnIds)t.has(r)&&n.add(r)}for(let r of e.supplementalTurnIds)t.has(r)&&n.add(r);if(n.size===0){let t=td(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:rd(t,n,r,e.shortlistedCandidates.length)})).sort((e,t)=>t.score-e.score),i=r[0]?.score??0,a=Math.max(8,i>=8?i*.7:1/0);for(let t of r)if(!(t.score<a)&&(n.add(t.candidate.turnId),n.size>=e.maxSelectedTurns))break}return{version:1,selectedTurnIds:[...n].slice(0,e.maxSelectedTurns),reason:e.selectedSegmentIds.length>0||e.supplementalTurnIds.length>0?`local segment retrieval matched prior segments`:`local candidate scoring matched recent turns`,confidence:`high`}}async function Qu(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=d(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await V.mkdir(n,{recursive:!0}),await V.appendFile(H.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function $u(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function ed(e){return e?.trim()||void 0}function td(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function nd(e){return[...td(e)].slice(0,8)}function rd(e,t,n,r){let i=id(e,td(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function id(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function ad(e){return e.role===`tool_result`}function od(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:sd(e.params.llm.baseUrl),timeoutMs:e.config.timeoutMs,maxTokens:e.config.maxTokens,minUserTurns:e.config.minUserTurns,minEstimatedTokens:e.config.minEstimatedTokens,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxCandidates:e.config.maxCandidates,maxSelectedTurns:e.config.maxSelectedTurns,transcriptEntryCount:e.params.fullTranscript.length,workingEntryCount:e.params.entries.length,pendingUserMessageChars:e.params.pendingUserMessage?.length,candidateCount:e.candidates?.length,shortlistCount:e.shortlistedCandidates?.length,tokenEstimateBefore:e.tokenEstimateBefore,extraPromptChars:e.extraPromptChars}}function sd(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function cd(e,t){if(e.length===0)return[];let n=e.slice().sort((e,t)=>t.score-e.score),r=n[0]?.score??0,i=Math.max(8,r>=8?r*.7:1/0);return n.filter(e=>e.forced||e.score>=i).slice(0,t)}async function ld(e){if(!ud(e))return{selectedCandidates:[],selectedTurnIds:[]};let t=new Set(e.segmentFilteredCandidates.map(e=>e.turnId)),n=new Set(e.recentProtectedTurnIds),r=e.allCandidates.filter(e=>!t.has(e.turnId)&&!n.has(e.turnId));if(r.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let i=dd(fd(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=qu({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await jl({currentUserMessage:e.currentUserMessage,turns:i,maxSelectedTurns:e.config.maxSelectedTurns,recentProtectedTurnIds:e.recentProtectedTurnIds,llm:{...e.llm,timeoutMs:a},signal:e.signal}),n=[...new Set(t.selectedTurns.map(e=>e.turnId))].filter(e=>r.some(t=>t.turnId===e));if(n.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let o=r.filter(e=>n.includes(e.turnId)),s=t.selectedTurns.filter(e=>n.includes(e.turnId)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:e.topicLabel?.trim()||void 0,keywords:(e.keywords??nd(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?Vl(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function ud(e){let t=e.selectedSegments.filter(e=>!e.forced);return hd(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:gd(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function dd(e,t){let n=new Map;for(let e of t??[])for(let t of e.turnIds)n.set(t,e);return e.map(e=>{let t=n.get(e.turnId),r=t?.turnMemories?.find(t=>t.turnId===e.turnId);return{turnId:e.turnId,user:e.user,assistant:e.assistant,toolNames:e.toolNames,hasErrors:e.hasErrors,summary:r?.summary??t?.summary,topicLabel:r?.topicLabel??t?.topicLabel,keywords:r?.keywords??t?.keywords}})}function fd(e,t,n){let r=Math.max(n.length,1),i=td(t);return e.map(e=>({candidate:e,score:rd(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function pd(...e){let t=new Map;for(let n of e)for(let e of n)t.has(e.turnId)||t.set(e.turnId,e);return[...t.values()].sort((e,t)=>e.startIndex-t.startIndex)}function md(e){if(e.retrieved.length<2||!hd(e.currentUserMessage))return!1;let t=new Set(e.selected.map(e=>e.segment.segmentId));if(e.selected.filter(e=>!e.forced).length>=2||e.retrieved.filter(e=>!e.forced).length<2)return!1;let n=new Set(e.selected.flatMap(e=>e.segment.turnIds));return e.recentProtectedTurnIds.length>0&&[...n].every(t=>e.recentProtectedTurnIds.includes(t))||t.size<2}function hd(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function gd(e){let t=e.toLowerCase();return/(回到|刚才|前面|之前|上次|那个|前一个|最早|继续刚才)/u.test(t)?!0:/\b(back to|earlier|previous|that earlier|the earlier)\b/i.test(t)}async function _d(e){try{let t=await Al({currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.retrieved.map(e=>({segmentId:e.segment.segmentId,turnIds:e.segment.turnIds,summary:e.segment.summary,compressedSummary:e.segment.compressedSummary,keywords:e.segment.keywords,toolNames:e.segment.toolNames,topicLabel:e.segment.topicLabel})),llm:e.llm,signal:e.signal}),n=new Set(t.selectedSegmentIds);return n.size===0?[]:e.retrieved.filter(e=>n.has(e.segment.segmentId))}catch{return[]}}function vd(e){let t=yd(e);if(!t||Bu.has(t))return;let n=Cu(e).catch(()=>{}).finally(()=>{Bu.delete(t)});Bu.set(t,n)}function yd(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`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(`
50
+ `);const bd=[`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 xd(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 Ed(t);for(let e of p.readStates)n.set(Sd(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 V.mkdir(H.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=Sd(e,t,r),a=n.get(i);if(!a)return null;let o=await wd(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:Td(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await wd(e.path)??Date.now()};return n.set(Sd(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())Cd(i.path)===Cd(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=H.join(s,c);await V.mkdir(s,{recursive:!0});let u=e.encryptSessions??!1;await a(l,t.content,u);let p=H.relative(e.dataDir,l).split(H.sep).join(`/`),h=Ad(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:kd(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 jd(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 Sd(e,t,n){return`${Cd(e)}::${t??``}::${n??``}`}function Cd(e){return H.normalize(e)}async function wd(e){try{return(await V.stat(e)).mtimeMs}catch{return null}}function Td(e){return Xe(`sha1`).update(e).digest(`hex`)}async function Ed(e){try{let t=await l(e);if(t===null)return Dd();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?Dd():{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:Od(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 Dd()}}function Dd(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Od(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 kd(e){let t=e.preview.length<e.originalChars?`
51
+ ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...bd,`Preview:`,e.preview+t].join(`
52
+ `)}function Ad(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
53
+ `),r=n>t*.5?n:t;return e.slice(0,r)}async function jd(e,t,r,i){let o=n(e,t,i);await V.mkdir(H.dirname(o),{recursive:!0});let s=i?.encryptSessions??!1;await a(o,JSON.stringify(r,null,2),s)}const Md=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Nd(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=Gd(t),x=b>=0?t.slice(b+1):t;b>=0&&(y=t[b].content);let S=t.length,C=rl(Sl(x,a)),w=[],T=(await Wu({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;if(T=await Fd({entries:T,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:w}),T=await Id({entries:T,contextStore:f,compactionEvents:w}),T=await Ld({entries:T,contextStore:f,compactionEvents:w,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g}),f&&(y=await Pd({entries:T,existingSummary:y,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:Tl(T,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:T.length,estimatedTokens:Z(T),compacted:!1},compactionEvents:w};let E=f?.getSnapshot(),D=Math.max(1e3,Math.floor(r*.7)),O=Kd({entries:t,workingEntries:T,pendingUserMessage:s,checkpoint:E?.compaction.modelUsage}).projectedInputTokens>=D,k=E?.compaction.consecutiveAutocompactFailures??0;if(!O||k>=3)return{messages:Tl(T,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:T.length,estimatedTokens:Z(T),compacted:!1},compactionEvents:w};let{toKeep:A,toSummarise:j}=nl(T,r);if(j.length===0)return{messages:Tl(T,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:T.length,estimatedTokens:Z(T),compacted:!1},compactionEvents:w};let M=new Date().toISOString();try{let e=E?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Gc({entries:j,llm:i,previousSummary:y,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d}),a={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,Z(j)),affectedEntries:j.length,snapshotVersion:2}),{messages:Tl(rl(A),n),priorSummary:t,compactionEntry:a,stats:{originalCount:S,keptCount:A.length,estimatedTokens:Z(A),compacted:!0},compactionEvents:w}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:M}),{messages:Tl(T,n),priorSummary:y,compactionEntry:void 0,stats:{originalCount:S,keptCount:T.length,estimatedTokens:Z(T),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 Pd(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=Z(t),u=i.getSnapshot().compaction.sessionMemory,d=!u&&l>=8e3,f=!!u&&l>=(u?.tokenEstimate??0)+15e3&&Wd(t)>=3;if(!d&&!f)return n??u?.summary;let p=await Gc({entries:t,llm:r,previousSummary:n??u?.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(` `),contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}),m={version:1,summary:p,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:l,trigger:d?`threshold`:`autocompact`};return await i.setSessionMemory(m),p}async function Fd(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(zd).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(!zd(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=Bd(n)?Vd(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
54
+ `);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}),rl(l.reverse())}async function Id(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(!zd(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=Bd(r)?Vd(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(`
55
+ `);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}),Fd({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Ld(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(zd).filter(e=>Md.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=Rd(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(Z(r)-Z([g])));let _={id:Ze(),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 qd(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 Rd(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(`
61
56
  `),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
62
57
  `);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
63
58
 
64
- `)}function rf(e){return e.role===`tool_result`}function af(e){return e.toolName===`skill_load`}function of(e){let t=sf(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(`
65
- `)}function sf(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=cf(t);if(e.name||e.path)return e}return{}}function cf(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 lf(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function uf(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function df(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 ff(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 pf(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await zd({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 Zd({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function mf(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}):Zd({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 hf=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 gf(e,t,n){return Math.max(t,Math.min(n,e))}function _f(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function vf(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:gf(Math.floor(e),0,12e4)}function yf(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 bf(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 xf(e){return Cf({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
66
- `)}function Sf(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Cf(e){let t=Sf(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 wf(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:hf,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=yf(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=_f(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,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,vf(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:bf(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?Cf({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[xf(l)],p=Sf(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(`
67
- `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Tf=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 Ef(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Df(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Of(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:Tf,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(`
68
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Df(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Ef(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`}}:Df(`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}}:Df(`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}}:Df(`No session found for ${i}`)}return Df(`Unsupported action: ${n.action}`)}}}const kf=2e5;function Af(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function jf(e,t){let n=e+t;return n.length<=kf?{text:n,truncated:!1}:{text:n.slice(-kf),truncated:!0}}function Mf(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=jf(e.output,r);e.output=i.text;let a=jf(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Nf(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:Af(e.output),stdoutTail:Af(e.stdout),stderrTail:Af(e.stderr),outputTruncated:e.outputTruncated}}function Pf(e,t){return t?e.scopeKey===t:!0}function Ff(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function If(e){return e?e.split(/\r?\n/):[]}function Lf(e){let t=If(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Ff(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(`
69
- `);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 Rf(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function zf(){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),Rf(e))};return{start(t){let n=_t(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:Ye(),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=>Mf(o,`stdout`,e)),n.stderr.on(`data`,e=>Mf(o,`stderr`,e));let s=Ff(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Mf(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`),Mf(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`)})}),Nf(o)},get(e,t){let n=r(e);return!n||!Pf(n,t)?null:Nf(n)},list(n){return[...e.values(),...t.values()].filter(e=>Pf(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Nf(e))},async wait(e,t,n){let i=r(e);if(!i||!Pf(i,t))return null;if(i.status!==`running`)return Nf(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||!Pf(a,t)?null:Nf(a)},readLog(e){let t=r(e.sessionId);return!t||!Pf(t,e.scopeKey)?null:Lf({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Pf(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||!Pf(n,t))return null;if(n.status!==`running`)return Nf(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?Nf(i):null}}}function Bf(e){return wf({workspaceDir:e,registry:zf(),scopeKey:e})}const Vf=5*1024*1024,Hf=2e3;async function Uf(e,t){e&&await e(t).catch(()=>{})}function Wf(e,t){return G.isAbsolute(e)?G.normalize(e):G.normalize(G.join(t,e))}const Gf=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 Kf(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Gf,async execute(n,r){let i;try{i=Wf(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 vt(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>Vf){let e=o.slice(0,Vf).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Vf} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
70
- `),l=Math.max(1,r.offset??1),u=Math.min(Hf,r.limit??Hf),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(`
59
+ `)}function zd(e){return e.role===`tool_result`}function Bd(e){return e.toolName===`skill_load`}function Vd(e){let t=Hd(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(`
60
+ `)}function Hd(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Ud(t);if(e.name||e.path)return e}return{}}function Ud(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 Wd(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Gd(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Kd(e){let t=e.pendingUserMessage?.trim()?Z([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=Z(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=Z(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 qd(e,t,n,r){let i=k(e,t,r);await V.mkdir(H.dirname(i),{recursive:!0}),await V.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Jd(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await xd({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 Nd({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Yd(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}):Nd({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 Xd=W.Object({command:W.String({description:`Shell command to execute`}),workdir:W.Optional(W.String({description:`Working directory (relative to workspace root)`})),env:W.Optional(W.Record(W.String(),W.String())),timeout:W.Optional(W.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:W.Optional(W.Number({description:`Wait this many milliseconds before returning running state`})),background:W.Optional(W.Boolean({description:`Return immediately with running session`}))});function Zd(e,t,n){return Math.max(t,Math.min(n,e))}function Qd(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function $d(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:Zd(Math.floor(e),0,12e4)}function ef(e,t){if(!t?.trim())return e;let n=H.isAbsolute(t)?H.normalize(t):H.normalize(H.join(e,t));if(!n.startsWith(e+H.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function tf(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 nf(e){return af({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
61
+ `)}function rf(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function af(e){let t=rf(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 of(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:Xd,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=ef(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Qd(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,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,$d(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:tf(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?af({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[nf(l)],p=rf(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(`
62
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const sf=W.Object({action:W.String({description:`Process action: list | poll | log | kill`}),sessionId:W.Optional(W.String({description:`Session id for non-list actions`})),offset:W.Optional(W.Number({description:`Log line offset (0-based)`})),limit:W.Optional(W.Number({description:`Maximum lines to return`})),timeout:W.Optional(W.Number({description:`Poll wait time in milliseconds`}))});function cf(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function lf(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function uf(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:sf,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(`
63
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return lf(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,cf(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`}}:lf(`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}}:lf(`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}}:lf(`No session found for ${i}`)}return lf(`Unsupported action: ${n.action}`)}}}const df=2e5;function ff(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function pf(e,t){let n=e+t;return n.length<=df?{text:n,truncated:!1}:{text:n.slice(-df),truncated:!0}}function mf(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=pf(e.output,r);e.output=i.text;let a=pf(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function hf(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:ff(e.output),stdoutTail:ff(e.stdout),stderrTail:ff(e.stderr),outputTruncated:e.outputTruncated}}function gf(e,t){return t?e.scopeKey===t:!0}function _f(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function vf(e){return e?e.split(/\r?\n/):[]}function yf(e){let t=vf(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=_f(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(`
64
+ `);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 bf(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function xf(){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),bf(e))};return{start(t){let n=bt(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:Ze(),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=>mf(o,`stdout`,e)),n.stderr.on(`data`,e=>mf(o,`stderr`,e));let s=_f(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,mf(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`),mf(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`)})}),hf(o)},get(e,t){let n=r(e);return!n||!gf(n,t)?null:hf(n)},list(n){return[...e.values(),...t.values()].filter(e=>gf(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>hf(e))},async wait(e,t,n){let i=r(e);if(!i||!gf(i,t))return null;if(i.status!==`running`)return hf(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||!gf(a,t)?null:hf(a)},readLog(e){let t=r(e.sessionId);return!t||!gf(t,e.scopeKey)?null:yf({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!gf(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||!gf(n,t))return null;if(n.status!==`running`)return hf(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?hf(i):null}}}function Sf(e){return of({workspaceDir:e,registry:xf(),scopeKey:e})}const Cf=5*1024*1024,wf=2e3;async function Tf(e,t){e&&await e(t).catch(()=>{})}function Ef(e,t){return H.isAbsolute(e)?H.normalize(e):H.normalize(H.join(t,e))}const Df=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),offset:W.Optional(W.Number({description:`Line offset (1-based, default: 1)`})),limit:W.Optional(W.Number({description:`Maximum lines to read (default: 2000)`}))});function Of(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Df,async execute(n,r){let i;try{i=Ef(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 V.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 xt(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>Cf){let e=o.slice(0,Cf).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Cf} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
65
+ `),l=Math.max(1,r.offset??1),u=Math.min(wf,r.limit??wf),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(`
71
66
  `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
72
67
  `),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
73
- `),lines:d.length,truncated:f}}}}}const qf=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),content:q.String({description:`File content to write`})});function Jf(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:qf,async execute(r,i){let a;try{a=Wf(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 Uf(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 Yf=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 Xf(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:Yf,async execute(r,i){let a;try{a=Wf(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 Uf(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 Zf=q.Object({path:q.Optional(q.String({description:`Directory path (default: workspace root)`}))});function Qf(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Zf,async execute(t,n){let r=n.path??`.`,i;try{i=Wf(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(`
74
- `)||`(empty directory)`}],details:{entries:a}}}}}const $f=q.Object({input:q.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function ep(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 tp(e,t){let n=G.relative(t,e);return!n||n===``?G.basename(e):n.startsWith(`..`)||G.isAbsolute(n)?e:n}async function np(e){await W.mkdir(G.dirname(e),{recursive:!0})}async function rp(e,t){e&&await e(t).catch(()=>{})}function ip(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(`
75
- `)}function ap(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:$f,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=sp(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=ep(r.path,e);await np(i),await W.writeFile(i,r.contents,`utf-8`),await rp(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),op(o,s,`added`,tp(i,e));continue}if(r.kind===`delete`){let i=ep(r.path,e);await W.rm(i,{force:!0,recursive:!1}),await rp(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),op(o,s,`deleted`,tp(i,e));continue}let i=ep(r.path,e),a=await dp(i,r.chunks);if(r.movePath){let c=ep(r.movePath,e);await np(c),await W.writeFile(c,a,`utf-8`),await W.rm(i,{force:!0,recursive:!1}),await rp(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),op(o,s,`modified`,tp(c,e))}else await W.writeFile(i,a,`utf-8`),await rp(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),op(o,s,`modified`,tp(i,e))}return{content:[{type:`text`,text:ip(o)}],details:{summary:o}}}catch(e){if(Wi(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function op(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function sp(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);cp(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=lp(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function cp(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 lp(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}=up(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 up(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 dp(e,t){let n=(await W.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
76
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=pp(n,fp(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
77
- `)}function fp(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=mp(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=mp(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=mp(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
78
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function pp(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 mp(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(hp(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(hp(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(hp(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(hp(e,t,n,e=>gp(e.trim())))return n;return null}function hp(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 gp(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 _p(e){return G.join(e,`.aimax`)}function vp(e){return G.join(_p(e),`MEMORY.md`)}async function yp(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function bp(e,t){let n=_p(e),r=de({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:se({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function xp(e){return U(_p(e))}async function Sp(e){try{return await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Cp(e){return Sp(vp(e))}async function wp(e,t,n){let{provider:r}=bp(e,n);return await r.search(t)}async function Tp(e,t,n,r,i){try{let{provider:a}=bp(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Ep(e,t,n){let{provider:r,resolvedProviderId:i}=bp(e,n);await r.append(t),await yp(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 Dp(e,t,n,r){let{provider:i,resolvedProviderId:a}=bp(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 yp(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await yp(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 yp(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 yp(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await yp(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 Op(e,t,n,r){let{provider:i,resolvedProviderId:a}=bp(e,r);await i.updateFile(t,n),await yp(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function kp(e,t,n){let{provider:r,resolvedProviderId:i}=bp(e,n);await r.deleteFile(t),await yp(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const Ap=q.Object({query:q.String({description:`Search query (case-insensitive substring match)`})});function jp(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:Ap,async execute(n,r){let i=(await wp(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(`
79
- `)}],details:{matches:i}}}}}const Mp=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 Np(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:Mp,async execute(n,r){let i=await Tp(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(`
80
- `)||`(empty)`}],details:{lines:i}}}}}const Pp=q.Object({content:q.String({description:`Content to write to memory`})});function Fp(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:Pp,async execute(n,r){try{return await Ep(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 Ip=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 Lp(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:Ip,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Ep(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 Op(e,`MEMORY.md`,Rp(await Cp(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Ep(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 Rp(e,t,n){let r=e.split(`
68
+ `),lines:d.length,truncated:f}}}}}const kf=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),content:W.String({description:`File content to write`})});function Af(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:kf,async execute(r,i){let a;try{a=Ef(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await V.mkdir(H.dirname(a),{recursive:!0}),await V.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await Tf(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 jf=W.Object({path:W.String({description:`File path (relative to workspace or absolute)`}),old_string:W.String({description:`Exact text to replace`}),new_string:W.String({description:`Replacement text`})});function Mf(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:jf,async execute(r,i){let a;try{a=Ef(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 V.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 V.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await Tf(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 Nf=W.Object({path:W.Optional(W.String({description:`Directory path (default: workspace root)`}))});function Pf(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Nf,async execute(t,n){let r=n.path??`.`,i;try{i=Ef(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await V.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(`
69
+ `)||`(empty directory)`}],details:{entries:a}}}}}const Ff=W.Object({input:W.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function If(e,t){let n=H.isAbsolute(e)?H.normalize(e):H.normalize(H.join(t,e));if(!n.startsWith(t+H.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Lf(e,t){let n=H.relative(t,e);return!n||n===``?H.basename(e):n.startsWith(`..`)||H.isAbsolute(n)?e:n}async function Rf(e){await V.mkdir(H.dirname(e),{recursive:!0})}async function zf(e,t){e&&await e(t).catch(()=>{})}function Bf(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(`
70
+ `)}function Vf(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:Ff,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=Uf(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=If(r.path,e);await Rf(i),await V.writeFile(i,r.contents,`utf-8`),await zf(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Hf(o,s,`added`,Lf(i,e));continue}if(r.kind===`delete`){let i=If(r.path,e);await V.rm(i,{force:!0,recursive:!1}),await zf(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Hf(o,s,`deleted`,Lf(i,e));continue}let i=If(r.path,e),a=await qf(i,r.chunks);if(r.movePath){let c=If(r.movePath,e);await Rf(c),await V.writeFile(c,a,`utf-8`),await V.rm(i,{force:!0,recursive:!1}),await zf(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Hf(o,s,`modified`,Lf(c,e))}else await V.writeFile(i,a,`utf-8`),await zf(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Hf(o,s,`modified`,Lf(i,e))}return{content:[{type:`text`,text:Bf(o)}],details:{summary:o}}}catch(e){if(bi(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Hf(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Uf(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Wf(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Gf(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Wf(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 Gf(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}=Kf(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 Kf(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 qf(e,t){let n=(await V.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
71
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Yf(n,Jf(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
72
+ `)}function Jf(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Xf(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=Xf(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=Xf(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
73
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Yf(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 Xf(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(Zf(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Zf(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Zf(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Zf(e,t,n,e=>Qf(e.trim())))return n;return null}function Zf(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 Qf(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 $f(e){return H.join(e,`.aimax`)}function ep(e){return H.join($f(e),`MEMORY.md`)}async function $(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function tp(e,t){let n=$f(e),r=me({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:le({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function np(e){return pe($f(e))}async function rp(e){try{return await V.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ip(e){return rp(ep(e))}async function ap(e,t,n){let{provider:r}=tp(e,n);return await r.search(t)}async function op(e,t,n,r,i){try{let{provider:a}=tp(e,i);return await a.getLines(t,n,r)}catch{return null}}async function sp(e,t,n){let{provider:r,resolvedProviderId:i}=tp(e,n);await r.append(t),await $(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 cp(e,t,n,r){let{provider:i,resolvedProviderId:a}=tp(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 $(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await $(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 $(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 $(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await $(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 lp(e,t,n,r){let{provider:i,resolvedProviderId:a}=tp(e,r);await i.updateFile(t,n),await $(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function up(e,t,n){let{provider:r,resolvedProviderId:i}=tp(e,n);await r.deleteFile(t),await $(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const dp=W.Object({query:W.String({description:`Search query (case-insensitive substring match)`})});function fp(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:dp,async execute(n,r){let i=(await ap(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(`
74
+ `)}],details:{matches:i}}}}}const pp=W.Object({file:W.String({description:`Memory file path (from memory_search results)`}),start_line:W.Number({description:`Start line number (1-based)`}),end_line:W.Number({description:`End line number (1-based)`})});function mp(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:pp,async execute(n,r){let i=await op(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(`
75
+ `)||`(empty)`}],details:{lines:i}}}}}const hp=W.Object({content:W.String({description:`Content to write to memory`})});function gp(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:hp,async execute(n,r){try{return await sp(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 _p=W.Object({section:W.Optional(W.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:W.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:W.Union([W.Literal(`append`),W.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function vp(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:_p,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await sp(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 lp(e,`MEMORY.md`,yp(await ip(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await sp(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 yp(e,t,n){let r=e.split(`
81
76
  `),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(`
82
77
  `).trimEnd(),a,r.slice(s).join(`
83
78
  `).trimStart()].filter(e=>e.length>0).join(`
84
- `)}\n`}function zp(e,t){let n=e.split(`
79
+ `)}\n`}function bp(e,t){let n=e.split(`
85
80
  `),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(`
86
81
  `).trimEnd(),n.slice(a).join(`
87
82
  `).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
88
- `)}\n`:``}function Bp(e,t){let n=e.split(`
83
+ `)}\n`:``}function xp(e,t){let n=e.split(`
89
84
  `);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
90
- `)}\n`:``)}function Vp(e,t,n){let r=e.split(`
85
+ `)}\n`:``)}function Sp(e,t,n){let r=e.split(`
91
86
  `);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
92
- `)}\n`)}function Hp(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 Up(e,t){let n=[],r=t.split(`
93
- `);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 Wp=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 Gp(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:Wp,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Dp(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 Kp=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 qp(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:Kp,async execute(n,r){try{let n=r.scope??`all`,i=await xp(e),a=[];for(let n of i.slice(0,30)){let r=await Tp(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
94
- `),t=Up(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(`
87
+ `)}\n`)}function Cp(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 wp(e,t){let n=[],r=t.split(`
88
+ `);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 Tp=W.Object({content:W.String({description:`Note to append to today's daily log`}),scope:W.Optional(W.Union([W.Literal(`daily`),W.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Ep(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:Tp,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await cp(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 Dp=W.Object({scope:W.Optional(W.Union([W.Literal(`long-term`),W.Literal(`recent`),W.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Op(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:Dp,async execute(n,r){try{let n=r.scope??`all`,i=await np(e),a=[];for(let n of i.slice(0,30)){let r=await op(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
89
+ `),t=wp(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(`
95
90
  `):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
96
91
 
97
- `)||`(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 Jp=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 Yp(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:Jp,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Hp(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=zp(await Cp(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 Op(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 Tp(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=zp(n.join(`
98
- `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Op(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 Tp(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=Bp(n.join(`
99
- `),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 Op(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 kp(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 wp(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await kp(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 Xp=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 Zp(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:Xp,async execute(n,r){try{let n=Hp(r.id);if(n.section){let i=Rp(await Cp(e)??``,n.section,r.content);return await Op(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 Tp(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=Vp(i.join(`
100
- `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Op(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 Op(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 Qp=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 $p(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:Qp,async execute(n,r){let i=em(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await tm(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 nm({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=hm(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 hl({entries:fm(dm(await m(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:mm({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 em(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function tm(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 nm(e){let t=e.messageLimit??50,n=(await y(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=om(e.query),i=(await gm(n,6,async t=>rm({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(um).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 rm(t){let n=await l(e(t.dataDir,t.sessionId,{storeName:t.storeName}));if(n===null)return[];let r=[],i=n.split(`
101
- `);for(let e of i){let n=e.trim();if(!n||!im(n,t.terms))continue;let i;try{i=JSON.parse(n)}catch{continue}if(!am(i.role)||t.roleFilter&&i.role!==t.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=cm(i.content,t.terms,i.role);if(a<=0)continue;let o=lm(i.content);r.push({sessionId:t.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),r.length>20&&(r.sort(um),r.length=20)}return r.sort(um),r}function im(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function am(e){return e===`user`||e===`assistant`||e===`tool_result`}function om(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=>sm(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 sm(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 cm(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 lm(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function um(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function dm(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function fm(e,t,n){if(e.length===0)return e;let r=om(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 pm(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 pm(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 mm(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(`
102
- `)}function hm(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(`
103
- `)}`}async function gm(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 _m=q.Object({category:q.Optional(q.String({description:`Reserved category filter field. Not used yet.`}))}),vm=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 ym(e,t,n=[]){return[...n,...t,Mt(e)]}function bm(e,t,n=[]){let r=ym(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:_m,async execute(e,t){let n=await Bt(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 xm(e){let t=ym(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:vm,async execute(r,i){let a=await Ut(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 Sm=q.Object({});function Cm(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:Sm,async execute(r,i){let a=await R(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null})}],details:{}};let o=await B(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 wm=q.Object({status:q.String({description:`Status to set. Only 'complete' is allowed.`})});function Tm(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:wm,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 R(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 un(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 Em=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.`}))}),Dm=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.`}))}),Om=q.Object({tasks:q.Array(Em,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function km(e){let t=e.label?`"${e.label}"`:`task: ${Ve(e.task)}`;return e.status===`done`?`${t}\n\n${Am(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Am(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 jm(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(Y.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:ji(p)}),!p){let e={status:`error`,error:`task must not be empty`};return Y.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 Y.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Ye(),v=new AbortController,y=t,b=ni(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return Y.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 Y.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}Y.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?ci(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),Y.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await w,Y.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=km({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 Y.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 Y.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 Mm(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:Dm,async execute(e,t){return jm(u,e,t)}}}function Nm(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:Om,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}}Y.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 jm(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${Am(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
92
+ `)||`(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 kp=W.Object({id:W.Optional(W.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:W.Optional(W.String({description:`Search query used to find memories to delete`})),limit:W.Optional(W.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:W.Optional(W.Union([W.Literal(`long-term`),W.Literal(`recent`),W.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Ap(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:kp,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Cp(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=bp(await ip(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 lp(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 op(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=bp(n.join(`
93
+ `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await lp(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 op(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=xp(n.join(`
94
+ `),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 lp(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 up(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 ap(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await up(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 jp=W.Object({id:W.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:W.String({description:`New content to replace the existing memory with`})});function Mp(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:jp,async execute(n,r){try{let n=Cp(r.id);if(n.section){let i=yp(await ip(e)??``,n.section,r.content);return await lp(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 op(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=Sp(i.join(`
95
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await lp(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 lp(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 Np=W.Object({query:W.Optional(W.String({description:`Search query; omit to browse recent sessions.`})),role_filter:W.Optional(W.Union([W.Literal(`user`),W.Literal(`assistant`),W.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:W.Optional(W.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:W.Optional(W.Union([W.Literal(`llm`),W.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Pp(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:Np,async execute(n,r){let i=Fp(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Ip(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 Lp({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=Xp(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 Gc({entries:qp(Kp(await m(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Yp({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 Fp(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Ip(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 P(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 Lp(e){let t=e.messageLimit??50,n=(await y(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Vp(e.query),i=(await Zp(n,6,async t=>Rp({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Gp).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 P(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 Rp(t){let n=await l(e(t.dataDir,t.sessionId,{storeName:t.storeName}));if(n===null)return[];let r=[],i=n.split(`
96
+ `);for(let e of i){let n=e.trim();if(!n||!zp(n,t.terms))continue;let i;try{i=JSON.parse(n)}catch{continue}if(!Bp(i.role)||t.roleFilter&&i.role!==t.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Up(i.content,t.terms,i.role);if(a<=0)continue;let o=Wp(i.content);r.push({sessionId:t.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),r.length>20&&(r.sort(Gp),r.length=20)}return r.sort(Gp),r}function zp(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Bp(e){return e===`user`||e===`assistant`||e===`tool_result`}function Vp(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=>Hp(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 Hp(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 Up(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 Wp(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Gp(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Kp(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function qp(e,t,n){if(e.length===0)return e;let r=Vp(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 Jp(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 Jp(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 Yp(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(`
97
+ `)}function Xp(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(`
98
+ `)}`}async function Zp(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}function Qp(e){return H.join(e,`.aimax`,`skills`)}function $p(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function em(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${$p(n)}\n`)}function tm(e){let t=$e(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
99
+ `);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 nm(e){let t=$e(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 rm(e){return(await V.stat(e)).mtime.toISOString()}async function im(e){return om([Qp(e)])}async function am(e,t,n=[]){return om([...n,...t,Qp(e)])}async function om(e){let t=new Map;for(let n of e){let e;try{e=await V.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=H.join(n,e,`SKILL.md`),i;try{i=await V.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=tm(i),o=nm(i),s=await rm(r)}catch(t){em(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 sm(e,t){let n=t.trim();if(!n)return;let r=(await om(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:H.dirname(r.location)}}async function cm(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=H.resolve(r),a=H.basename(i)===`SKILL.md`?i:H.join(i,`SKILL.md`);if(H.basename(a)!==`SKILL.md`)return;let o;try{o=await V.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=tm(o),c=nm(o),l=await rm(a)}catch(e){em(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:H.dirname(a)}}async function lm(e,t,n){let r=n?.trim()?await cm(t,n):await sm(e,t);if(!r)return;let i=await V.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function um(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(`
100
+ `)).join(`
101
+ `)}\n</available_skills>`}const dm=W.Object({category:W.Optional(W.String({description:`Reserved category filter field. Not used yet.`}))}),fm=W.Object({name:W.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:W.Optional(W.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function pm(e,t,n=[]){return[...n,...t,Qp(e)]}function mm(e,t,n=[]){let r=pm(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:dm,async execute(e,t){let n=await om(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 hm(e){let t=pm(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:fm,async execute(r,i){let a=await lm(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 gm=W.Object({});function _m(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:gm,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 B(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 vm=W.Object({status:W.String({description:`Status to set. Only 'complete' is allowed.`})});function ym(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:vm,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 pl(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 bm=W.Object({task:W.String({description:`The task description for the subagent to execute`}),label:W.Optional(W.String({description:`Optional short label to identify this subagent`})),agent:W.Optional(W.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.`}))}),xm=W.Object({task:W.String({description:`The task description for the subagent to execute`}),label:W.Optional(W.String({description:`Optional short label to identify this subagent`})),agent:W.Optional(W.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.`}))}),Sm=W.Object({tasks:W.Array(bm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Cm(e){let t=e.label?`"${e.label}"`:`task: ${We(e.task)}`;return e.status===`done`?`${t}\n\n${wm(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function wm(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 Tm(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(q.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:si(p)}),!p){let e={status:`error`,error:`task must not be empty`};return q.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 q.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Ze(),v=new AbortController,y=t,b=Mr(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return q.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 q.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}q.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?Rr(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),q.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await w,q.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=Cm({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 q.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 q.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 Em(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:xm,async execute(e,t){return Tm(u,e,t)}}}function Dm(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:Sm,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}}q.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 Tm(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${wm(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
104
102
 
105
- `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const Pm=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 Fm(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 Im(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 Lm(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:Pm,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} (${Fm(e.runtimeMs)})${n}`})).join(`
106
- `)};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=Im(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}}}}function Rm(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 zm(e){let t=Rm(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 Bm(e){let t=e.watchFactory??((e,t,n)=>K.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=zm({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{}}}function Vm(e){return e.projectDir?.trim()||G.join(e.dataDir,`workspace`)}async function Hm(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Vm(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Gm(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=de({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),g=h?.provider??se({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=Bm({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,Wm({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 Um(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Wm(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 Gm(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}const Km=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 qm(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Km,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 Jm=q.Object({reason:q.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Ym(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??Jm,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=We(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 Gi(e,i,t,e,o,s,n);throw ea(r),r}}}function Xm(e,t){let n=Vm({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=zf(),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=[wf({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),Of({registry:i,scopeKey:n}),Kf(n,t?.contextManager),Jf(n,t?.contextManager,s),Xf(n,t?.contextManager,s),Qf(n),ap(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[Cm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),Tm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId)]:[],jp(e,r),$p(e,r),Np(e,r),Lp(e,r),Gp(e,r),qp(e,r),Yp(e,r),Zp(e,r),bm(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),xm({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(Xo(e),Zo(e),Qo(e),$o(e)),t&&c.push(Mm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Nm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Lm(t.registry,t.parentSessionId)),c}function Zm(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(`
103
+ `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const Om=W.Object({action:W.Union([`list`,`kill`].map(e=>W.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:W.Optional(W.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function km(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 Am(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 jm(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:Om,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} (${km(e.runtimeMs)})${n}`})).join(`
104
+ `)};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=Am(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}}}}function Mm(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 Nm(e){let t=Mm(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=H.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 Pm(e){let t=e.watchFactory??((e,t,n)=>U.watch(e,t,n)),n=H.join(e.dataDir,`.aimax`),r=[{target:H.join(n,`MEMORY.md`),kind:`memory-file`},{target:H.join(n,`memory.md`),kind:`memory-file-lower`},{target:H.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=Nm({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{}}}function Fm(e){return e.projectDir?.trim()||H.join(e.dataDir,`workspace`)}async function Im(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Fm(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=zm(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=H.join(t.dataDir,`.aimax`),h=me({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:m,sessionId:i,sessionStoreName:t.sessionStoreName}),g=h?.provider??le({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=Pm({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,Rm({sessionOptions:X(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 Lm(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Rm(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 zm(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}const Bm=W.Object({image:W.String({description:`Image path or URL`}),prompt:W.Optional(W.String({description:`Prompt for image analysis`})),model:W.Optional(W.String({description:`Optional model override`})),maxBytesMb:W.Optional(W.Number({description:`Optional size cap in MB`}))});function Vm(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Bm,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 Hm=W.Object({reason:W.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Um(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??Hm,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=qe(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 xi(e,i,t,e,o,s,n);throw Ai(r),r}}}function Wm(e,t){let n=Fm({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=xf(),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=[of({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),uf({registry:i,scopeKey:n}),Of(n,t?.contextManager),Af(n,t?.contextManager,s),Mf(n,t?.contextManager,s),Pf(n),Vf(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[_m(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),ym(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId)]:[],fp(e,r),Pp(e,r),mp(e,r),vp(e,r),Ep(e,r),Op(e,r),Ap(e,r),Mp(e,r),mm(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),hm({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(Eo(e),Do(e),Oo(e),ko(e)),t&&c.push(Em(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Dm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),jm(t.registry,t.parentSessionId)),c}function Gm(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(`
107
105
  `),`</auto_skill_categories>`,``].join(`
108
- `)}const Qm={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`},$m=[`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 eh(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:[...$m.filter(e=>t.has(e)),...n.filter(e=>!$m.includes(e)).sort()],displayName:t}}function th(e){let{ordered:t,displayName:n}=eh(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)??Qm[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
106
+ `)}const Km={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`},qm=[`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 Jm(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:[...qm.filter(e=>t.has(e)),...n.filter(e=>!qm.includes(e)).sort()],displayName:t}}function Ym(e){let{ordered:t,displayName:n}=Jm(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)??Km[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
109
107
  `),``].join(`
110
- `)}function nh(){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(`
111
- `)}function rh(){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(`
112
- `)}function ih(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
113
- `)}function ah(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(`
114
- `)}function oh(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(`
108
+ `)}function Xm(){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(`
109
+ `)}function Zm(){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(`
110
+ `)}function Qm(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
111
+ `)}function $m(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(`
112
+ `)}function eh(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(`
115
113
  `)).join(`
116
114
  `)}\n</available_skills>`,``].join(`
117
- `)}function sh(e=[]){let t=Zm(e).trim();return t?`${t}\n`:``}function ch(){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(`
118
- `)}function lh(){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(`
119
- `)}function uh(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(`
120
- `)}function dh(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(`
121
- `)}function fh(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(`
122
- `)}function ph(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=mh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
123
- `)}function mh(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 hh(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(`
124
- `)}function gh(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(`
125
- `)}function _h(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(`
126
- `)}function vh(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(`
127
- `)}function yh(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(`
128
- `)}function bh(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(`
129
- `):``}function xh(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:[...$m],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,yh(e.subagentDepth??0),th({toolNames:i,toolSummaries:e.toolSummaries}),ah(n),nh(),rh(),si(e.availableAgents??[]),oh(a),sh(e.autoSkillCategories),ch(),lh(),uh(e.memoryCitationsMode??`off`),dh({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),fh(e.sandboxInfo),ph({currentDate:e.currentDate,timezone:e.timezone}),ih(),hh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),_h({isMinimal:n}),gh(e.runtimeInfo),vh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),bh(e.priorConversationSummary)].filter(Boolean).join(`
130
- `)}const Sh=Symbol(`pluginToolOwner`);var Ch=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,Sh,{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=Ym({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,Sh,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function wh(e){return e[Sh]}function Th(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=wh(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await hi({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(Wi(e))return Xi(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(Wi(i)){Xi(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 Eh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Dh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Oh(e){let t=Dh(e?.warningThreshold,Eh.warningThreshold),n=Dh(e?.criticalThreshold,Eh.criticalThreshold),r=Dh(e?.globalCircuitBreakerThreshold,Eh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Eh.enabled,historySize:Dh(e?.historySize,Eh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Eh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Eh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Eh.detectors.pingPong}}}function kh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Ah(e,t){return`${e}:${Nh(t)}`}function jh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(jh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${jh(t[e])}`).join(`,`)}}`}function Mh(e){try{return jh(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 Nh(e){let t=Mh(e);return Je(`sha256`).update(t).digest(`hex`)}function Ph(e,t){if(e===`command_status`)return!0;if(e!==`process`||!kh(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Fh(e){return!kh(e)||!Array.isArray(e.content)?``:e.content.filter(e=>kh(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
131
- `).trim()}function Ih(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:jh(e)}function Lh(e,t,n,r){if(r!==void 0)return`error:${Nh(Ih(r))}`;if(!kh(n))return n===void 0?void 0:Nh(n);let i=kh(n.details)?n.details:{},a=Fh(n);if(Ph(e,t)&&e===`process`&&kh(t)){let e=t.action;if(e===`poll`)return Nh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Nh({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 Nh({details:i,text:a})}function Rh(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 zh(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 Bh(e,t){return[e,t].toSorted().join(`|`)}function Vh(e,t,n,r){let i=Oh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Ah(t,n),s=Rh(a,t,o),c=s.count,l=Ph(t,n),u=zh(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:${Bh(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 Hh(e,t,n,r,i){let a=Oh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Ah(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Uh(e,t){let n=Oh(t.config),r=Lh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Ah(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 Wh(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 Gh(e){return e&&e.trim()||`tool`}function Kh(e,t,n){if(!e.execute)return e;let r=Gh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Vh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Wh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Hh(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Uh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Uh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function qh(e,t,n){return e.map(e=>Kh(e,t,n))}function Jh(e){let t=e.streamFn??ot;return(e,n,r)=>(e.api===`anthropic-messages`&&Yh(e),t(e,n,{...r,...ng(e,r)}))}function Yh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Qh(tg(e),n)?(globalThis.fetch=t,Xh(await t(e,$h(e,r)))):t(e,r))}function Xh(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
132
-
133
- `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Zh))),a.enqueue(r.encode(e+`
134
-
135
- `))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Zh=`event: message_start
115
+ `)}function th(e=[]){let t=Gm(e).trim();return t?`${t}\n`:``}function nh(){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(`
116
+ `)}function rh(){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(`
117
+ `)}function ih(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(`
118
+ `)}function ah(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(`
119
+ `)}function oh(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(`
120
+ `)}function sh(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=ch(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
121
+ `)}function ch(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 lh(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(`
122
+ `)}function uh(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(`
123
+ `)}function dh(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(`
124
+ `)}function fh(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(`
125
+ `)}function ph(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(`
126
+ `)}function mh(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(`
127
+ `):``}function hh(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:[...qm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,ph(e.subagentDepth??0),Ym({toolNames:i,toolSummaries:e.toolSummaries}),$m(n),Xm(),Zm(),Lr(e.availableAgents??[]),eh(a),th(e.autoSkillCategories),nh(),rh(),ih(e.memoryCitationsMode??`off`),ah({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),oh(e.sandboxInfo),sh({currentDate:e.currentDate,timezone:e.timezone}),Qm(),lh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),dh({isMinimal:n}),uh(e.runtimeInfo),fh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),mh(e.priorConversationSummary)].filter(Boolean).join(`
128
+ `)}const gh=Symbol(`pluginToolOwner`);var _h=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,gh,{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=Um({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,gh,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function vh(e){return e[gh]}function yh(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=vh(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await Gr({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(bi(e))return Ei(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(bi(i)){Ei(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 bh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function xh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Sh(e){let t=xh(e?.warningThreshold,bh.warningThreshold),n=xh(e?.criticalThreshold,bh.criticalThreshold),r=xh(e?.globalCircuitBreakerThreshold,bh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??bh.enabled,historySize:xh(e?.historySize,bh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??bh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??bh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??bh.detectors.pingPong}}}function Ch(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function wh(e,t){return`${e}:${Dh(t)}`}function Th(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Th).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Th(t[e])}`).join(`,`)}}`}function Eh(e){try{return Th(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 Dh(e){let t=Eh(e);return Xe(`sha256`).update(t).digest(`hex`)}function Oh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Ch(t))return!1;let n=t.action;return n===`poll`||n===`log`}function kh(e){return!Ch(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Ch(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
129
+ `).trim()}function Ah(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Th(e)}function jh(e,t,n,r){if(r!==void 0)return`error:${Dh(Ah(r))}`;if(!Ch(n))return n===void 0?void 0:Dh(n);let i=Ch(n.details)?n.details:{},a=kh(n);if(Oh(e,t)&&e===`process`&&Ch(t)){let e=t.action;if(e===`poll`)return Dh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Dh({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 Dh({details:i,text:a})}function Mh(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 Nh(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 Ph(e,t){return[e,t].toSorted().join(`|`)}function Fh(e,t,n,r){let i=Sh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=wh(t,n),s=Mh(a,t,o),c=s.count,l=Oh(t,n),u=Nh(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:${Ph(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 Ih(e,t,n,r,i){let a=Sh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:wh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Lh(e,t){let n=Sh(t.config),r=jh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=wh(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 Rh(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 zh(e){return e&&e.trim()||`tool`}function Bh(e,t,n){if(!e.execute)return e;let r=zh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Fh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Rh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Ih(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Lh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Lh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Vh(e,t,n){return e.map(e=>Bh(e,t,n))}function Hh(e){let t=e.streamFn??lt;return(e,n,r)=>(e.api===`anthropic-messages`&&Uh(e),t(e,n,{...r,...Xh(e,r)}))}function Uh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Kh(Yh(e),n)?(globalThis.fetch=t,Wh(await t(e,qh(e,r)))):t(e,r))}function Wh(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
130
+
131
+ `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Gh))),a.enqueue(r.encode(e+`
132
+
133
+ `))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Gh=`event: message_start
136
134
  data: {"type":"message_start","message":{"id":"","type":"message","role":"assistant","content":[],"model":"","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}
137
135
 
138
- `;function Qh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function $h(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))eg(e)&&n.delete(e);return{...t,headers:n}}function eg(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function tg(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function ng(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function rg(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:t.llm.apiFormat??`openai-completions`},D=await pf({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 mf({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,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 og({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=oi([...Xm(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,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,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,baseEnv:t.env}),...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=xh({dataDir:t.dataDir,projectDir:t.projectDir,skills:ai(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:ht.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});N=await ig({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=qh(Th(A,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},Sc),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 re=b({...t.llm,model:I},n,t.messageId,t.channel),R=new Ze({initialState:{systemPrompt:N,model:re,tools:F,messages:[]},getApiKey:e=>t.llm.apiKey,streamFn:Jh({})});return O.messages.length>0&&R.replaceMessages(O.messages),{agent:R,resolvedModelId:I,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:a.workspaceDir}}async function ig(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 ag(e){let{session:t,runtime:n,effectivePromptText:r,dependencies:i}=e,{runParams:a,sessionId:o,hookRegistry:s,hookContext:c,runContext:l,eventDispatcher:u}=t,{abortSignal:d}=i;if(a.channel===`CRON`)return{status:`skipped`,reason:`CRON runs do not persist transcript history.`};let f=await Cl({entries:await m(a.dataDir,o,Q(a)),contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.flashModel??a.llm.model},instructions:Ha,signal:d,hooks:s,hookCtx:c});if(f.status!==`compacted`)return{status:`skipped`,reason:f.reason};await og({sessionId:o,historyResult:{messages:[],priorSummary:void 0,compactionEntry:f.entry,stats:{originalCount:f.keptCount+f.droppedCount,keptCount:f.keptCount,estimatedTokens:f.estimatedTokens,compacted:!0},compactionEvents:[{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`,estimatedTokensFreed:Math.max(0,f.droppedCount),affectedEntries:f.droppedCount,snapshotVersion:2}]},runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),await u.dispatchProgress(o,{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`});let p={model:a.llm.model,api:a.llm.apiFormat??`openai-completions`},h=await mf({entries:await m(a.dataDir,o,Q(a)),modelInfo:p,contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.model,flashModel:a.llm.flashModel},historyLimit:a.historyLimit,topicSegmentation:a.topicSegmentation,channel:a.channel,isSubagent:!!a.subagentContext,compactionEnabled:!0,pendingUserMessage:r,signal:d,hooks:s,hookCtx:c,contextManager:n.contextManager,dataDir:a.dataDir,sessionId:o});return await og({sessionId:o,historyResult:h,runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),n.historyResult=h,n.historyMessages=h.messages,n.agent.replaceMessages(h.messages),{status:`compacted`}}async function og(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=sg(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 sg(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(`
136
+ `;function Kh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function qh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Jh(e)&&n.delete(e);return{...t,headers:n}}function Jh(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function Yh(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function Xh(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function Zh(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,X(t)),E={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},D=await Jd({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 Yd({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,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 eg({sessionId:n,historyResult:O,runContext:a,eventDispatcher:o,hookRegistry:r,hookContext:i});let k=t.subagentContext?.depth??0,A=d(t.dataDir,n,X(t)),j=Ir([...Wm(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:A,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,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:a.memoryProviderId,pluginId:a.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,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,baseEnv:t.env}),...p],C),M=j.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),N={};for(let e of j){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||N[t]||(N[t]=n)}let ee=t.messaging?.enabled??t.channel!==`CRON`,P=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],F=hh({dataDir:t.dataDir,projectDir:t.projectDir,skills:Fr(l,C),autoSkillCategories:S?u:[],contextFiles:s,toolNames:M,toolSummaries:N,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:c,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:ee,channels:P},sandboxInfo:{enabled:!0,hostWorkspaceDir:a.workspaceDir,containerWorkspaceDir:a.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:vt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});F=await Qh({systemPrompt:F,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let te=await r.dispatch(`before_prompt_build`,{prompt:f},i,{eventDispatcher:o});for(let e of te)e&&(e.systemPrompt&&(F=e.systemPrompt),e.prependContext&&(F=`${e.prependContext}\n\n${F}`));await r.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:F},i,{eventDispatcher:o});let ne=Vh(yh(j,r,i,{eventDispatcher:o}),{sessionId:n,config:t.loopDetection},Qs),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 et({initialState:{systemPrompt:F,model:R,tools:ne,messages:[]},getApiKey:e=>t.llm.apiKey,streamFn:Hh({})});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 Qh(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 ${j(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 $h(e){let{session:t,runtime:n,effectivePromptText:r,dependencies:i}=e,{runParams:a,sessionId:o,hookRegistry:s,hookContext:c,runContext:l,eventDispatcher:u}=t,{abortSignal:d}=i;if(a.channel===`CRON`)return{status:`skipped`,reason:`CRON runs do not persist transcript history.`};let f=await il({entries:await m(a.dataDir,o,X(a)),contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.flashModel??a.llm.model},instructions:va,signal:d,hooks:s,hookCtx:c});if(f.status!==`compacted`)return{status:`skipped`,reason:f.reason};await eg({sessionId:o,historyResult:{messages:[],priorSummary:void 0,compactionEntry:f.entry,stats:{originalCount:f.keptCount+f.droppedCount,keptCount:f.keptCount,estimatedTokens:f.estimatedTokens,compacted:!0},compactionEvents:[{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`,estimatedTokensFreed:Math.max(0,f.droppedCount),affectedEntries:f.droppedCount,snapshotVersion:2}]},runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),await u.dispatchProgress(o,{type:`compaction`,reason:`Emergency compaction after context limit error`,layer:`L6`,strategy:`full_summary`});let p={model:a.llm.model,api:a.llm.apiFormat??`openai-completions`},h=await Yd({entries:await m(a.dataDir,o,X(a)),modelInfo:p,contextWindowTokens:a.llm.contextWindow??2e5,llm:{apiFormat:a.llm.apiFormat,baseUrl:a.llm.baseUrl,apiKey:a.llm.apiKey,model:a.llm.model,flashModel:a.llm.flashModel},historyLimit:a.historyLimit,topicSegmentation:a.topicSegmentation,channel:a.channel,isSubagent:!!a.subagentContext,compactionEnabled:!0,pendingUserMessage:r,signal:d,hooks:s,hookCtx:c,contextManager:n.contextManager,dataDir:a.dataDir,sessionId:o});return await eg({sessionId:o,historyResult:h,runContext:l,eventDispatcher:u,hookRegistry:s,hookContext:c}),n.historyResult=h,n.historyMessages=h.messages,n.agent.replaceMessages(h.messages),{status:`compacted`}}async function eg(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=tg(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 tg(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(`
139
137
 
140
- `):void 0}}async function cg(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++,Y.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){Y.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}Y.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=lg(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Xa({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?Y.warn(`subagent announce round completed with error`,v):Y.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&Y.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function lg(e){if(e.length===1){let t=e[0];return km({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>km({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
138
+ `):void 0}}async function ng(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++,q.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){q.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}q.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=rg(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await Ea({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?q.warn(`subagent announce round completed with error`,v):q.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&q.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function rg(e){if(e.length===1){let t=e[0];return Cm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Cm({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
141
139
 
142
140
  ---
143
141
 
144
- `)}`}function ug(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dg(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function fg(){let e=ht.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function pg(e){let t=e.trim(),n=fg();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?G.join(n,t.slice(2)):void 0:G.resolve(t)}const mg=new yt({allErrors:!0,strict:!1}),hg=new Map;function gg(e,t){let n=hg.get(t);if(n)return n;let r=mg.compile(e);return hg.set(t,r),r}function _g(e){let t=e.cacheKey??JSON.stringify(e.schema),n=gg(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function vg(e){let t=dg(e?.allow),n=dg(e?.deny),r=dg(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 yg(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=_g({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 bg(e){try{return K.realpathSync(e)}catch{return null}}function xg(e){try{return K.statSync(e)}catch{return null}}function Sg(e,t){let n=G.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!G.isAbsolute(n)}function Cg(e){return`0o${e.toString(8).padStart(3,`0`)}`}const wg=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Tg=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Eg(e){let t=G.join(e,`package.json`);if(K.existsSync(t))try{let e=JSON.parse(K.readFileSync(t,`utf-8`));return ug(e)?e:void 0}catch{return}}function Dg(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 Og(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function kg(e){let t=bg(e.source),n=bg(e.rootDir);return!t||!n||Sg(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Ag(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=xg(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 jg(e){return kg({source:e.source,rootDir:e.rootDir})||Ag({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Og(e.ownershipUid)})}function Mg(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=${Cg(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Ng(e){let t=jg({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Mg(t),source:e.source}),!0):!1}function Pg(e){return G.basename(e,G.extname(e))}function Fg(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 Ig(e){for(let t of Tg){let n=G.join(e,t);if(K.existsSync(n))return n}return null}function Lg(e){let t;try{t=K.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=G.join(e.rootDir,n.name);if(n.isFile()){if(!wg.has(G.extname(n.name)))continue;let r=G.dirname(t);if(Ng({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Fg({idHint:Pg(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Eg(t),i=Dg(r);if(i.status===`ok`){for(let n of i.entries){let i=G.resolve(t,n);if(!Sg(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!K.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!wg.has(G.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Ng({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Pg(i)}`:Pg(i);e.candidates.push(Fg({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=Ig(t);a&&(Ng({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Fg({idHint:G.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Rg(e){return e?e.map(pg).filter(e=>typeof e==`string`&&e.length>0):[]}function zg(){let e=fg();if(e)return G.join(e,`.aimax`,`extensions`)}function Bg(e){return G.join(e,`.aimax`,`extensions`)}function Vg(e){return G.join(e,`.aimax`,`extensions`)}function Hg(e={}){let t=[],n=[],r=Rg(e.extraPaths);for(let i of r){if(!K.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=xg(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!wg.has(G.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=G.dirname(i);if(Ng({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Fg({idHint:Pg(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Lg({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Lg({rootDir:Bg(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Lg({rootDir:Vg(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=zg();return i?Lg({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&&Lg({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Ug(e){let t=e.rejectHardlinks??!0,n=bg(e.rootPath),r=bg(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!Sg(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=K.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:K.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Wg=`aimax.plugin.json`,Gg=[Wg];function Kg(e){for(let t of Gg){let n=G.join(e,t);if(K.existsSync(n))return n}return G.join(e,Wg)}function qg(e,t=!0){let n=Kg(e),r=Ug({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(K.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{K.closeSync(r.fd)}if(!ug(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=ug(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=dg(i.skills),f;return ug(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 Jg(e){let t=new Map,n=[];for(let r of e){let e=qg(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 Yg=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Xg(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Yg.ERROR){Y.error(i);return}if(e===Yg.WARN){Y.warn(i);return}Y.info(i)}function Zg(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Xg(Yg.INFO,e.pluginId,t,n),warn:n=>Xg(Yg.WARN,e.pluginId,t,n),error:n=>Xg(Yg.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}function Qg(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 $g(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 e_(e){let t=[...e.registry.diagnostics],n=new Ch,r=new _i,i=[],a=[],o=e.runtime?.llm?Ni({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=t_(e.runtime?.llmAllowlist),c=bt(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Qg({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=$g({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=Zg({pluginId:l.id,env:e.runtime?.env}),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(!n_(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`);ae({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`);fe({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:()=>gi(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 t_(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function n_(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function r_(e={}){let t=vg(e.config),n=Hg({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Jg(n.candidates),i=yg({config:t,registry:r}),a=e_({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 i_(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?r_({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):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 _i,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 a_(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Vm(t),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=i_({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await Hm({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=>Nc({sessionId:o,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:i,...e})}}function o_(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function s_(e){if(!(e instanceof Error))return{errorValue:o_(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]=o_(n[e]));return t}async function c_(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...s_(e.error)}})}function l_(e,t,n){return G.join(d(e,t,n),`pending-ui-tool.json`)}async function u_(e,t,n,r){let i=d(e,t,r);await W.mkdir(i,{recursive:!0}),await a(l_(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function d_(e,t,n){let r=await l(l_(e,t,n));return r===null?null:JSON.parse(r)}async function f_(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await u_(e,t,a,r),a}async function p_(e,t,n,r,i){let a=await d_(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 u_(e,t,o,i),o}async function m_(e,t,n){try{await W.unlink(l_(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const h_=`crons`;function g_(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:ji(e.message)}}function __(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ue(t))}async function v_(e,t,n,r){let i=await R(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 y_(e,t,n,r,i,a){let o=await R(e,t,{storeName:a?.storeName});await v_(e,t,n,a);let s=await Kt(e,t,n,r,a);return s.goal&&await un(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}async function b_(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=Ji();if(i=await Yi(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Wi(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=x_(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 x_(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 S_(e,t){Ai(e.dataDir),Tc();let n=Date.now(),r=new Mi(e),i=jl(e);Y.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 a_({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;Y.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}}),Y.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,Um({sessionId:l,title:Mc(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 Tt(e.dataDir),b=[],x=Ot(y,{warn:e=>b.push(e)}),S=await jt();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}}),Y.info(`bootstrap context loaded`,{sessionId:l,bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length});let C=e.skillsLoadPaths??[],w=await zt(e.dataDir,h.pluginSkillDirs,C),T=await $r({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}))}}),Y.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}))}}),Y.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 C_({dataDir:e.dataDir,sessionId:l,eventDispatcher:r,enabled:e.autoSkills?.load?.enabled===!0}),A=e=>g.appendTranscriptEntry(e),j=await Nl({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 Y.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}}),Y.info(`invocation resolved`,{sessionId:l,promptType:typeof te==`string`?`string`:`messages`,transcriptLength:a.length});let N=await rg({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=>S_(e,new bc),createModel:Kr,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}}),Y.info(`agent runtime created`,{sessionId:l,modelId:F,historyMessageCount:N.historyMessages.length,pluginToolCount:h.pluginTools.length});let I=k_(e.timeoutMs),re=!1,R=setTimeout(()=>{re=!0,v.abort(),P.abort(),r.dispatchDiagnostic(l,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:I}}),Y.warn(`agent run timed out`,{sessionId:l,timeoutMs:I})},I);v.signal.addEventListener(`abort`,()=>P.abort());let z=0,B=0,V=``,H,ie=!1,ae=new Gt;await v_(e.dataDir,l,ae,{storeName:e.sessionStoreName});let oe=()=>({input:z,output:B,total:z+B}),se=new Ua,ce={runParams:k,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},le={registry:t,spawnFn:e=>S_(e,new bc),createModel:Kr,abortSignal:v.signal},ue=(e,t,n)=>({turnKind:e,budget:se,reloadHistory:()=>ag({session:ce,runtime:n,effectivePromptText:t,dependencies:le}),onPhase:async(e,t)=>{await r.dispatchDiagnostic(l,{level:e.includes(`failed`)||e.includes(`skipped`)?`warn`:`info`,scope:`runner`,phase:e,message:e.replace(/_/g,` `),details:t})}});try{if(__(e)){let t=await b_({params:e,agent:P,sessionId:l,eventDispatcher:r,appendEntry:A,abortSignal:v.signal});return V=t.text,Ic({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:V,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(a);ie=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let i=await sn(e.dataDir,l,te,{storeName:e.sessionStoreName});Y.info(`first agent turn started`,{sessionId:l,modelId:F});let s=typeof i.prompt==`string`?i.prompt:ne,c=await Xa({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,contextLimitRecovery:ue(`first`,s,N),onTurnRecordProduced:async(e,t)=>{e&&await A(e);for(let e of t)await A(e)}});V=c.text,z+=c.inputTokens,B+=c.outputTokens,c.error&&(H=c.error);let d=!!c.contextLimitRecoverySucceeded;i.hadObjectiveUpdatedSteering&&!c.error&&await cn(e.dataDir,l,{storeName:e.sessionStoreName}),await r.dispatchDiagnostic(l,{level:c.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let m={sessionId:l,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?Y.warn(`first agent turn completed with error`,m):Y.info(`first agent turn completed`,m);let h=await y_(e.dataDir,l,ae,oe(),r,{storeName:e.sessionStoreName,eventSource:`runner`});h.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`}),Y.info(`announce loop started`,{sessionId:l});let _=await cg({agent:P,registry:t,sessionId:l,resolvedModelId:F,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,retry:e.llmRetry,appendEntry:A});if(_.text&&(V=_.text),z+=_.inputTokens,B+=_.outputTokens,_.error&&!H&&(H=_.error),await r.dispatchDiagnostic(l,{level:_.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens}}),h=await y_(e.dataDir,l,ae,oe(),r,{storeName:e.sessionStoreName,eventSource:`runner`}),h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),tn()){let n=new en;n.reset(),c.error&&!d&&(n.lastTurnHadOutput=!1);let i=!0,a=Be;for(;i&&n.continuationCount<a&&!v.signal.aborted;)if(i=await an({agent:P,dataDir:e.dataDir,sessionId:l,sessionStoreName:e.sessionStoreName,state:n,accounting:ae,abortSignal:v.signal,executeTurn:async t=>{let n=await Xa({agent:P,message:t,continueFromHistory:!1,sessionId:l,channel:e.channel,modelId:F,historyMessages:N.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,contextLimitRecovery:ue(`continuation`,t,N),onTurnRecordProduced:async(e,t)=>{await on(A,e,t)}});z+=n.inputTokens,B+=n.outputTokens,V=n.text||V,n.error&&!H&&(H=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 y_(e.dataDir,l,ae,oe(),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 cg({agent:P,registry:t,sessionId:l,resolvedModelId:F,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,appendEntry:A});z+=e.inputTokens,B+=e.outputTokens,e.text&&(V=e.text),e.error&&!H&&(H=e.error)}}let y={sessionId:l,hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens};_.error?Y.warn(`announce loop completed with error`,y):Y.info(`announce loop completed`,y)}catch(t){if(Wi(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await _e(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}}),Y.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:z,output:B,total:z+B};return await w_({runtime:N,resolvedModelId:F,usage:c,currentUserEntryCoveredByUsage:ie}),Ic({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:V||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Ki(t)){let i=t,o=i.request.outputSchema.properties??{};await f_(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}}),Y.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:z,output:B,total:z+B};return await w_({runtime:N,resolvedModelId:F,usage:s,currentUserEntryCoveredByUsage:ie}),Ic({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:V||``,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}})}if(re&&A_(t))H=`Run timed out after ${I}ms`;else throw await c_({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),Y.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{clearTimeout(R);try{await y_(e.dataDir,l,ae,oe(),r,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}ae.clearActiveGoal(),Cc(l),g.stop()}let U={input:z,output:B,total:z+B};re&&(H=`Run timed out after ${I}ms`),await r.dispatchDiagnostic(l,{level:H?`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:!!H,error:H}});let de={sessionId:l,durationMs:Date.now()-n,inputTokens:U.input,outputTokens:U.output,totalTokens:U.total,hasError:!!H,error:H};return H?Y.warn(`agent run completed with error`,de):Y.info(`agent run completed`,de),await w_({runtime:N,resolvedModelId:F,usage:U,currentUserEntryCoveredByUsage:ie}),await $s({sessionId:l,runParams:k,eventDispatcher:r,transcriptStartIndex:_,result:{text:V,usage:U,durationMs:Date.now()-n,error:H}}),Ic({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:V,usage:U,error:H})}async function C_(e){if(!e.enabled)return[];try{let t=await new fr({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 w_(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 T_(e){Ai(e.dataDir);let n=Date.now(),i=new Mi(e),a=jl(e),o=a.transcriptMessage.trim()||`CRON task`,s=e.sessionStoreName;Y.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:s,...g_(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,Um({sessionId:c,title:Mc(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:h_});await i.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:u,task:o}),Y.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:u,taskLength:o.length,taskPreview:ji(o)});let d={...e,sessionId:u,sessionStoreName:h_,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await S_(d,new bc),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:h_}),toolResultsDir:S(e.dataDir,u,{storeName:h_})}},m=`error`,Y.error(`cron child run failed`,{parentSessionId:c,childSessionId:u,error:r})}await i.dispatchProgress(c,{type:`subagent_complete`,childSessionId:u,task:o,status:m}),Y.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let _=km({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=>E_(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 E_(e,t){if(t<=0)return e.filter(e=>!D_(e));let n=e.reduce((e,t,n)=>(D_(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!D_(e)||r.has(t))}function D_(e){return`source`in e&&e.source===`cron`}async function O_(e,t){if(Ai(e.dataDir),Y.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,...g_(e)}),e.channel===`CRON`&&!e.subagentContext)return T_(e);let n=t??new bc;try{return await S_(e,n)}catch(t){throw e.onProgress&&await e.onProgress({type:`diagnostic`,level:`error`,scope:`runner`,phase:`run_crashed`,message:`agent run crashed before completion`,details:s_(t)}),Y.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}function k_(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:6e5}function A_(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const j_={"AGENTS.md":`---
142
+ `)}`}function ig(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ag(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function og(){let e=vt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function sg(e){let t=e.trim(),n=og();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?H.join(n,t.slice(2)):void 0:H.resolve(t)}const cg=new St({allErrors:!0,strict:!1}),lg=new Map;function ug(e,t){let n=lg.get(t);if(n)return n;let r=cg.compile(e);return lg.set(t,r),r}function dg(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ug(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function fg(e){let t=ag(e?.allow),n=ag(e?.deny),r=ag(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 pg(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=dg({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 mg(e){try{return U.realpathSync(e)}catch{return null}}function hg(e){try{return U.statSync(e)}catch{return null}}function gg(e,t){let n=H.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!H.isAbsolute(n)}function _g(e){return`0o${e.toString(8).padStart(3,`0`)}`}const vg=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),yg=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function bg(e){let t=H.join(e,`package.json`);if(U.existsSync(t))try{let e=JSON.parse(U.readFileSync(t,`utf-8`));return ig(e)?e:void 0}catch{return}}function xg(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 Sg(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Cg(e){let t=mg(e.source),n=mg(e.rootDir);return!t||!n||gg(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function wg(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=H.resolve(r);if(n.has(t))continue;n.add(t);let i=hg(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 Tg(e){return Cg({source:e.source,rootDir:e.rootDir})||wg({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Sg(e.ownershipUid)})}function Eg(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=${_g(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Dg(e){let t=Tg({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Eg(t),source:e.source}),!0):!1}function Og(e){return H.basename(e,H.extname(e))}function kg(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 Ag(e){for(let t of yg){let n=H.join(e,t);if(U.existsSync(n))return n}return null}function jg(e){let t;try{t=U.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=H.join(e.rootDir,n.name);if(n.isFile()){if(!vg.has(H.extname(n.name)))continue;let r=H.dirname(t);if(Dg({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(kg({idHint:Og(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=bg(t),i=xg(r);if(i.status===`ok`){for(let n of i.entries){let i=H.resolve(t,n);if(!gg(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!U.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!vg.has(H.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Dg({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Og(i)}`:Og(i);e.candidates.push(kg({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=Ag(t);a&&(Dg({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(kg({idHint:H.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Mg(e){return e?e.map(sg).filter(e=>typeof e==`string`&&e.length>0):[]}function Ng(){let e=og();if(e)return H.join(e,`.aimax`,`extensions`)}function Pg(e){return H.join(e,`.aimax`,`extensions`)}function Fg(e){return H.join(e,`.aimax`,`extensions`)}function Ig(e={}){let t=[],n=[],r=Mg(e.extraPaths);for(let i of r){if(!U.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=hg(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!vg.has(H.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=H.dirname(i);if(Dg({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(kg({idHint:Og(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&jg({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?jg({rootDir:Pg(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&jg({rootDir:Fg(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Ng();return i?jg({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&&jg({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Lg(e){let t=e.rejectHardlinks??!0,n=mg(e.rootPath),r=mg(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!gg(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=U.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:U.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Rg=`aimax.plugin.json`,zg=[Rg];function Bg(e){for(let t of zg){let n=H.join(e,t);if(U.existsSync(n))return n}return H.join(e,Rg)}function Vg(e,t=!0){let n=Bg(e),r=Lg({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(U.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{U.closeSync(r.fd)}if(!ig(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=ig(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=ag(i.skills),f;return ig(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 Hg(e){let t=new Map,n=[];for(let r of e){let e=Vg(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 Ug=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Wg(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Ug.ERROR){q.error(i);return}if(e===Ug.WARN){q.warn(i);return}q.info(i)}function Gg(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Wg(Ug.INFO,e.pluginId,t,n),warn:n=>Wg(Ug.WARN,e.pluginId,t,n),error:n=>Wg(Ug.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}function Kg(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 qg(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 Jg(e){let t=[...e.registry.diagnostics],n=new _h,r=new qr,i=[],a=[],o=e.runtime?.llm?li({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Yg(e.runtime?.llmAllowlist),c=Ct(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=Kg({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=qg({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=Gg({pluginId:l.id,env:e.runtime?.env}),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(!Xg(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`);se({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`);he({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=H.isAbsolute(e)?e:H.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Kr(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=H.isAbsolute(e)?e:H.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Yg(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Xg(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function Zg(e={}){let t=fg(e.config),n=Ig({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Hg(n.candidates),i=pg({config:t,registry:r}),a=Jg({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 Qg(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?Zg({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):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 qr,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 $g(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Fm(t),o=n,s=!o,c=X(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=Qg({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i}),d=u.hookRegistry,f=await Im({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=>lc({sessionId:o,runParams:t,hookRegistry:d,hookContext:l,eventDispatcher:i,...e})}}function e_(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function t_(e){if(!(e instanceof Error))return{errorValue:e_(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]=e_(n[e]));return t}async function n_(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...t_(e.error)}})}function r_(e,t,n){return H.join(d(e,t,n),`pending-ui-tool.json`)}async function i_(e,t,n,r){let i=d(e,t,r);await V.mkdir(i,{recursive:!0}),await a(r_(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function a_(e,t,n){let r=await l(r_(e,t,n));return r===null?null:JSON.parse(r)}async function o_(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await i_(e,t,a,r),a}async function s_(e,t,n,r,i){let a=await a_(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 i_(e,t,o,i),o}async function c_(e,t,n){try{await V.unlink(r_(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function l_(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 u_(e,t,n,r,i,a){let o=await z(e,t,{storeName:a?.storeName});await l_(e,t,n,a);let s=await Tt(e,t,n,r,a);return s.goal&&await pl(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function d_(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Ke(t))}async function f_(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=wi();if(i=await Ti(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(bi(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=p_(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 p_(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)}const m_=2e4,h_=15e4,g_=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function __(e){return H.join(e,`.aimax`)}async function v_(e){let t=__(e),n=[];for(let e of g_){let r=H.join(t,e);try{let t=await V.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await V.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 y_(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(`
143
+ `),s].join(`
144
+ `),truncated:!0,originalLength:r.length}}function b_(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function x_(e,t){let n=t?.maxChars??m_,r=Math.max(1,t?.totalMaxChars??Math.max(n,h_)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=b_(`[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}=y_(a.content??``,a.name,e),l=b_(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 S_=`You are a personal assistant running inside AiMax.`;async function C_(e){try{return{presetSystemPrompt:$e(await V.readFile(e,`utf-8`)).content.trim()||S_}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:S_};throw e}}async function w_(){return C_(`/aimax_pvc/system_prompt.md`)}async function T_(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await v_(t.dataDir),o=[],s=x_(a,{warn:e=>o.push(e)}),c=await w_();await i.dispatchDiagnostic(n,{level:o.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length}}),q.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await am(t.dataDir,r.pluginSkillDirs,l),d=await kr({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),q.info(`skills loaded`,{sessionId:n,skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length}),await i.dispatchDiagnostic(n,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,agents:d.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),q.info(`custom agents loaded`,{sessionId:n,agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,requestedAgentName:m.requestedAgentName}),{contextFiles:s,bootstrapWarnings:o,skills:u,autoSkillCategories:await E_({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function E_(e){if(!e.enabled)return[];try{let t=await new K({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)}}),[]}}var D_=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const O_=`crons`;function k_(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:si(e.message)}}async function A_(e,t){oi(e.dataDir),tc();let n=Date.now(),r=new ci(e),i=ml(e);q.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 $g({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;q.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}}),q.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 N(e.dataDir,Lm({sessionId:l,title:cc(a),channel:e.channel}),X(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 T_({runParams:e,sessionId:l,pluginContext:h,eventDispatcher:r}),b=e=>g.appendTranscriptEntry(e),x=await gl({invocation:i,skills:y.skills,sessionId:l,isNewSession:u,initialUserEntryPersisted:o,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r});if(x.kind===`completed`)return q.info(`agent run short-circuited`,{sessionId:l,durationMs:Date.now()-n,hasError:!!x.result.error,paused:!!x.result.paused,uiToolPending:!!x.result.uiToolPending,textLength:x.result.text.length}),x.result;let S=x.effectivePrompt;a=x.transcriptMessage;let C=typeof S==`string`?S:a;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof S==`string`?`string`:`messages`,transcriptLength:a.length}}),q.info(`invocation resolved`,{sessionId:l,promptType:typeof S==`string`?`string`:`messages`,transcriptLength:a.length});let w=await Zh({session:{runParams:y.runParamsWithAgentPolicy,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},runtimeInputs:{contextFiles:y.contextFiles,bootstrapWarnings:y.bootstrapWarnings,skills:y.skills,autoSkillCategories:y.autoSkillCategories,effectivePromptText:C,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:y.skillsLoadPaths,presetSystemPrompt:y.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>A_(e,new Xs),createModel:Sr,abortSignal:v.signal}}),T=w.agent,E=w.resolvedModelId;await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:E,historyMessageCount:w.historyMessages.length,pluginToolCount:h.pluginTools.length}}),q.info(`agent runtime created`,{sessionId:l,modelId:E,historyMessageCount:w.historyMessages.length,pluginToolCount:h.pluginTools.length});let D=I_(e.timeoutMs),O=!1,k=setTimeout(()=>{O=!0,v.abort(),T.abort(),r.dispatchDiagnostic(l,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:D}}),q.warn(`agent run timed out`,{sessionId:l,timeoutMs:D})},D);v.signal.addEventListener(`abort`,()=>T.abort());let A=new D_,j=``,M,ee=!1,P=new wt;await l_(e.dataDir,l,P,{storeName:e.sessionStoreName});let F=new ya,te={runParams:y.runParamsWithAgentPolicy,sessionId:l,hookRegistry:p,hookContext:f,runContext:g,eventDispatcher:r},ne={registry:t,spawnFn:e=>A_(e,new Xs),createModel:Sr,abortSignal:v.signal},I=(e,t,n)=>({turnKind:e,budget:F,reloadHistory:()=>$h({session:te,runtime:n,effectivePromptText:t,dependencies:ne}),onPhase:async(e,t)=>{await r.dispatchDiagnostic(l,{level:e.includes(`failed`)||e.includes(`skipped`)?`warn`:`info`,scope:`runner`,phase:e,message:e.replace(/_/g,` `),details:t})}});try{if(d_(e)){let t=await f_({params:e,agent:T,sessionId:l,eventDispatcher:r,appendEntry:b,abortSignal:v.signal});return j=t.text,fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(a);ee=e,o=e||o}await r.dispatchDiagnostic(l,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let i=await zt(e.dataDir,l,S,{storeName:e.sessionStoreName});q.info(`first agent turn started`,{sessionId:l,modelId:E});let s=typeof i.prompt==`string`?i.prompt:C,c=await Ea({agent:T,message:i.prompt,continueFromHistory:!!e.uiToolResume,sessionId:l,channel:e.channel,modelId:E,historyMessages:w.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,retry:e.llmRetry,contextLimitRecovery:I(`first`,s,w),onTurnRecordProduced:async(e,t)=>{e&&await b(e);for(let e of t)await b(e)}});j=c.text,A.add(c.inputTokens,c.outputTokens),c.error&&(M=c.error);let d=!!c.contextLimitRecoverySucceeded;i.hadObjectiveUpdatedSteering&&!c.error&&await Bt(e.dataDir,l,{storeName:e.sessionStoreName}),await r.dispatchDiagnostic(l,{level:c.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let m={sessionId:l,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?q.warn(`first agent turn completed with error`,m):q.info(`first agent turn completed`,m);let h=await u_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`});h.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`}),q.info(`announce loop started`,{sessionId:l});let _=await ng({agent:T,registry:t,sessionId:l,resolvedModelId:E,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,retry:e.llmRetry,appendEntry:b});if(_.text&&(j=_.text),A.add(_.inputTokens,_.outputTokens),_.error&&!M&&(M=_.error),await r.dispatchDiagnostic(l,{level:_.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens}}),h=await u_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`}),h.budgetLimited&&await r.dispatchDiagnostic(l,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Pt()){let n=new Nt;n.reset(),c.error&&!d&&(n.lastTurnHadOutput=!1);let i=!0,a=Ue;for(;i&&n.continuationCount<a&&!v.signal.aborted;)if(i=await Lt({agent:T,dataDir:e.dataDir,sessionId:l,sessionStoreName:e.sessionStoreName,state:n,accounting:P,abortSignal:v.signal,executeTurn:async t=>{let n=await Ea({agent:T,message:t,continueFromHistory:!1,sessionId:l,channel:e.channel,modelId:E,historyMessages:w.historyMessages,eventDispatcher:r,hooks:p,hookCtx:f,abortSignal:v.signal,contextLimitRecovery:I(`continuation`,t,w),onTurnRecordProduced:async(e,t)=>{await Rt(b,e,t)}});A.add(n.inputTokens,n.outputTokens),j=n.text||j,n.error&&!M&&(M=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 u_(e.dataDir,l,P,A.snapshot(),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 ng({agent:T,registry:t,sessionId:l,resolvedModelId:E,eventDispatcher:r,hookRegistry:p,hookContext:f,abortSignal:v.signal,appendEntry:b});A.add(e.inputTokens,e.outputTokens),e.text&&(j=e.text),e.error&&!M&&(M=e.error)}}let y={sessionId:l,hasError:!!_.error,error:_.error,inputTokens:_.inputTokens,outputTokens:_.outputTokens};_.error?q.warn(`announce loop completed with error`,y):q.info(`announce loop completed`,y)}catch(t){if(bi(t)){let i=t,o=e.subagentContext?.parentSessionId??l,s=o===i.request.sessionId?i.request:{...i.request,sessionId:o};await be(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}}),q.info(`agent paused for HITL`,{sessionId:l,requestId:s.requestId,kind:s.kind,checkpointPhase:i.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={...A.snapshot()};return await j_({runtime:w,resolvedModelId:E,usage:c,currentUserEntryCoveredByUsage:ee}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j||`[HITL paused] ${i.request.title}: ${i.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Si(t)){let i=t,o=i.request.outputSchema.properties??{};await o_(e.dataDir,l,i.request,X(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}}),q.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={...A.snapshot()};return await j_({runtime:w,resolvedModelId:E,usage:s,currentUserEntryCoveredByUsage:ee}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j||``,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}})}if(O&&L_(t))M=`Run timed out after ${D}ms`;else throw await n_({dispatcher:r,sessionId:l,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:u}}),q.error(`agent run failed`,{sessionId:l,channel:e.channel,isNewSession:u,error:t instanceof Error?t.message:String(t)}),t}finally{clearTimeout(k);try{await u_(e.dataDir,l,P,A.snapshot(),r,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}P.clearActiveGoal(),$s(l),g.stop()}let R=A.snapshot();O&&(M=`Run timed out after ${D}ms`),await r.dispatchDiagnostic(l,{level:M?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:R.input,outputTokens:R.output,totalTokens:R.total,hasError:!!M,error:M}});let z={sessionId:l,durationMs:Date.now()-n,inputTokens:R.input,outputTokens:R.output,totalTokens:R.total,hasError:!!M,error:M};return M?q.warn(`agent run completed with error`,z):q.info(`agent run completed`,z),await j_({runtime:w,resolvedModelId:E,usage:R,currentUserEntryCoveredByUsage:ee}),await ks({sessionId:l,runParams:y.runParamsWithAgentPolicy,eventDispatcher:r,transcriptStartIndex:_,result:{text:j,usage:R,durationMs:Date.now()-n,error:M}}),fc({sessionId:l,isNewSession:u,transcriptMessage:a,runParams:e,hookRegistry:p,hookContext:f,startTime:n,eventDispatcher:r,text:j,usage:R,error:M})}async function j_(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 M_(e){oi(e.dataDir);let n=Date.now(),i=new ci(e),a=ml(e),o=a.transcriptMessage.trim()||`CRON task`,s=e.sessionStoreName;q.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:s,...k_(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 N(e.dataDir,Lm({sessionId:c,title:cc(o),channel:e.channel}),{storeName:s});let u=await C(e.dataDir,e.channel,{storeName:O_});await i.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:u,task:o}),q.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:u,taskLength:o.length,taskPreview:si(o)});let d={...e,sessionId:u,sessionStoreName:O_,subagentContext:{depth:1,parentSessionId:c}},f,m=`done`;try{f=await A_(d,new Xs),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:O_}),toolResultsDir:S(e.dataDir,u,{storeName:O_})}},m=`error`,q.error(`cron child run failed`,{parentSessionId:c,childSessionId:u,error:r})}await i.dispatchProgress(c,{type:`subagent_complete`,childSessionId:u,task:o,status:m}),q.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let _=Cm({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=>N_(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 N_(e,t){if(t<=0)return e.filter(e=>!P_(e));let n=e.reduce((e,t,n)=>(P_(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!P_(e)||r.has(t))}function P_(e){return`source`in e&&e.source===`cron`}async function F_(e,t){if(oi(e.dataDir),q.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,...k_(e)}),e.channel===`CRON`&&!e.subagentContext)return M_(e);let n=t??new Xs;try{return await A_(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:t_(t)}),q.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}function I_(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:6e5}function L_(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const R_={"AGENTS.md":`---
145
145
  title: "AGENTS.md Template"
146
146
  summary: ".aimax template for AGENTS.md"
147
147
  read_when:
@@ -434,7 +434,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
434
434
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
435
435
 
436
436
  Add whatever helps you do your job. This is your cheat sheet.
437
- `},M_=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function N_(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 P_(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 F_(e){let t=wt(e);return[e,t,G.join(t,`skills`),G.join(t,`sessions`),G.join(t,`memory`),G.join(e,`workspace`)]}function I_(e){let t=wt(e);return[...M_.filter(e=>e!==`BOOTSTRAP.md`).map(e=>G.join(t,e)),G.join(t,`MEMORY.md`)]}function L_(e){return G.join(wt(e),`.bootstrapped`)}async function R_(e){try{return(await W.stat(L_(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function z_(e){let t=L_(e);await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,``,{encoding:`utf-8`})}async function B_(e){let t=[],n=[];for(let n of F_(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 I_(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 V_(e){return(await B_(e)).ready}async function H_(e){if(await R_(e))return{ready:!0,performedBootstrap:!1};if((await B_(e)).ready)return await z_(e),{ready:!0,performedBootstrap:!1};let t=await U_(e);return await z_(e),{ready:!0,performedBootstrap:!0,result:t}}async function U_(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=wt(e),r=G.join(e,`workspace`),i=G.join(n,`skills`),a=G.join(n,`sessions`),o=G.join(n,`memory`);await N_(e,t),await N_(n,t),await N_(i,t),await N_(a,t),await N_(o,t),await N_(r,t);for(let e of M_){let r=j_[e]??``;await P_(G.join(n,e),r,t)}return await P_(G.join(n,`MEMORY.md`),``,t),t}async function W_(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 G_(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 K_(e,t){let n=await W_(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 q_(e,t=7){let n=await W_(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 G_(e,n),i}var J_=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function Y_(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function X_(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 R(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 B(t,n,l,s)).trim();if(u!==c){if(!a)throw new J_(`A different goal already exists for this session. Use --force to replace it.`,Y_(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 J_(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,Y_(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 Z_(e,t,n,r){let i=await be(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?He(i.request)?(await ge(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 Q_(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ye(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 Z_(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await ge(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 $_={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 ev(e){return e.action===`timeout`?$_.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?$_.approval.summary.approved:$_.approval.summary.denied}function tv(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:ev(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function nv(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 rv(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 iv(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
437
+ `},z_=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function B_(e,t){try{if(!(await V.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 V.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function V_(e,t,n){try{if(!(await V.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 V.mkdir(H.dirname(e),{recursive:!0});try{await V.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 H_(e){let t=__(e);return[e,t,H.join(t,`skills`),H.join(t,`sessions`),H.join(t,`memory`),H.join(e,`workspace`)]}function U_(e){let t=__(e);return[...z_.filter(e=>e!==`BOOTSTRAP.md`).map(e=>H.join(t,e)),H.join(t,`MEMORY.md`)]}function W_(e){return H.join(__(e),`.bootstrapped`)}async function G_(e){try{return(await V.stat(W_(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function K_(e){let t=W_(e);await V.mkdir(H.dirname(t),{recursive:!0}),await V.writeFile(t,``,{encoding:`utf-8`})}async function q_(e){let t=[],n=[];for(let n of H_(e))try{(await V.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of U_(e))try{(await V.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 J_(e){return(await q_(e)).ready}async function Y_(e){if(await G_(e))return{ready:!0,performedBootstrap:!1};if((await q_(e)).ready)return await K_(e),{ready:!0,performedBootstrap:!1};let t=await X_(e);return await K_(e),{ready:!0,performedBootstrap:!0,result:t}}async function X_(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=__(e),r=H.join(e,`workspace`),i=H.join(n,`skills`),a=H.join(n,`sessions`),o=H.join(n,`memory`);await B_(e,t),await B_(n,t),await B_(i,t),await B_(a,t),await B_(o,t),await B_(r,t);for(let e of z_){let r=R_[e]??``;await V_(H.join(n,e),r,t)}return await V_(H.join(n,`MEMORY.md`),``,t),t}async function Z_(e){let t=H.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await V.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 Q_(e,t){let n=H.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 V.mkdir(H.dirname(n),{recursive:!0}),await V.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function $_(e,t){let n=await Z_(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 ev(e,t=7){let n=await Z_(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 Q_(e,n),i}var tv=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function nv(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function rv(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 B(t,n,l,s)).trim();if(u!==c){if(!a)throw new tv(`A different goal already exists for this session. Use --force to replace it.`,nv(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 tv(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,nv(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 iv(e,t,n,r){let i=await Ce(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ge(i.request)?(await ye(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 av(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await Se(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 iv(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await ye(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 ov={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 sv(e){return e.action===`timeout`?ov.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?ov.approval.summary.approved:ov.approval.summary.denied}function cv(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:sv(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function lv(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 uv(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 dv(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
438
438
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
439
439
  `)):(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(`
440
- `))}export{fr as AutoSkillsLoader,Ct as BOOTSTRAP_FILE_NAMES,xt as BOOTSTRAP_MAX_CHARS,St as BOOTSTRAP_TOTAL_MAX_CHARS,en as ContinuationState,ee as DEFAULT_SESSION_STORE_NAME,$t as ENV_GOAL_CONTINUATION,zc as GOAL_MULTILINE_TEMPLATE_EXAMPLE,Gt as GoalAccounting,J_ as GoalConflictError,$_ as HITL_MESSAGES,Ui as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,yc as MAX_CHILDREN_PER_SESSION,vc as MAX_SUBAGENT_DEPTH,le as MemoryIndexManager,Wg as PLUGIN_MANIFEST_FILENAME,Gg as PLUGIN_MANIFEST_FILENAMES,_i as PluginHookRegistry,Ch as PluginToolRegistry,qr as SYSTEM_AGENTS_DIR,bc as SubagentRegistry,Gi as UiToolPauseSignal,Ie as addAgent,Me as addBinding,Yr as agentDirCandidates,ri as agentVisibility,wt as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,P as appendGoalEvent,Dp as appendRecentToMemory,o as appendSessionFile,Ep as appendToMemory,p as appendTranscriptEntry,X_ as applyCliGoalBeforeRun,ev as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,qn as autoSkillsDir,U_ as bootstrapMountLayout,si as buildAgentDelegationPrompt,ci as buildAgentTaskPrompt,Vc as buildAimaxGoalCliHelpExtra,Ot as buildBootstrapContextFiles,Yt as buildBudgetLimitPrompt,Jt as buildContinuationPrompt,Zt as buildGoalContextItem,Bc as buildGoalSlashHelpText,Xt as buildObjectiveUpdatedPrompt,iv as buildResumeNarration,Wt as buildSkillsPrompt,km as buildSubagentAnnounceMessage,xh as buildSystemPrompt,q_ as cleanupOldSubagentRecords,xe as clearPendingHitl,m_ as clearPendingUiTool,k as collapseLogPath,cn as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,rn as continuationTurnHadMeaningfulOutput,Zr as createAgentDefinitionsContext,Xm as createAgentTools,ap as createApplyPatchTool,Xo as createAutoSkillCategoriesTool,Zo as createAutoSkillListTool,Qo as createAutoSkillSearchTool,$o as createAutoSkillViewTool,ur as createAutoSkillsLoader,Bf as createBashTool,Nm as createBatchSubagentSpawnTool,se as createBuiltinMemoryProvider,pf as createContextManager,Xf as createEditFileTool,wf as createExecTool,qm as createImageTool,Qf as createListDirTool,Fp as createMemoryAppendTool,Yp as createMemoryForgetTool,Np as createMemoryGetTool,qp as createMemoryListTool,Gp as createMemoryLogTool,jp as createMemorySearchTool,Zp as createMemoryUpdateTool,Lp as createMemoryWriteTool,_e as createPendingHitl,f_ as createPendingUiTool,gi as createPluginProgressEmitter,Zg as createPluginRuntime,Of as createProcessTool,Kf as createReadFileTool,C as createSession,zd as createSessionContextStore,$p as createSessionSearchTool,bm as createSkillListTool,xm as createSkillLoadTool,Mm as createSubagentSpawnTool,Lm as createSubagentsTool,Ym as createUiTool,Jf as createWriteFileTool,A as cronExecutionsPath,Jm as defaultUiToolInputSchema,V as deleteGoal,kp as deleteMemoryFile,Hg as discoverAIMaxPlugins,ln as emitGoalUpdatedProgress,H_ as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,ai as filterSkillsForAgent,oi as filterToolsForAgent,ni as findAgentDefinition,Vt as findSkillByName,Kt as flushAccounting,tv as formatApprovalResolution,nv as formatClarifyResolution,rv as formatReviewResolution,Dc as generateSessionTitle,ke as getAgentConfig,Tp as getMemoryLines,N as goalEventsPath,re as goalObjectiveMdPath,z as goalPath,R_ as hasBootstrapSentinel,he as hitlHistoryPath,r_ as initializePluginSystem,B_ as inspectBootstrapMountLayout,D as inspectSession,V_ as isBootstrapMountLayoutReady,tn as isContinuationEnabled,Qt as isGoalContext,Wi as isHitlPauseSignal,Ki as isUiToolPauseSignal,Ce as listAgents,Qc as listAvailableSlashCommands,Ne as listBindings,xp as listMemoryFiles,w as listSessionSummaries,y as listSessions,K_ as listSubagentRunsFromDisk,ei as loadAgentDefinitionsFromDir,Fe as loadAgentsConfig,v as loadArtifactOperations,Tt as loadBootstrapFiles,f as loadCronExecutionRecords,be as loadPendingHitl,be as readPendingHitl,d_ as loadPendingUiTool,d_ as readPendingUiTool,qg as loadPluginManifest,Jg as loadPluginManifestRegistry,e_ as loadPlugins,j as loadSessionContextSnapshot,ne as loadSessionMetadata,Ut as loadSkillView,Rt as loadSkills,Bt as loadSkillsFromDirs,zt as loadSkillsWithPluginDirs,W_ as loadSubagentRegistryFromDisk,m as loadTranscript,an as maybeContinueGoalIfIdle,_p as memoryDir,te as metadataPath,F as mirrorGoalStatusToSession,we as normalizeAgentId,vg as normalizePluginsConfig,u as normalizeSessionStoreName,ti as parseAgentDefinition,me as pendingHitlPath,l_ as pendingUiToolPath,sn as prependObjectiveUpdatedSteeringIfNeeded,vp as primaryMemoryPath,ii as publicAgentDefinitions,R as readGoal,ve as readHitlHistory,Sp as readMemoryFile,Cp as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,ae as registerEmbeddingProvider,fe as registerMemoryProvider,Ae as removeAgent,Le as removeBindings,Op as replaceMemoryFile,H as resetEmbeddingProviderRegistryForTests,pe as resetMemoryProviderRegistryForTests,$r as resolveAgentDefinitionsContext,Te as resolveAgentDir,Ee as resolveAgentIdByBinding,Pe as resolveAgentsConfigPath,je as resolveDefaultAgentId,ce as resolveEmbeddingProvider,B as resolveGoalObjective,Q_ as resolveHitlRequest,Q_ as resolvePendingHitl,de as resolveMemoryProvider,Oe as resolveModelFallbacks,De as resolveModelString,p_ as resolvePendingUiTool,Kg as resolvePluginManifestPath,t as rewriteTranscript,O_ as runAgent,Se as saveAgentsConfig,M as saveSessionMetadata,G_ as saveSubagentRegistryToDisk,Xr as scanAgentDefinitions,wp as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,nn as shouldContinueGoal,Mt as skillsDir,S as toolResultsDir,e as transcriptPath,ge as transitionHitlStatus,Re as updateAgent,ze as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,yg as validatePluginsConfig,Z_ as validateResume,Th as wrapToolsWithHooks,L as writeGoal,a as writeSessionFile};
440
+ `))}export{K as AutoSkillsLoader,g_ as BOOTSTRAP_FILE_NAMES,m_ as BOOTSTRAP_MAX_CHARS,h_ as BOOTSTRAP_TOTAL_MAX_CHARS,Nt as ContinuationState,A as DEFAULT_SESSION_STORE_NAME,Mt as ENV_GOAL_CONTINUATION,hc as GOAL_MULTILINE_TEMPLATE_EXAMPLE,wt as GoalAccounting,tv as GoalConflictError,ov as HITL_MESSAGES,yi as HitlPauseSignal,T as MAX_ARTIFACT_CONTENT_CHARS,Ys as MAX_CHILDREN_PER_SESSION,Js as MAX_SUBAGENT_DEPTH,de as MemoryIndexManager,Rg as PLUGIN_MANIFEST_FILENAME,zg as PLUGIN_MANIFEST_FILENAMES,qr as PluginHookRegistry,_h as PluginToolRegistry,Cr as SYSTEM_AGENTS_DIR,Xs as SubagentRegistry,xi as UiToolPauseSignal,ze as addAgent,Fe as addBinding,Tr as agentDirCandidates,Nr as agentVisibility,__ as aimaxDir,O as appendArtifactOperation,b as appendCronExecutionRecord,te as appendGoalEvent,cp as appendRecentToMemory,o as appendSessionFile,sp as appendToMemory,p as appendTranscriptEntry,rv as applyCliGoalBeforeRun,sv as approvalSummaryFromResolution,E as artifactsPath,s as atomicWriteSessionFile,wn as autoSkillsDir,X_ as bootstrapMountLayout,Lr as buildAgentDelegationPrompt,Rr as buildAgentTaskPrompt,_c as buildAimaxGoalCliHelpExtra,x_ as buildBootstrapContextFiles,Ot as buildBudgetLimitPrompt,Dt as buildContinuationPrompt,At as buildGoalContextItem,gc as buildGoalSlashHelpText,kt as buildObjectiveUpdatedPrompt,dv as buildResumeNarration,um as buildSkillsPrompt,Cm as buildSubagentAnnounceMessage,hh as buildSystemPrompt,ev as cleanupOldSubagentRecords,we as clearPendingHitl,c_ as clearPendingUiTool,k as collapseLogPath,Bt as confirmObjectiveUpdatedSteeringConsumed,h as contextSnapshotPath,It as continuationTurnHadMeaningfulOutput,Dr as createAgentDefinitionsContext,Wm as createAgentTools,Vf as createApplyPatchTool,Eo as createAutoSkillCategoriesTool,Do as createAutoSkillListTool,Oo as createAutoSkillSearchTool,ko as createAutoSkillViewTool,Vn as createAutoSkillsLoader,Sf as createBashTool,Dm as createBatchSubagentSpawnTool,le as createBuiltinMemoryProvider,Jd as createContextManager,Mf as createEditFileTool,of as createExecTool,Vm as createImageTool,Pf as createListDirTool,gp as createMemoryAppendTool,Ap as createMemoryForgetTool,mp as createMemoryGetTool,Op as createMemoryListTool,Ep as createMemoryLogTool,fp as createMemorySearchTool,Mp as createMemoryUpdateTool,vp as createMemoryWriteTool,be as createPendingHitl,o_ as createPendingUiTool,Kr as createPluginProgressEmitter,Gg as createPluginRuntime,uf as createProcessTool,Of as createReadFileTool,C as createSession,xd as createSessionContextStore,Pp as createSessionSearchTool,mm as createSkillListTool,hm as createSkillLoadTool,Em as createSubagentSpawnTool,jm as createSubagentsTool,Um as createUiTool,Af as createWriteFileTool,j as cronExecutionsPath,Hm as defaultUiToolInputSchema,ie as deleteGoal,up as deleteMemoryFile,Ig as discoverAIMaxPlugins,fl as emitGoalUpdatedProgress,Y_ as ensureBootstrapMountLayout,g as ensureSession,_ as exportSession,Fr as filterSkillsForAgent,Ir as filterToolsForAgent,Mr as findAgentDefinition,sm as findSkillByName,Tt as flushAccounting,cv as formatApprovalResolution,lv as formatClarifyResolution,uv as formatReviewResolution,rc as generateSessionTitle,Me as getAgentConfig,op as getMemoryLines,F as goalEventsPath,R as goalObjectiveMdPath,re as goalPath,G_ as hasBootstrapSentinel,ve as hitlHistoryPath,Zg as initializePluginSystem,q_ as inspectBootstrapMountLayout,D as inspectSession,J_ as isBootstrapMountLayoutReady,Pt as isContinuationEnabled,jt as isGoalContext,bi as isHitlPauseSignal,Si as isUiToolPauseSignal,Ee as listAgents,Oc as listAvailableSlashCommands,Ie as listBindings,np as listMemoryFiles,w as listSessionSummaries,y as listSessions,$_ as listSubagentRunsFromDisk,Ar as loadAgentDefinitionsFromDir,Re as loadAgentsConfig,v as loadArtifactOperations,v_ as loadBootstrapFiles,f as loadCronExecutionRecords,Ce as loadPendingHitl,Ce as readPendingHitl,a_ as loadPendingUiTool,a_ as readPendingUiTool,Vg as loadPluginManifest,Hg as loadPluginManifestRegistry,Jg as loadPlugins,M as loadSessionContextSnapshot,P as loadSessionMetadata,lm as loadSkillView,im as loadSkills,om as loadSkillsFromDirs,am as loadSkillsWithPluginDirs,Z_ as loadSubagentRegistryFromDisk,m as loadTranscript,Lt as maybeContinueGoalIfIdle,$f as memoryDir,ee as metadataPath,ne as mirrorGoalStatusToSession,De as normalizeAgentId,fg as normalizePluginsConfig,u as normalizeSessionStoreName,jr as parseAgentDefinition,_e as pendingHitlPath,r_ as pendingUiToolPath,zt as prependObjectiveUpdatedSteeringIfNeeded,ep as primaryMemoryPath,Pr as publicAgentDefinitions,z as readGoal,xe as readHitlHistory,rp as readMemoryFile,ip as readPrimaryMemory,l as readSessionFile,i as readSessionFileContent,se as registerEmbeddingProvider,he as registerMemoryProvider,Ne as removeAgent,Be as removeBindings,lp as replaceMemoryFile,ae as resetEmbeddingProviderRegistryForTests,ge as resetMemoryProviderRegistryForTests,kr as resolveAgentDefinitionsContext,Oe as resolveAgentDir,ke as resolveAgentIdByBinding,Le as resolveAgentsConfigPath,Pe as resolveDefaultAgentId,ue as resolveEmbeddingProvider,B as resolveGoalObjective,av as resolveHitlRequest,av as resolvePendingHitl,me as resolveMemoryProvider,je as resolveModelFallbacks,Ae as resolveModelString,s_ as resolvePendingUiTool,Bg as resolvePluginManifestPath,t as rewriteTranscript,F_ as runAgent,Te as saveAgentsConfig,N as saveSessionMetadata,Q_ as saveSubagentRegistryToDisk,Er as scanAgentDefinitions,ap as searchMemory,d as sessionDir,n as sessionMemoryPath,c as sessionsDir,Ft as shouldContinueGoal,Qp as skillsDir,S as toolResultsDir,e as transcriptPath,ye as transitionHitlStatus,Ve as updateAgent,He as updateAgentIdentity,I as updateGoal,x as updateSessionMetadata,pg as validatePluginsConfig,iv as validateResume,yh as wrapToolsWithHooks,L as writeGoal,a as writeSessionFile};