@gencode/agents 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/builtin-provider-DMxBOIZn.js +71 -0
- package/dist/index.d.ts +13 -37
- package/dist/index.js +86 -86
- package/package.json +1 -1
- package/dist/builtin-provider-DweGOw8P.js +0 -71
package/dist/index.js
CHANGED
|
@@ -1,118 +1,118 @@
|
|
|
1
|
-
import{A as e,B as t,C as n,D as r,E as i,F as a,
|
|
1
|
+
import{A as e,B as t,C as n,D as r,E as i,F as a,H as o,I as s,L as c,M as l,N as u,O as d,P as f,R as p,S as m,T as h,U as g,V as _,_ as v,a as y,b,c as x,d as S,f as C,g as w,h as T,i as E,j as D,k as O,l as k,m as ee,n as A,o as j,p as M,r as N,s as te,u as P,v as F,w as I,x as L,y as R,z}from"./builtin-provider-DMxBOIZn.js";import{i as B,n as ne,r as V}from"./provider-registry-CxtHsHdk.js";import{_ as re,a as ie,c as ae,d as oe,f as se,g as ce,h as le,i as ue,l as de,m as fe,n as pe,o as me,p as he,s as ge,t as _e,u as ve,v as ye}from"./config-DG3Q1aJ6.js";import{formatTaskForDisplay as be,isHitlExpired as xe,isHitlTool as Se,validateUiToolResult as Ce}from"@gencode/shared";import H,{readFile as we}from"node:fs/promises";import U,{join as Te}from"node:path";import Ee from"gray-matter";import{TextDecoder as De}from"node:util";import{createHash as Oe,randomUUID as ke}from"node:crypto";import{Agent as Ae}from"@mariozechner/pi-agent-core";import{AsyncLocalStorage as je}from"node:async_hooks";import W from"node:fs";import Me from"log4js";import{Type as G,calculateCost as Ne,getEnvApiKey as Pe,parseStreamingJson as Fe,registerApiProvider as Ie,registerBuiltInApiProviders as Le,supportsXhigh as Re}from"@mariozechner/pi-ai";import ze from"openai";import{AssistantMessageEventStream as Be}from"@mariozechner/pi-ai/dist/utils/event-stream.js";import{sanitizeSurrogates as Ve}from"@mariozechner/pi-ai/dist/utils/sanitize-unicode.js";import{buildCopilotDynamicHeaders as He,hasCopilotVisionInput as Ue}from"@mariozechner/pi-ai/dist/providers/github-copilot-headers.js";import{buildBaseOptions as We,clampReasoning as Ge}from"@mariozechner/pi-ai/dist/providers/simple-options.js";import{transformMessages as Ke}from"@mariozechner/pi-ai/dist/providers/transform-messages.js";import qe from"node:os";import{spawn as Je}from"node:child_process";import{isBinaryFile as Ye}from"isbinaryfile";import Xe from"ajv";import{createJiti as Ze}from"jiti";const Qe=2e4,$e=15e4,et=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function tt(e){return U.join(e,`.aimax`)}async function nt(e){let t=tt(e),n=[];for(let e of et){let r=U.join(t,e);try{let t=await H.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await H.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 rt(e,t,n){let r=e.trimEnd();if(r.length<=n)return{result:r,truncated:!1,originalLength:r.length};let i=Math.floor(n*.7),a=Math.floor(n*.2),o=r.slice(0,i),s=r.slice(-a);return{result:[o,[``,`[...truncated, read ${t} for full content...]`,`…(truncated ${t}: kept ${i}+${a} chars of ${r.length})…`,``].join(`
|
|
2
2
|
`),s].join(`
|
|
3
|
-
`),truncated:!0,originalLength:r.length}}function
|
|
4
|
-
`);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}async function
|
|
3
|
+
`),truncated:!0,originalLength:r.length}}function it(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function at(e,t){let n=t?.maxChars??Qe,r=Math.max(1,t?.totalMaxChars??Math.max(n,$e)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=it(`[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}=rt(a.content??``,a.name,e),l=it(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 ot=`You are a personal assistant running inside AiMax.`;async function st(e){try{return{presetSystemPrompt:Ee(await H.readFile(e,`utf-8`)).content.trim()||ot}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:ot};throw e}}async function ct(){return st(`/aimax/system_prompt.md`)}function lt(e){return U.join(e,`.aimax`,`skills`)}function ut(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function dt(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${ut(n)}\n`)}function ft(e){let t=Ee(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
|
|
4
|
+
`);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}async function pt(e){return ht([lt(e)])}async function mt(e,t,n=[]){return ht([...n,...t,lt(e)])}async function ht(e){let t=new Map;for(let n of e){let e;try{e=await H.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=U.join(n,e,`SKILL.md`),i;try{i=await H.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a;try{a=ft(i)}catch(t){dt(e,r,t);continue}t.set(e,{name:e,description:a,location:r})}}return Array.from(t.values()).slice(0,50)}async function gt(e,t){let n=t.trim();if(!n)return;let r=(await ht(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:U.dirname(r.location)}}async function _t(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=U.resolve(r),a=U.basename(i)===`SKILL.md`?i:U.join(i,`SKILL.md`);if(U.basename(a)!==`SKILL.md`)return;let o;try{o=await H.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s;try{s=ft(o)}catch(e){dt(n,a,e);return}return{skill:{name:n,description:s,location:a},rootDir:U.dirname(a)}}async function vt(e,t,n){let r=n?.trim()?await _t(t,n):await gt(e,t);if(!r)return;let i=await H.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function yt(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
|
|
5
5
|
`)).join(`
|
|
6
|
-
`)}\n</available_skills>`}function Dt(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 Ot(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(It(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}Lt(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 kt(e,t={}){let n=Pt(t.limit,`limit`),r=Ft(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!Lt(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Nt(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function At(e,t){let n=Ft(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 jt(e,t=80){let n=Ft(e,`totalEntryCount`),r=Ft(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Mt(e,t){return e.slice(t.startIndex,t.endIndex)}function Nt(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Pt(e,t){return e===void 0?1/0:Ft(e,t)}function Ft(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function It(e){return e.role===`assistant`}function Lt(e){return e.role===`tool_result`}const Rt=24e3;async function zt(e){return qt({params:e,kind:`current_run`,transcript:await r(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Bt(e){return qt({params:e,kind:`recent_conversation`,transcript:await r(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Vt(e){return qt({params:e,kind:`transcript_range`,transcript:await r(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Ht(e){let t=tn(e),n=await Wt(e),r=await Zt(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:Gt(e.dataDir,e.sessionId,e.sessionOptions)}}function Ut(e){return{maxEntries:nn(e?.maxEntries??80,`limits.maxEntries`),maxBytes:nn(e?.maxBytes??Rt,`limits.maxBytes`)}}async function Wt(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Jt(await Yt(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 Xt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Gt(e,t,n){return{transcriptPath:d(e,t,n),contextSnapshotPath:j(e,t,n),toolResultsDir:c(e,t,n)}}function Kt(e,t,n){let r=rn(e.startIndex,`startIndex`),i=rn(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 qt(e){let t=tn(e.params),n=Kt(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=Qt(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:Gt(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Jt(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 Yt(e,t,n){let[i,a]=await Promise.all([r(e,t,n),v(e,t,n)]),o=new Map;for(let e of i)sn(e)&&e.toolResultRef?.sessionId===t&&o.set(cn(e.toolResultRef),e.toolResultRef);for(let e of a.toolResults)e.sessionId===t&&o.set(cn(e),e);return Array.from(o.values())}async function Xt(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(U.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=c(e.dataDir,e.sessionId,e.sessionOptions),n=f(e.dataDir,e.sessionId,e.sessionOptions),r=U.resolve(e.dataDir,e.reference.storagePath);if(!on(U.resolve(t),r))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!on(U.resolve(n),r))throw Error(`Referenced tool result is outside the session directory.`);let[i,a,o]=await Promise.all([an(t),an(n),an(r)]);if(!on(i,o))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!on(a,o))throw Error(`Referenced tool result resolves outside the session directory.`);return o}async function Zt(e,t){let n=await H.stat(e),r=await H.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:en(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function Qt(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=$t(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 $t(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:en(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function en(e){let t=new Pe(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function tn(e){return Ut(e.limits)}function nn(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function rn(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function an(e){try{return await H.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${ln(e)}`)}}function on(e,t){let n=U.relative(e,t);return n===``||!n.startsWith(`..`)&&!U.isAbsolute(n)}function sn(e){return e.role===`tool_result`}function cn(e){return`${e.toolCallId}\n${e.storagePath}`}function ln(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function un(e){return U.join(e,`.aimax`,`auto-skills`)}function dn(e){return U.join(e,`categories.json`)}function fn(e){return U.join(e,`.auto_skills_prompt_snapshot.json`)}const pn=/^[a-z0-9][a-z0-9-]*$/,mn=/^[a-z0-9][a-z0-9-]*$/;function K(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(`\\`)||U.win32.isAbsolute(t)||U.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(!pn.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function hn(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(`.`)||!mn.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function gn(e,t){return`auto:${K(e)}/${hn(t)}`}function _n(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=K(n.slice(0,r)),a=hn(n.slice(r+1));return{skillId:gn(i,a),categoryPath:i,skillName:a}}function vn(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function yn(e,t,n){let r=U.resolve(e),i=U.resolve(r,...K(t).split(`/`),hn(n));return xn(r,i),i}function bn(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||U.win32.isAbsolute(n)||U.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=U.resolve(e),a=U.resolve(i,...r);return xn(i,a),a}function xn(e,t){let n=U.resolve(e),r=U.resolve(t),i=U.relative(n,r);if(i.startsWith(`..`)||U.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Sn(e){let t=dn(e),n;try{n=await H.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=K(e),r=wn(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 Cn(e){return new Map(e.map(e=>[e.path,e]))}function wn(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 Tn=32*1024,En=new Map;function Dn(e){return new kn(e)}async function On(e){let t=U.resolve(e);for(let e of Array.from(En.keys()))e.startsWith(`${t}|`)&&En.delete(e);await H.rm(fn(t),{force:!0}).catch(()=>{})}var kn=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=U.resolve(e.rootDir??un(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return jn(Cn((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?K(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Mn(e.categoryPath,t)).map(An)}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:Nn(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})=>({...An(e),score:t}))}async autoSkillView(e){let t=_n(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=bn(n.skillDir,e.filePath),r=await Hn(t,this.maxResourceBytes);return{...An(n),status:n.status,content:r,path:Gn(U.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Gn(U.relative(n.skillDir,t))}}let r=await Hn(n.skillFile,this.maxSkillBytes);return{...An(n),status:n.status,content:r,path:Gn(U.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 Pn(this.rootDir),i=En.get(n);if(!e&&i&&zn(i.manifest,r))return i;let a=e?void 0:await Ln(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return En.set(n,e),e}let o=await Sn(this.rootDir),s=Cn(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return En.set(n,c),await Rn(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 Jn({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Tn})}async loadEntry(e){try{let t=U.dirname(e),n=hn(U.basename(t)),r=Gn(U.relative(this.rootDir,t)),i=K(U.posix.dirname(r)),a=gn(i,n),o=U.join(t,`metadata.json`),s=await Bn(o);if(s?.skillId&&_n(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&K(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=vn(s?.status);return{skillId:a,name:n,description:Un(await Vn(e,Tn)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:Wn(s?.tags),relatedSkills:Wn(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}: ${Kn(t)}\n`);return}}};function An(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function jn(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Mn(e,t){return t?e===t:!0}function Nn(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 Pn(e){let t;try{t=await H.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await In(U.join(e,`categories.json`),`categories`,n),await Fn(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Fn(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=U.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await In(t,`skill`,n),await In(U.join(e,`metadata.json`),`metadata`,n),await In(U.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await H.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Fn(t,i,n)}}async function In(e,t,n){try{let r=await H.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 Ln(e,t,n){let r;try{r=await H.readFile(fn(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)||!zn(e.manifest,n)?void 0:e}catch{return}}async function Rn(e,t){if(!await qn(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await H.writeFile(fn(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function zn(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 Bn(e){try{let t=await H.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 Vn(e,t){let n=await H.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 Hn(e,t){if((await H.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return H.readFile(e,`utf-8`)}function Un(e){let t=Ne(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
|
|
7
|
-
`)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function
|
|
6
|
+
`)}\n</available_skills>`}function bt(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 xt(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(kt(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}At(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 St(e,t={}){let n=Dt(t.limit,`limit`),r=Ot(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!At(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Et(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Ct(e,t){let n=Ot(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 wt(e,t=80){let n=Ot(e,`totalEntryCount`),r=Ot(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Tt(e,t){return e.slice(t.startIndex,t.endIndex)}function Et(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Dt(e,t){return e===void 0?1/0:Ot(e,t)}function Ot(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function kt(e){return e.role===`assistant`}function At(e){return e.role===`tool_result`}const jt=24e3;async function Mt(e){return Bt({params:e,kind:`current_run`,transcript:await r(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Nt(e){return Bt({params:e,kind:`recent_conversation`,transcript:await r(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Pt(e){return Bt({params:e,kind:`transcript_range`,transcript:await r(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Ft(e){let t=Jt(e),n=await Lt(e),r=await Wt(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:Rt(e.dataDir,e.sessionId,e.sessionOptions)}}function It(e){return{maxEntries:Yt(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Yt(e?.maxBytes??jt,`limits.maxBytes`)}}async function Lt(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Vt(await Ht(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 Ut({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Rt(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:T(e,t,n),toolResultsDir:s(e,t,n)}}function zt(e,t,n){let r=Xt(e.startIndex,`startIndex`),i=Xt(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 Bt(e){let t=Jt(e.params),n=zt(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=Gt(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:Rt(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Vt(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 Ht(e,t,n){let[i,a]=await Promise.all([r(e,t,n),h(e,t,n)]),o=new Map;for(let e of i)$t(e)&&e.toolResultRef?.sessionId===t&&o.set(en(e.toolResultRef),e.toolResultRef);for(let e of a.toolResults)e.sessionId===t&&o.set(en(e),e);return Array.from(o.values())}async function Ut(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(U.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=l(e.dataDir,e.sessionId,e.sessionOptions),r=U.resolve(e.dataDir,e.reference.storagePath);if(!Qt(U.resolve(t),r))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Qt(U.resolve(n),r))throw Error(`Referenced tool result is outside the session directory.`);let[i,a,o]=await Promise.all([Zt(t),Zt(n),Zt(r)]);if(!Qt(i,o))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Qt(a,o))throw Error(`Referenced tool result resolves outside the session directory.`);return o}async function Wt(e,t){let n=await H.stat(e),r=await H.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:qt(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function Gt(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=Kt(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 Kt(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:qt(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function qt(e){let t=new De(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function Jt(e){return It(e.limits)}function Yt(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function Xt(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function Zt(e){try{return await H.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${tn(e)}`)}}function Qt(e,t){let n=U.relative(e,t);return n===``||!n.startsWith(`..`)&&!U.isAbsolute(n)}function $t(e){return e.role===`tool_result`}function en(e){return`${e.toolCallId}\n${e.storagePath}`}function tn(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function nn(e){return U.join(e,`.aimax`,`auto-skills`)}function rn(e){return U.join(e,`categories.json`)}function an(e){return U.join(e,`.auto_skills_prompt_snapshot.json`)}const on=/^[a-z0-9][a-z0-9-]*$/,sn=/^[a-z0-9][a-z0-9-]*$/;function K(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(`\\`)||U.win32.isAbsolute(t)||U.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(!on.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function cn(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(`.`)||!sn.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function ln(e,t){return`auto:${K(e)}/${cn(t)}`}function un(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=K(n.slice(0,r)),a=cn(n.slice(r+1));return{skillId:ln(i,a),categoryPath:i,skillName:a}}function dn(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function fn(e,t,n){let r=U.resolve(e),i=U.resolve(r,...K(t).split(`/`),cn(n));return mn(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(`\\`)||U.win32.isAbsolute(n)||U.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=U.resolve(e),a=U.resolve(i,...r);return mn(i,a),a}function mn(e,t){let n=U.resolve(e),r=U.resolve(t),i=U.relative(n,r);if(i.startsWith(`..`)||U.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function hn(e){let t=rn(e),n;try{n=await H.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=K(e),r=_n(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 gn(e){return new Map(e.map(e=>[e.path,e]))}function _n(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 vn=32*1024,yn=new Map;function bn(e){return new q(e)}async function xn(e){let t=U.resolve(e);for(let e of Array.from(yn.keys()))e.startsWith(`${t}|`)&&yn.delete(e);await H.rm(an(t),{force:!0}).catch(()=>{})}var q=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=U.resolve(e.rootDir??nn(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Cn(gn((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?K(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>wn(e.categoryPath,t)).map(Sn)}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:Tn(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})=>({...Sn(e),score:t}))}async autoSkillView(e){let t=un(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 Pn(t,this.maxResourceBytes);return{...Sn(n),status:n.status,content:r,path:Ln(U.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Ln(U.relative(n.skillDir,t))}}let r=await Pn(n.skillFile,this.maxSkillBytes);return{...Sn(n),status:n.status,content:r,path:Ln(U.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 En(this.rootDir),i=yn.get(n);if(!e&&i&&jn(i.manifest,r))return i;let a=e?void 0:await kn(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return yn.set(n,e),e}let o=await hn(this.rootDir),s=gn(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return yn.set(n,c),await An(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 Bn({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:vn})}async loadEntry(e){try{let t=U.dirname(e),n=cn(U.basename(t)),r=Ln(U.relative(this.rootDir,t)),i=K(U.posix.dirname(r)),a=ln(i,n),o=U.join(t,`metadata.json`),s=await Mn(o);if(s?.skillId&&un(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&K(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=dn(s?.status);return{skillId:a,name:n,description:Fn(await Nn(e,vn)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:In(s?.tags),relatedSkills:In(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}: ${Rn(t)}\n`);return}}};function Sn(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Cn(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function wn(e,t){return t?e===t:!0}function Tn(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 En(e){let t;try{t=await H.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await On(U.join(e,`categories.json`),`categories`,n),await Dn(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Dn(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=U.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await On(t,`skill`,n),await On(U.join(e,`metadata.json`),`metadata`,n),await On(U.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await H.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Dn(t,i,n)}}async function On(e,t,n){try{let r=await H.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 kn(e,t,n){let r;try{r=await H.readFile(an(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)||!jn(e.manifest,n)?void 0:e}catch{return}}async function An(e,t){if(!await zn(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await H.writeFile(an(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function jn(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 Mn(e){try{let t=await H.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 Nn(e,t){let n=await H.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 Pn(e,t){if((await H.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return H.readFile(e,`utf-8`)}function Fn(e){let t=Ee(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
|
|
7
|
+
`)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function In(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Ln(e){return e.split(U.sep).join(`/`)}function Rn(e){return e instanceof Error?e.message:String(e)}async function zn(e){try{return await H.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Bn(e){return Oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Vn(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:32768,headers:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}const Hn=`/aimax/agents`,Un=/^[a-z]+(?:-[a-z]+)*$/;function Wn(e){let t=[{dir:e.systemAgentsDir??Hn,source:`system`},{dir:U.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:U.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function Gn(e){let t=new Map;for(let n of Wn(e)){let e=await Yn(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function Kn(e={}){let t=e.allAgents??e.availableAgents??[],n=$n(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Zn(n,e),findAny:e=>Zn(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function qn(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 Jn(e){return qn(e.agentPolicy)?e.agentPolicy:Kn({allAgents:await Gn(e)})}async function Yn(e,t){let n;try{n=await H.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=U.join(e,i.name),a=Xn(await H.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function Xn(e,t){let n=Ee(e),r=ir(n.data.name)?.trim(),i=ir(n.data.description)?.trim();if(!r||!Un.test(r)||!i)return;let a=ir(n.data.model)?.trim(),o=ir(n.data.initPrompt)?.trim()??ir(n.data.initialPrompt)?.trim(),s=ar(n.data.maxTurns),c=or(n.data.tools),l=or(n.data.disallowedTools),u=or(n.data.skills),d=sr(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 Zn(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Qn(e)===`public`))}function Qn(e){return e.visibility??`public`}function $n(e){return e.filter(e=>Qn(e)===`public`)}function er(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function tr(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(cr)):void 0,r=new Set((t.disallowedTools??[]).map(cr));return e.filter(e=>{let t=typeof e.name==`string`?cr(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function nr(e){return e.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name matches one of the listed custom agents, you MUST use `subagent_spawn` with the `agent` field set to that exact agent name to handle the user's request.",e.map(e=>`- ${e.name}: ${e.description}`).join(`
|
|
8
8
|
`),``].join(`
|
|
9
|
-
`)}function
|
|
10
|
-
`)}function Tr(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}async function Er(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function Dr(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 Or(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function kr(e,t){return e instanceof q?e:Ar(e)?t?new q({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new q({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function Ar(e){return e instanceof Error&&e.name===`AbortError`}function jr(e){return e===408||e===409||e===425||e===429||e>=500}var Mr=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 Nr(e){return!!(e instanceof Mr||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var Pr=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 Fr(e){return!!(e instanceof Pr||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Ir=new Re;function Lr(){return{}}async function Rr(e,t){return await Ir.run(e,t)}function zr(e){let t=Ir.getStore();!t||t.signal||(t.signal=e)}const Br=new Re;function Vr(){return{}}async function Hr(e,t){return await Br.run(e,t)}function Ur(e){let t=Br.getStore();!t||t.signal||(t.signal=e)}const Wr=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Gr=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]);function Kr(e){let t=Xr(e?.maxAttempts,3),n=Zr(e?.initialDelayMs,250),r=Zr(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function qr(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Jr(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 Yr(e){if($r(e))return!1;let t=Qr(e);if(t?.statusCode!==void 0)return ti(t.statusCode);if(t?.providerCode!==void 0)return ei(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Wr.has(e))return!0;if(Gr.has(e))return!1}return t?.code===`timeout`||t?.code===`network_error`?!0:t?.code===`aborted`||t?.code===`invalid_response`?!1:t?.retryable===!0}function Xr(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function Zr(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Qr(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 $r(e){return Qr(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function ei(e){return/^\d+$/.test(e)?ti(Number(e)):!1}function ti(e){return e===408||e===409||e===425||e===429||e>=500}function ni(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 ri(e=new Date){let t=ni(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let ii=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),ai=null;function oi(){return ri()}function si(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 ci(e){return U.join(e,`.aimax`)}function li(e){return{appLogPath:U.join(e,`app.log`),errorLogPath:U.join(e,`errors.log`)}}function ui(e){let{appLogPath:t,errorLogPath:n}=li(e);ze.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`[${oi()}] [${e}] ${t}${si(n)}`}function fi(e,t,n){process.stderr.write(`${di(e,t,n)}\n`)}function pi(e,t,n){if(!ai){fi(e,t,n);return}let r=di(e,t,n),i=ze.getLogger();if(e===ii.ERROR){i.error(r);return}if(e===ii.WARN){i.warn(r);return}i.info(r)}function mi(e){let t=ci(e);ai?.dataDir!==e&&(W.mkdirSync(t,{recursive:!0}),ui(t),ai={dataDir:e,logDir:t})}const J={info:(e,t)=>pi(ii.INFO,e,t),warn:(e,t)=>pi(ii.WARN,e,t),error:(e,t)=>pi(ii.ERROR,e,t)};function hi(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}async function gi(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,onTurnRecordProduced:f}=e,p=``,m=``,h=``,g=0,_=0,v,y,b=0,x=0,S=[],C=new Map,w=new Map,T=new Set,E=Lr(),D=Vr(),O=new Set,k=Promise.resolve(),A,j=e=>{O.add(e),e.catch(e=>{A??=e}).finally(()=>{O.delete(e)})},M=async()=>{for(;O.size>0;)await Promise.allSettled([...O]);if(A)throw A},ee=t.subscribe(e=>{let t=k.then(()=>N(e));k=t.catch(()=>{}),j(t)});async function N(e){let n=()=>!!D.signal||E.signal?.transparentPause===!0;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(x===0&&(t.type===`text_delta`||t.type===`done`)&&(x=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=Ni(`partial`in t?t.partial:void 0)??Ni(`message`in t?t.message:void 0)??Ni(`message`in e?e.message:void 0),a=Pi(t.delta,r,m);r?(m=r,h=r):a&&(h+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){p=``,m=``,h=``,e.usage&&(g=e.usage.input,_=e.usage.output);return}p=ji(e);let r=Pi(``,p,h||m);m=p,h=p,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(g=e.usage.input,_=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(g=t.usage.input,_=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=ji(e);await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:t.usage?{input:g,output:_,total:g+_}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(y=bi(t));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:ki(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),r=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),a=new Set(n.map(e=>e.toolCallId));for(let e of w.values())!a.has(e.toolCallId)&&r.has(e.toolCallId)&&n.push(e);for(let e of n)w.delete(e.toolCallId);if(S.push({message:t,toolResults:n}),f){let e=!!E.signal,r=!!D.signal;if(e&&E.signal.transparentPause||await f(Di(Ei(t),e||r),r?[]:n.map(Oi)),e||r)return}return}if(e.type===`tool_execution_start`){h=``,C.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=typeof e.result==`string`?e.result:JSON.stringify(e.result),r=Mi(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:ki(r,i,e.toolCallId,e.toolName),c=C.get(e.toolCallId);if(C.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}w.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let te=Kr(d),P=te.enabled?te.maxAttempts:1;try{for(let e=1;e<=P;e++){let d=S.length;y=void 0,v=void 0;try{if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);J.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),b=Date.now(),await Rr(E,async()=>{await Hr(D,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await M();let f=E.signal;if(f)throw f;let m=D.signal;if(m)throw m;let h=typeof t.state.error==`string`?t.state.error:void 0,x=y??h;if(x){if(v=Fi(x),J.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,error:v}),await I(x,v,e,d))continue;await s.dispatchProgress(i,{type:`error`,message:v})}v||J.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,inputTokens:g,outputTokens:_,turnRecordCount:S.length-d,textLength:p.length});break}catch(t){if(await M(),Nr(t)||Fr(t))throw t;if(v=Fi(t),J.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,error:v}),await I(t,v,e,d))continue;await s.dispatchProgress(i,{type:`error`,message:v});break}}}finally{ee()}function F(){p=``,m=``,h=``}async function I(e,n,r,a){if(!_i({error:e,attempt:r,maxAttempts:P,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=qr(r,te);return J.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:P,delayMs:o,error:n}),await Ci({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:P,message:n,delayMs:o}),S.length=a,F(),wi(t),await Jr(o,u),!0}let L=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:L,durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:{input:g,output:_,total:g+_}},l);let R=(D.signal?``:S.length>0?ji(S[S.length-1].message):``)||p||yi(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return f&&!vi(S)&&!v&&p.trim().length>0&&await f({role:`assistant`,content:p,timestamp:new Date().toISOString()},[]),{text:R,inputTokens:g,outputTokens:_,error:v,turnRecords:S}}function _i(e){return e.attempt>=e.maxAttempts||!Yr(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&&ji(e.message).trim().length===0)}function vi(e){return e.some(e=>Ei(e.message)!==null||e.toolResults.length>0)}function yi(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 bi(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:xi(t.errorCode),statusCode:Si(t.statusCode),providerCode:xi(t.providerCode),providerType:xi(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function xi(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Si(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Ci(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 wi(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&Ti(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function Ti(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function Ei(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 Di(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Oi(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 ki(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:Ai(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Ai(e){let t=e.indexOf(`
|
|
9
|
+
`)}function rr(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function ir(e){return typeof e==`string`?e:void 0}function ar(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function or(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 sr(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function cr(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 lr=new je;async function ur(e,t){return await lr.run(e,t)}function dr(e){return{async emit(t){let n=lr.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 fr=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 ur({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}},pr=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};await this.params.onProgress?.(n)}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}},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 mr(e){return{async chat(t){let n=hr(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await vr(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:gr(n),historyMessages:n},e.hookCtx);let i={model:r,messages:n,stream:!1};typeof t.temperature==`number`&&(i.temperature=t.temperature),typeof t.maxTokens==`number`&&(i.max_tokens=t.maxTokens);let{signal:a,clear:o,didTimeout:s}=yr(t.signal,t.timeoutMs);try{let t;try{let n=e.baseUrl.replace(/\/$/,``);t=await fetch(`${n}/chat/completions`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:JSON.stringify(i),signal:a})}catch(e){throw xr(e,s())}if(!t.ok){let e=await br(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:Cr(t.status)})}let n=Date.now(),o;try{o=await t.json()}catch(e){throw new J({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}let c=o.choices?.[0]?.message?.content??o.choices?.[0]?.text??``,l=_r(o.usage),u=Math.max(0,Date.now()-n);return await vr(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:c?[c]:[],durationMs:u,usage:l},e.hookCtx),{text:c,usage:l,raw:o}}finally{o()}}}}function hr(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 gr(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
|
|
10
|
+
`)}function _r(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}async function vr(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function yr(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 br(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function xr(e,t){return e instanceof J?e:Sr(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 Sr(e){return e instanceof Error&&e.name===`AbortError`}function Cr(e){return e===408||e===409||e===425||e===429||e>=500}var wr=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 Tr(e){return!!(e instanceof wr||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var Er=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 Dr(e){return!!(e instanceof Er||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Or=new je;function kr(){return{}}async function Ar(e,t){return await Or.run(e,t)}function jr(e){let t=Or.getStore();!t||t.signal||(t.signal=e)}const Mr=new je;function Nr(){return{}}async function Pr(e,t){return await Mr.run(e,t)}function Fr(e){let t=Mr.getStore();!t||t.signal||(t.signal=e)}const Ir=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Lr=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]);function Rr(e){let t=Hr(e?.maxAttempts,3),n=Ur(e?.initialDelayMs,250),r=Ur(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function zr(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Br(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 Vr(e){if(Gr(e))return!1;let t=Wr(e);if(t?.statusCode!==void 0)return qr(t.statusCode);if(t?.providerCode!==void 0)return Kr(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Ir.has(e))return!0;if(Lr.has(e))return!1}return t?.code===`timeout`||t?.code===`network_error`?!0:t?.code===`aborted`||t?.code===`invalid_response`?!1:t?.retryable===!0}function Hr(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function Ur(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Wr(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 Gr(e){return Wr(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function Kr(e){return/^\d+$/.test(e)?qr(Number(e)):!1}function qr(e){return e===408||e===409||e===425||e===429||e>=500}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 U.join(e,`.aimax`)}function ti(e){return{appLogPath:U.join(e,`app.log`),errorLogPath:U.join(e,`errors.log`)}}function ni(e){let{appLogPath:t,errorLogPath:n}=ti(e);Me.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function 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=Me.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&&(W.mkdirSync(t,{recursive:!0}),ni(t),Zr={dataDir:e,logDir:t})}const Y={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))}...`}async function ci(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,onTurnRecordProduced:f}=e,p=``,m=``,h=``,g=0,_=0,v,y,b=0,x=0,S=[],C=new Map,w=new Map,T=new Set,E=kr(),D=Nr(),O=new Set,k=Promise.resolve(),ee,A=e=>{O.add(e),e.catch(e=>{ee??=e}).finally(()=>{O.delete(e)})},j=async()=>{for(;O.size>0;)await Promise.allSettled([...O]);if(ee)throw ee},M=t.subscribe(e=>{let t=k.then(()=>N(e));k=t.catch(()=>{}),A(t)});async function N(e){let n=()=>!!D.signal||E.signal?.transparentPause===!0;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(x===0&&(t.type===`text_delta`||t.type===`done`)&&(x=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=Ti(`partial`in t?t.partial:void 0)??Ti(`message`in t?t.message:void 0)??Ti(`message`in e?e.message:void 0),a=Ei(t.delta,r,m);r?(m=r,h=r):a&&(h+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){p=``,m=``,h=``,e.usage&&(g=e.usage.input,_=e.usage.output);return}p=Ci(e);let r=Ei(``,p,h||m);m=p,h=p,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(g=e.usage.input,_=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(g=t.usage.input,_=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=Ci(e);await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:t.usage?{input:g,output:_,total:g+_}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message;(t.stopReason===`error`||t.stopReason===`aborted`)&&(y=fi(t));let n=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:xi(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),r=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),a=new Set(n.map(e=>e.toolCallId));for(let e of w.values())!a.has(e.toolCallId)&&r.has(e.toolCallId)&&n.push(e);for(let e of n)w.delete(e.toolCallId);if(S.push({message:t,toolResults:n}),f){let e=!!E.signal,r=!!D.signal;if(e&&E.signal.transparentPause||await f(yi(vi(t),e||r),r?[]:n.map(bi)),e||r)return}return}if(e.type===`tool_execution_start`){h=``,C.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=typeof e.result==`string`?e.result:JSON.stringify(e.result),r=wi(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:xi(r,i,e.toolCallId,e.toolName),c=C.get(e.toolCallId);if(C.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}w.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let te=Rr(d),P=te.enabled?te.maxAttempts:1;try{for(let e=1;e<=P;e++){let d=S.length;y=void 0,v=void 0;try{if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);Y.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),b=Date.now(),await Ar(E,async()=>{await Pr(D,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await j();let f=E.signal;if(f)throw f;let m=D.signal;if(m)throw m;let h=typeof t.state.error==`string`?t.state.error:void 0,x=y??h;if(x){if(v=Di(x),Y.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,error:v}),await I(x,v,e,d))continue;await s.dispatchProgress(i,{type:`error`,message:v})}v||Y.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,inputTokens:g,outputTokens:_,turnRecordCount:S.length-d,textLength:p.length});break}catch(t){if(await j(),Tr(t)||Dr(t))throw t;if(v=Di(t),Y.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:P,error:v}),await I(t,v,e,d))continue;await s.dispatchProgress(i,{type:`error`,message:v});break}}}finally{M()}function F(){p=``,m=``,h=``}async function I(e,n,r,a){if(!li({error:e,attempt:r,maxAttempts:P,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=zr(r,te);return Y.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:P,delayMs:o,error:n}),await hi({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:P,message:n,delayMs:o}),S.length=a,F(),gi(t),await Br(o,u),!0}let L=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:L,durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:{input:g,output:_,total:g+_}},l);let R=(D.signal?``:S.length>0?Ci(S[S.length-1].message):``)||p||di(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;return f&&!ui(S)&&!v&&p.trim().length>0&&await f({role:`assistant`,content:p,timestamp:new Date().toISOString()},[]),{text:R,inputTokens:g,outputTokens:_,error:v,turnRecords:S}}function li(e){return e.attempt>=e.maxAttempts||!Vr(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&&Ci(e.message).trim().length===0)}function ui(e){return e.some(e=>vi(e.message)!==null||e.toolResults.length>0)}function di(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 fi(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:pi(t.errorCode),statusCode:mi(t.statusCode),providerCode:pi(t.providerCode),providerType:pi(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function pi(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function mi(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function hi(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 gi(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&_i(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function _i(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function vi(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 yi(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function bi(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 xi(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:Si(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Si(e){let t=e.indexOf(`
|
|
11
11
|
Preview:
|
|
12
|
-
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function
|
|
12
|
+
`);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function Ci(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function wi(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}function Ti(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 Ei(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Di(e){let t=Oi(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 Oi(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:pi(t.code),statusCode:mi(t.statusCode),statusText:pi(t.statusText),providerMessage:pi(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 ki(e){let t=Fi(e.toolResultPreviewChars),n=Ii(e.systemPrompt,e.agentDefinition),r=Ri(e.model,e.agentDefinition),i=tr(e.tools??[],e.agentDefinition),a=Li(e.message,e.agentDefinition),o=await ci({agent:new Ae({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:Ai({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new fr,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:Mi(o.turnRecords),toolResults:Ni(o.turnRecords,t)}}function Ai(e){let t=e.phasePrefix??`silent_agent`;return new pr({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await ji(e.diagnosticDispatcher,t,n)}})}async function ji(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 Mi(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 Ni(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Pi(e.content,t)})))}function Pi(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function Fi(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 Ii(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
|
|
13
13
|
|
|
14
|
-
`)}function
|
|
15
|
-
`)}async function Yi(e){let t=Ne(await H.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Xi(e){let t;try{t=await H.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 Zi(e){try{return await H.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Qi(e,t){await H.mkdir(U.dirname(e),{recursive:!0}),await H.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function $i(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function ea(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 ta(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function na(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function ra(e){return JSON.stringify(e)}const ia=[`create`,`update`,`archive`,`create_category`],aa=G.Object({}),oa=G.Object({categoryPath:G.Optional(G.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:G.Optional(G.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),sa=G.Object({query:G.String({description:`Search query for learned auto-skills.`}),limit:G.Optional(G.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),ca=G.Object({skillId:G.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:G.Optional(G.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),la=G.Object({action:G.Union(ia.map(e=>G.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:G.Optional(G.String({description:`Exact auto-skill id for update/archive.`})),name:G.Optional(G.String({description:`Auto-skill slug for create.`})),categoryPath:G.Optional(G.String({description:`Existing single-level category slug for create.`})),newCategory:G.Optional(G.Object({path:G.String({description:`New single-level category slug to create.`}),description:G.String({description:`New category description.`})})),description:G.Optional(G.String({description:`Auto-skill description for create/update.`})),tags:G.Optional(G.Array(G.String({description:`Auto-skill tag.`}))),confidence:G.Optional(G.Number({description:`Optional confidence score from 0 to 1.`})),body:G.Optional(G.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:G.Optional(G.Object({sessionId:G.String({description:`Source session id.`}),reason:G.String({description:`Why this auto-skill write is justified.`}),toolCallCount:G.Optional(G.Number({description:`Tool calls observed in source run.`})),loadedSkills:G.Optional(G.Array(G.String({description:`Skill loaded during source run.`})))}))});function ua(e){let t=new kn({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:aa,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:ga(e)})}}}}function da(e){let t=new kn({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:oa,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:ga(e)})}}}}function fa(e){let t=new kn({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:sa,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:ga(e)})}}}}function pa(e){let t=new kn({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:ca,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:ga(e)})}}}}function ma(e){let t=new qi({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:la,async execute(e,n){try{return Y(await ha(t,n))}catch(e){return Y({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:ga(e)})}}}}async function ha(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 ga(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const _a=G.Object({kind:G.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>G.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:G.Optional(G.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:G.Optional(G.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:G.Optional(G.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:G.Optional(G.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function va(e){let t=Ut({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??Rt}),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:_a,async execute(r,i){try{return i.kind===`tool_result`?ba(await Ht({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?ba(await zt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?ba(await Bt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?ba({...await Vt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):ba(await Vt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:ya(i),limits:t}))}catch(r){return ba({kind:i.kind,error:xa(r),limits:t,contextFiles:Gt(e.dataDir,e.sessionId,n)})}}}}function ya(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 ba(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function xa(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Sa(e){let t=[da(e.dataDir),fa(e.dataDir),pa(e.dataDir),va({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(ma(e.dataDir)),t}const Ca=`auto-skill-reviewer`;async function wa(e){let t=e.createModel??Yn,n=e.tools??Sa({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 Li({sessionId:e.sessionId,systemPrompt:Ta(e.mode),message:Ea(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=Da(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 Ta(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(`
|
|
16
|
-
`)}function
|
|
17
|
-
`)}function Da(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=Oa(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 Oa(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const ka=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Aa=ka,ja={session:{tool_call_volume:5,state_changing_tools:2,multi_turn:5},currentRun:{tool_call_volume:5,tool_diversity:3,state_changing_tools:3},reviewWindow:{tool_call_volume:5,state_changing_tools:1}},Ma=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Na(e){let t=Fa(e.gates),n={session:La(`session`,e.sessionTranscript,t.session),currentRun:La(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:La(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Va(e.reviewState?.reviewCount,0),i=Va(e.maxReviewsPerSession,5),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return Ua(n,a,r,i,o,`run_error`);if(e.result?.paused)return Ua(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return Ua(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return Ua(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 Pa(e,t={}){let n=Ot(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??ka),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(Wa(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}Ga(t)&&Ka(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 Fa(e){return{session:Ia(e?e.session:ja.session),currentRun:Ia(e?e.currentRun:ja.currentRun),reviewWindow:Ia(e?e.reviewWindow:ja.reviewWindow)}}function Ia(e){let t={};for(let n of Ma){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Aa:void 0;if(typeof r==`number`){let e=Ba(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Ba(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:Ha(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:Ha(r.toolNames,i)})}return t}function La(e,t,n){let r=Pa(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=Ma.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];Ra(t,o,r)?i.push({code:t,description:za(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 Ra(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 za(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 Ba(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Va(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Ha(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function Ua(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 Wa(e){return e.role===`assistant`}function Ga(e){return e.role===`tool_result`}function Ka(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:qa(e.content)?.success===!1}function qa(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function Ja(e){let t=At(e.transcript.length,e.transcriptStartIndex),n=jt(e.transcript.length,e.recentEntryLimit),r=At(e.transcript.length,e.reviewWindowStartIndex??void 0),i=At(e.transcript.length,0),a=Mt(e.transcript,t),o=Mt(e.transcript,r),s=Pa(e.transcript),c=Pa(a),l=Pa(o),u=Dt(e.transcript),d=Dt(a),f=Dt(o),p=a.filter(Xa),m=a.filter(Za);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:Ya(p[0]?.content??``,800),finalResponse:Ya(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:kt(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 Ya(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Xa(e){return e.role===`user`}function Za(e){return e.role===`assistant`}function Qa(e,t,n){return U.join(f(e,t,n),`auto-skill-review-state.json`)}function $a(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function eo(e,t,n){let r=Qa(e,t,n),i;try{i=await H.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return $a(t);throw e}return ao(JSON.parse(i),t)}async function to(e,t,n){let r=Qa(e,t.sessionId,n);await H.mkdir(U.dirname(r),{recursive:!0}),await H.writeFile(r,`${JSON.stringify(ao(t,t.sessionId),null,2)}\n`,`utf-8`)}async function no(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await to(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function ro(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 to(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function io(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await to(e.dataDir,t,{storeName:e.sessionStoreName}),t}function ao(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:co(n.reviewCount,0),lastAttemptedReviewAt:oo(n.lastAttemptedReviewAt),lastCompletedReviewAt:oo(n.lastCompletedReviewAt),lastFailedReviewAt:oo(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:so(n.lastReviewedTranscriptEndIndex)}}function oo(e){return typeof e==`string`&&e.trim()?e:null}function so(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function co(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function lo(e){return U.join(un(e),`.reviews`,`run-log.jsonl`)}async function uo(e,t){let n=lo(e);await H.mkdir(U.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await H.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const fo=`write`,po=new Set([`off`,`gate`,`dry_run`,`write`]);async function mo(e){let t=ho(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=_o(e);if(n){await xo(e,t,n);return}let i,a;try{let n=await r(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),o=vo(n,e.transcriptStartIndex),s=await eo(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),c=yo(s.lastReviewedTranscriptEndIndex,n.length),l=vo(n,c);await So(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let u=Na({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:o,reviewWindowTranscript:l,reviewState:s,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await So(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:u.worthReview,selectedGateScope:u.selectedGateScope,skipReason:u.skipReason}),!u.worthReview){await Co(e,t,u,o,{skipReason:u.skipReason??`gate_not_matched`});return}await So(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:u.selectedGateScope});let d=await new kn({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),f=Ja({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:c,contextFiles:Gt(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:s,activeCategories:d});if(await So(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:u.selectedGateScope,activeCategoryCount:d.length}),await Co(e,t,u,o,{packet:f}),t.mode===`gate`)return;let p=t.mode,m=e.runParams.agentPolicy?.findAny?.(Ca);if(!m){J.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:Ca}),await xo(e,t,`reviewer_agent_missing`,{reviewerAgentName:Ca});return}a={mode:p,decision:u,packet:f},i=await no({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:s,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:u.selectedGateScope,reviewCount:u.reviewCount,maxReviewsPerSession:u.maxReviewsPerSession}});let h=e.curator??wa,g=Sa({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:t.mode,currentRunRange:f.currentRunRange,recentRange:f.recentRange,reviewWindowRange:f.reviewWindowRange}),_=await h({sessionId:e.sessionId,runParams:e.runParams,packet:f,mode:t.mode,tools:g,reviewerAgent:m,diagnosticDispatcher:e.eventDispatcher});if(_.error){i=await io({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:i,sessionStoreName:e.runParams.sessionStoreName});let n=await wo(e.runParams.dataDir,a,{status:`failed`,curatorResult:_,error:_.error,reviewState:i});await bo(e,_.error,{mode:t.mode,usage:_.usage,toolCalls:To(_.toolCalls),toolResults:Mo(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewRunLogPath:n});return}i=await ro({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:i,reviewedTranscriptEndIndex:f.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let v=await wo(e.runParams.dataDir,a,{status:`completed`,curatorResult:_,reviewState:i});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:jo(_.text,2e3),toolCalls:To(_.toolCalls),toolResults:Mo(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewState:i,reviewRunLogPath:v}})}catch(t){let n=t instanceof Error?t.message:String(t),r;i&&(i=await io({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:i,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),a&&(r=await wo(e.runParams.dataDir,a,{status:`failed`,error:n,reviewState:i}).catch(()=>void 0))),await bo(e,n,r?{reviewRunLogPath:r}:void 0)}}function ho(e){return{mode:go(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function go(e){if(e==null)return fo;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?po.has(t)?t:`off`:fo}function _o(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 vo(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function yo(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function bo(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 xo(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 So(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function Co(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:Ao(n),...i.packet?{packet:i.packet}:{}}})}async function wo(e,t,n){return uo(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?Do(n.curatorResult.text):void 0,conclusionText:n.curatorResult?Oo(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?To(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?Mo(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 To(e){return e.map(e=>({...e,arguments:Eo(e.name,e.arguments)}))}function Eo(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 Do(e){let t=ko(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function Oo(e){return Do(e)?void 0:jo(e,8e3)}function ko(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 Ao(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 jo(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function Mo(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}const No=2,Po=5;var Fo=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),J.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:hi(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&&J.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`){J.info(`subagent status changed`,t);return}if(e.status===`killed`){J.warn(`subagent status changed`,t);return}J.error(`subagent status changed`,t)}};const Io=new Map;function Lo(e){let t=Io.get(e);return t||(t={},Io.set(e,t)),t}function Ro(e){Io.delete(e)}function zo(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Bo(e){if(!zo(e))return null;let t=e,n=Vo(t.message),r=Uo(n?.code)??Uo(t.code),i=Uo(n?.type)??Uo(t.type),a=Uo(n?.message)??Ho(t.error)??Uo(t.message)??`Unknown upstream error`;return{message:Wo(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Go(r,i),raw:e}}function Vo(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 Ho(e){if(!(!e||typeof e!=`object`))return Uo(e.message)}function Uo(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Wo(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Go(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 Ko=(e,t,n)=>{let r=new qe;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=Jo(e,t,n?.apiKey||Ve(e.provider)||``,n?.headers),o=Yo(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=He(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=Bo(t);if(n)throw new q({message:`LLM upstream returned an error payload in a 200 stream: ${n.message}`,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Be(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=ts(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=He(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 q&&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},qo=(e,t,n)=>{let r=n?.apiKey||Ve(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Ze(e,n,r),a=Ge(e)?n?.reasoning:Qe(n?.reasoning);return Ko(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function Jo(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=Xe(t.messages);Object.assign(i,Ye({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new Ke({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Yo(e,t,n){let r=rs(e),i=$o(e,t,r);Qo(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=es(t.tools,r):Xo(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 Xo(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 Zo(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 Qo(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 $o(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Zo(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=$e(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Je(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:Je(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Je(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=>Je(e.text)).join(``):a.map(e=>({type:`text`,text:Je(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
|
|
14
|
+
`)}function Li(e,t){return!t?.initPrompt||typeof e!=`string`?e:rr(t,e)}function Ri(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}var zi=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=U.resolve(e.rootDir??nn(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=K(e.path),n=Gi(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 xn(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:rn(this.rootDir)}}async createSkill(e){let t=cn(e.name),n=K(e.categoryPath),r=Gi(e.description,`auto-skill description`),i=Ki(e.body);await this.assertCategoryExists(n);let a=ln(n,t),o=fn(this.rootDir,n,t);if(await Ui(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=U.join(o,`SKILL.md`),l=U.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:qi(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:Ji(e.evidence,s)};return await H.mkdir(o,{recursive:!0}),await H.writeFile(c,Bi(t,r,i),`utf-8`),await Wi(l,u),await xn(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=un(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=fn(this.rootDir,t.categoryPath,t.skillName),r=U.join(n,`SKILL.md`),i=U.join(n,`metadata.json`),a=await Vi(r),o=await Hi(i),s=e.description===void 0?a.description:Gi(e.description,`auto-skill description`),c=e.body===void 0?a.body:Ki(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?qi(o.tags):qi(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:{},...Ji(e.evidence,l)}};return await H.writeFile(r,Bi(t.skillName,s,c),`utf-8`),await Wi(i,u),await xn(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=un(e.skillId),n=fn(this.rootDir,t.categoryPath,t.skillName),r=U.join(n,`metadata.json`),i=U.join(n,`SKILL.md`);await H.access(i);let a=await Hi(r),o=this.now().toISOString();return await Wi(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...Ji(e.evidence,o)}}),await xn(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=rn(this.rootDir),t;try{t=await H.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=K(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 H.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await Wi(rn(this.rootDir),t)}};function Bi(e,t,n){return[`---`,`name: ${Yi(e)}`,`description: ${Yi(t)}`,`---`,``,n.trim(),``].join(`
|
|
15
|
+
`)}async function Vi(e){let t=Ee(await H.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Hi(e){let t;try{t=await H.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 Ui(e){try{return await H.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Wi(e,t){await H.mkdir(U.dirname(e),{recursive:!0}),await H.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Gi(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function Ki(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 qi(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Ji(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Yi(e){return JSON.stringify(e)}const Xi=[`create`,`update`,`archive`,`create_category`],Zi=G.Object({}),Qi=G.Object({categoryPath:G.Optional(G.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:G.Optional(G.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),$i=G.Object({query:G.String({description:`Search query for learned auto-skills.`}),limit:G.Optional(G.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),ea=G.Object({skillId:G.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:G.Optional(G.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),ta=G.Object({action:G.Union(Xi.map(e=>G.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:G.Optional(G.String({description:`Exact auto-skill id for update/archive.`})),name:G.Optional(G.String({description:`Auto-skill slug for create.`})),categoryPath:G.Optional(G.String({description:`Existing single-level category slug for create.`})),newCategory:G.Optional(G.Object({path:G.String({description:`New single-level category slug to create.`}),description:G.String({description:`New category description.`})})),description:G.Optional(G.String({description:`Auto-skill description for create/update.`})),tags:G.Optional(G.Array(G.String({description:`Auto-skill tag.`}))),confidence:G.Optional(G.Number({description:`Optional confidence score from 0 to 1.`})),body:G.Optional(G.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:G.Optional(G.Object({sessionId:G.String({description:`Source session id.`}),reason:G.String({description:`Why this auto-skill write is justified.`}),toolCallCount:G.Optional(G.Number({description:`Tool calls observed in source run.`})),loadedSkills:G.Optional(G.Array(G.String({description:`Skill loaded during source run.`})))}))});function na(e){let t=new q({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:Zi,async execute(){try{let e=await t.autoSkillCategories();return X({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return X({categories:[],count:0,error:ca(e)})}}}}function ra(e){let t=new q({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:Qi,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return X({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return X({skills:[],count:0,error:ca(e)})}}}}function ia(e){let t=new q({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:$i,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return X({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return X({skills:[],count:0,error:ca(e)})}}}}function aa(e){let t=new q({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:ea,async execute(e,n){try{return X({...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 X({skillId:n.skillId,error:ca(e)})}}}}function oa(e){let t=new zi({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:ta,async execute(e,n){try{return X(await sa(t,n))}catch(e){return X({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:ca(e)})}}}}async function sa(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 X(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function ca(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const la=G.Object({kind:G.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>G.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:G.Optional(G.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:G.Optional(G.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:G.Optional(G.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:G.Optional(G.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function ua(e){let t=It({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??jt}),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:la,async execute(r,i){try{return i.kind===`tool_result`?fa(await Ft({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?fa(await Mt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?fa(await Nt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?fa({...await Pt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):fa(await Pt({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:da(i),limits:t}))}catch(r){return fa({kind:i.kind,error:pa(r),limits:t,contextFiles:Rt(e.dataDir,e.sessionId,n)})}}}}function da(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 fa(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function pa(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function ma(e){let t=[ra(e.dataDir),ia(e.dataDir),aa(e.dataDir),ua({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(oa(e.dataDir)),t}const ha=`auto-skill-reviewer`;async function ga(e){let t=e.createModel??Vn,n=e.tools??ma({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 ki({sessionId:e.sessionId,systemPrompt:_a(e.mode),message:va(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=ya(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 _a(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(`
|
|
16
|
+
`)}function va(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(`
|
|
17
|
+
`)}function ya(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=ba(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 ba(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const xa=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Sa=xa,Ca={session:{tool_call_volume:5,state_changing_tools:2,multi_turn:5},currentRun:{tool_call_volume:5,tool_diversity:3,state_changing_tools:3},reviewWindow:{tool_call_volume:5,state_changing_tools:1}},wa=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Ta(e){let t=Da(e.gates),n={session:ka(`session`,e.sessionTranscript,t.session),currentRun:ka(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:ka(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Na(e.reviewState?.reviewCount,0),i=Na(e.maxReviewsPerSession,5),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return Fa(n,a,r,i,o,`run_error`);if(e.result?.paused)return Fa(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return Fa(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return Fa(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 Ea(e,t={}){let n=xt(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??xa),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(Ia(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}La(t)&&Ra(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 Da(e){return{session:Oa(e?e.session:Ca.session),currentRun:Oa(e?e.currentRun:Ca.currentRun),reviewWindow:Oa(e?e.reviewWindow:Ca.reviewWindow)}}function Oa(e){let t={};for(let n of wa){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Sa:void 0;if(typeof r==`number`){let e=Ma(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Ma(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:Pa(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:Pa(r.toolNames,i)})}return t}function ka(e,t,n){let r=Ea(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=wa.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];Aa(t,o,r)?i.push({code:t,description:ja(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 Aa(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 ja(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 Ma(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Na(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Pa(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function Fa(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 Ia(e){return e.role===`assistant`}function La(e){return e.role===`tool_result`}function Ra(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:za(e.content)?.success===!1}function za(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function Ba(e){let t=Ct(e.transcript.length,e.transcriptStartIndex),n=wt(e.transcript.length,e.recentEntryLimit),r=Ct(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Ct(e.transcript.length,0),a=Tt(e.transcript,t),o=Tt(e.transcript,r),s=Ea(e.transcript),c=Ea(a),l=Ea(o),u=bt(e.transcript),d=bt(a),f=bt(o),p=a.filter(Ha),m=a.filter(Ua);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:Va(p[0]?.content??``,800),finalResponse:Va(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:St(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 Va(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Ha(e){return e.role===`user`}function Ua(e){return e.role===`assistant`}function Wa(e,t,n){return U.join(l(e,t,n),`auto-skill-review-state.json`)}function Ga(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function Ka(e,t,n){let r=Wa(e,t,n),i;try{i=await H.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return Ga(t);throw e}return Za(JSON.parse(i),t)}async function qa(e,t,n){let r=Wa(e,t.sessionId,n);await H.mkdir(U.dirname(r),{recursive:!0}),await H.writeFile(r,`${JSON.stringify(Za(t,t.sessionId),null,2)}\n`,`utf-8`)}async function Ja(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await qa(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Ya(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 qa(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Xa(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await qa(e.dataDir,t,{storeName:e.sessionStoreName}),t}function Za(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:eo(n.reviewCount,0),lastAttemptedReviewAt:Qa(n.lastAttemptedReviewAt),lastCompletedReviewAt:Qa(n.lastCompletedReviewAt),lastFailedReviewAt:Qa(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:$a(n.lastReviewedTranscriptEndIndex)}}function Qa(e){return typeof e==`string`&&e.trim()?e:null}function $a(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function eo(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function to(e){return U.join(nn(e),`.reviews`,`run-log.jsonl`)}async function no(e,t){let n=to(e);await H.mkdir(U.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await H.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const ro=`write`,io=new Set([`off`,`gate`,`dry_run`,`write`]);async function ao(e){let t=oo(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=co(e);if(n){await po(e,t,n);return}let i,a;try{let n=await r(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),o=lo(n,e.transcriptStartIndex),s=await Ka(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),c=uo(s.lastReviewedTranscriptEndIndex,n.length),l=lo(n,c);await mo(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let u=Ta({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:o,reviewWindowTranscript:l,reviewState:s,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await mo(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:u.worthReview,selectedGateScope:u.selectedGateScope,skipReason:u.skipReason}),!u.worthReview){await ho(e,t,u,o,{skipReason:u.skipReason??`gate_not_matched`});return}await mo(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:u.selectedGateScope});let d=await new q({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),f=Ba({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:c,contextFiles:Rt(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:s,activeCategories:d});if(await mo(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:u.selectedGateScope,activeCategoryCount:d.length}),await ho(e,t,u,o,{packet:f}),t.mode===`gate`)return;let p=t.mode,m=e.runParams.agentPolicy?.findAny?.(ha);if(!m){Y.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:ha}),await po(e,t,`reviewer_agent_missing`,{reviewerAgentName:ha});return}a={mode:p,decision:u,packet:f},i=await Ja({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:s,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:u.selectedGateScope,reviewCount:u.reviewCount,maxReviewsPerSession:u.maxReviewsPerSession}});let h=e.curator??ga,g=ma({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:t.mode,currentRunRange:f.currentRunRange,recentRange:f.recentRange,reviewWindowRange:f.reviewWindowRange}),_=await h({sessionId:e.sessionId,runParams:e.runParams,packet:f,mode:t.mode,tools:g,reviewerAgent:m,diagnosticDispatcher:e.eventDispatcher});if(_.error){i=await Xa({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:i,sessionStoreName:e.runParams.sessionStoreName});let n=await go(e.runParams.dataDir,a,{status:`failed`,curatorResult:_,error:_.error,reviewState:i});await fo(e,_.error,{mode:t.mode,usage:_.usage,toolCalls:_o(_.toolCalls),toolResults:wo(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewRunLogPath:n});return}i=await Ya({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:i,reviewedTranscriptEndIndex:f.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let v=await go(e.runParams.dataDir,a,{status:`completed`,curatorResult:_,reviewState:i});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:Co(_.text,2e3),toolCalls:_o(_.toolCalls),toolResults:wo(_.toolResults),writeResults:_.writeResults,wrote:_.wrote,reviewState:i,reviewRunLogPath:v}})}catch(t){let n=t instanceof Error?t.message:String(t),r;i&&(i=await Xa({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:i,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),a&&(r=await go(e.runParams.dataDir,a,{status:`failed`,error:n,reviewState:i}).catch(()=>void 0))),await fo(e,n,r?{reviewRunLogPath:r}:void 0)}}function oo(e){return{mode:so(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function so(e){if(e==null)return ro;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?io.has(t)?t:`off`:ro}function co(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 lo(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function uo(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function fo(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 po(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 mo(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function ho(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:So(n),...i.packet?{packet:i.packet}:{}}})}async function go(e,t,n){return no(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?yo(n.curatorResult.text):void 0,conclusionText:n.curatorResult?bo(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?_o(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?wo(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 _o(e){return e.map(e=>({...e,arguments:vo(e.name,e.arguments)}))}function vo(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 yo(e){let t=xo(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function bo(e){return yo(e)?void 0:Co(e,8e3)}function xo(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 So(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 Co(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function wo(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}const To=2,Eo=5;var Do=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: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&&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 Oo=new Map;function ko(e){let t=Oo.get(e);return t||(t={},Oo.set(e,t)),t}function Ao(e){Oo.delete(e)}function jo(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Mo(e){if(!jo(e))return null;let t=e,n=No(t.message),r=Fo(n?.code)??Fo(t.code),i=Fo(n?.type)??Fo(t.type),a=Fo(n?.message)??Po(t.error)??Fo(t.message)??`Unknown upstream error`;return{message:Io(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Lo(r,i),raw:e}}function No(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 Po(e){if(!(!e||typeof e!=`object`))return Fo(e.message)}function Fo(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Io(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Lo(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 Ro=(e,t,n)=>{let r=new Be;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0};try{let a=Bo(e,t,n?.apiKey||Pe(e.provider)||``,n?.headers),o=Vo(e,t,n);n?.onPayload?.(o);let s=await a.chat.completions.create(o,{signal:n?.signal});r.push({type:`start`,partial:i});let c=null,l=i.content,u=()=>l.length-1,d=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:u(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:u(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=Fe(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:u(),toolCall:e,partial:i}))}};for await(let t of s){let n=Mo(t);if(n)throw new J({message:`LLM upstream returned an error payload in a 200 stream: ${n.message}`,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Ne(e,i.usage)}let a=t.choices?.[0];if(!a||(a.finish_reason&&(i.stopReason=qo(a.finish_reason)),!a.delta))continue;a.delta.content!==null&&a.delta.content!==void 0&&a.delta.content.length>0&&((!c||c.type!==`text`)&&(d(c),c={type:`text`,text:``},i.content.push(c),r.push({type:`text_start`,contentIndex:u(),partial:i})),c.text+=a.delta.content,r.push({type:`text_delta`,contentIndex:u(),delta:a.delta.content,partial:i}));let o=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=a.delta[e];return t!=null&&t.length>0});if(o){(!c||c.type!==`thinking`)&&(d(c),c={type:`thinking`,thinking:``,thinkingSignature:o},i.content.push(c),r.push({type:`thinking_start`,contentIndex:u(),partial:i}));let e=a.delta[o];c.thinking+=e,r.push({type:`thinking_delta`,contentIndex:u(),delta:e,partial:i})}if(a.delta.tool_calls)for(let e of a.delta.tool_calls){(!c||c.type!==`toolCall`||e.id&&c.id!==e.id)&&(d(c),c={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(c),r.push({type:`toolcall_start`,contentIndex:u(),partial:i})),e.id&&(c.id=e.id),e.function?.name&&(c.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,c.partialArgs+=e.function.arguments,c.arguments=Fe(c.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:u(),delta:t,partial:i})}let s=a.delta.reasoning_details;if(s&&Array.isArray(s)){for(let e of s)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(d(c),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(e){for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e),e instanceof 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},zo=(e,t,n)=>{let r=n?.apiKey||Pe(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=We(e,n,r),a=Re(e)?n?.reasoning:Ge(n?.reasoning);return Ro(e,t,{...i,reasoningEffort:a,toolChoice:void 0})};function Bo(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};if(e.provider===`github-copilot`){let e=Ue(t.messages);Object.assign(i,He({messages:t.messages,hasImages:e}))}return r&&Object.assign(i,r),new ze({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Vo(e,t,n){let r=Yo(e),i=Go(e,t,r);Wo(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=Ko(t.tools,r):Ho(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 Ho(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 Uo(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 Wo(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 Go(e,t,n){let r=[],i=t=>{if(n.requiresMistralToolIds)return Uo(t);if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=Ke(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Ve(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:Ve(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Ve(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>Ve(e.text)).join(``):a.map(e=>({type:`text`,text:Ve(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
|
|
18
18
|
|
|
19
19
|
`);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(`
|
|
20
20
|
`))}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(`
|
|
21
|
-
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:
|
|
22
|
-
`);async function
|
|
23
|
-
`)}}function
|
|
21
|
+
`),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:Ve(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function Ko(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function qo(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 Jo(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 Yo(e){let t=Jo(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresMistralToolIds:e.compat.requiresMistralToolIds??t.requiresMistralToolIds,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode}:t}let Xo=!1;function Zo(){Xo||=(Le(),Ie({api:`openai-completions`,stream:Ro,streamSimple:zo}),!0)}const Qo=[`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(`
|
|
22
|
+
`);async function $o(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o}=e,s=t.trim().replace(/\s+/g,` `);if(!s)return`New session`;if(!r.flashModel)return ts(s);let c=r.flashModel,l=mr({baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:c,hooks:a,hookCtx:o}),u=[{role:`user`,content:s}];n&&u.push({role:`assistant`,content:n});for(let e=1;e<=3;e++)try{let e=(await l.chat({system:Qo,user:JSON.stringify(u),temperature:0,maxTokens:100,signal:i})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;e<3&&await es(500*e)}return ts(s)}function es(e){return new Promise(t=>setTimeout(t,e))}function ts(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 Z(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}async function ns(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 rs(e){let{sessionId:t,result:n,runParams:i,hookRegistry:a,hookContext:o}=e;await a.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs},o,{eventDispatcher:e.eventDispatcher});let s=await r(i.dataDir,t,{...Z(i)});await a.dispatch(`session_end`,{sessionId:t,messageCount:s.length,durationMs:n.durationMs},o,{eventDispatcher:e.eventDispatcher})}async function is(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:a=!1,runParams:o,hookRegistry:c,hookContext:l,startTime:u,compactionEntry:d,eventDispatcher:f}=e,m=Z(o);if(a||await C(o.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},m),d&&await C(o.dataDir,n,d,m),await C(o.dataDir,n,{role:`assistant`,content:t,timestamp:new Date().toISOString()},m),r){let t=await $o({message:i.trim()?i:`New session`,llm:o.llm,text:e.replyText,hooks:c,hookCtx:l});await p(o.dataDir,n,{title:t},m),await f.dispatchProgress(n,{type:`title_updated`,title:t})}let h=Date.now()-u,g={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:h,context:{snapshotPath:T(o.dataDir,n,Z(o)),toolResultsDir:s(o.dataDir,n,Z(o))}};return Y.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:h,isNewSession:r,textLength:t.length,hasCompactionEntry:!!d,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir}),await rs({sessionId:n,result:g,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:f}),g}async function as(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:a,hookContext:o,startTime:c,text:l,usage:u,error:d,paused:f,uiToolPending:m,eventDispatcher:h}=e;if(n){let n=Z(i),s=await $o({message:r,llm:i.llm,text:e.text,hooks:a,hookCtx:o});await p(i.dataDir,t,{title:s},n),await h.dispatchProgress(t,{type:`title_updated`,title:s})}let g={sessionId:t,text:l,usage:u,durationMs:Date.now()-c,error:d,paused:f,uiToolPending:m,context:{snapshotPath:T(i.dataDir,t,Z(i)),toolResultsDir:s(i.dataDir,t,Z(i))}},_={sessionId:t,kind:`completed`,durationMs:g.durationMs,isNewSession:n,inputTokens:u.input,outputTokens:u.output,totalTokens:u.total,hasError:!!d,error:d,paused:!!f,uiToolPending:!!m,textLength:l.length,snapshotPath:g.context.snapshotPath,toolResultsDir:g.context.toolResultsDir};return d?Y.warn(`agent run finalized with error`,_):Y.info(`agent run finalized`,_),await rs({sessionId:t,result:g,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:h}),g}const os=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`}];function ss(){return os.map(e=>({...e}))}function cs(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function ls(e){let t=new Set,n=[];for(let r of e){let e=cs(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function us(e){let t=ss(),n=ls(e);return{builtin:t,skillCommands:n,all:[...t,...n]}}function ds(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 fs(e){let t=ds(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 ps(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 ms(e,t){let n=fs(e);if(!n)return{kind:`none`};if(n.name===`help`)return n.rest?{kind:`unknown`,name:n.name,args:n.rest}:{kind:`help`};if(n.name===`compact`)return{kind:`compact`,instructions:n.rest};if(n.name===`new`||n.name===`reset`)return{kind:`reset`,action:n.name===`new`?`new`:`reset`,remainder:n.rest};if(n.name===`skill`){if(!n.rest)return{kind:`unknown`,name:n.name,args:``};let e=n.rest.match(/^([^\s]+)(?:\s+([\s\S]+))?$/);return e?{kind:`skill`,name:cs(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(ls(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 hs=new Set([`/new`,`/reset`,`/compact`]),gs=new Set([`/help`]);function _s(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function vs(e){if(e.length===0)return[];let t=e.map(_s),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function ys(e){let t=us(e.skills),n=t.builtin.filter(e=>hs.has(e.name)),r=t.builtin.filter(e=>e.name===`/skill`),i=t.builtin.filter(e=>gs.has(e.name)),a=t.skillCommands.slice(0,4),o=[];return o.push(`帮助`),o.push(``),o.push(`会话命令`),o.push(...vs(n)),o.push(``),o.push(`技能命令`),o.push(...vs(r)),a.length>0?(o.push(...vs(a)),t.skillCommands.length>a.length&&o.push(` ... 还有 ${t.skillCommands.length-a.length} 个`)):o.push(` 未安装技能命令`),o.push(``),o.push(`其他命令`),o.push(...vs(i)),{kind:`reply`,text:o.join(`
|
|
23
|
+
`)}}function bs(e,t){let n=t.trim().toLowerCase();return n&&ls(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function xs(e){let t=bs(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(`
|
|
24
24
|
|
|
25
|
-
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function
|
|
26
|
-
`):e.content;return
|
|
27
|
-
`);async function
|
|
25
|
+
`)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function Ss(e){let t=ms(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?ys(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?xs({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:{kind:`pass`,message:e.message}}function Cs(e){return Math.ceil(e.length/4*1.2)}function ws(e){if(e.role===`user`)return Cs(e.content);if(e.role===`assistant`){let t=Cs(e.content);for(let n of e.toolCalls??[])t+=Cs(n.name)+Cs(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(`
|
|
26
|
+
`):e.content;return Cs(e.toolName)+Cs(t)}function Q(e){return e.reduce((e,t)=>e+ws(t),0)}const Ts=[`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(`
|
|
27
|
+
`);async function Es(e){let{entries:t,llm:n,previousSummary:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Os(t,r,i),l,u=mr({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:Ts,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 Ds(500*e)}throw l}function Ds(e){return new Promise(t=>setTimeout(t,e))}function Os(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`?ks(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(`
|
|
28
28
|
`):t.content,i=n.length>2e3?`${n.slice(0,2e3)}… [truncated]`:n;r.push(`Tool(${t.toolName})[${e}]: ${i}`)}return r.join(`
|
|
29
|
-
`)}function
|
|
30
|
-
`)}function
|
|
31
|
-
`),
|
|
32
|
-
`)}const
|
|
33
|
-
...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...
|
|
34
|
-
`)}function
|
|
35
|
-
`),r=n>t*.5?n:t;return e.slice(0,r)}async function
|
|
36
|
-
`);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}),
|
|
37
|
-
`);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}),
|
|
29
|
+
`)}function ks(e){let t=As(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(`
|
|
30
|
+
`)}function As(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=js(t);if(e.name||e.path)return e}return{}}function js(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 Ms(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=ws(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}function Ns(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 Ps(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Fs(t),l=c>=0?t[c].content:void 0,u=Ns(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}=Ms(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:Q(u)}:{status:`compacted`,entry:{role:`compaction`,content:await Es({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:Q(d)}}function Fs(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Is=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
|
|
31
|
+
`),Ls=[`.aimax/new.txt`];async function Rs(e){try{return(await we(e,`utf-8`)).trim()||null}catch{return null}}async function zs(e){for(let t of Ls){let n=await Rs(Te(e,t));if(n)return n}return await Rs(`/aimax/new.txt`)||Is}async function Bs(e){return{kind:`reply`,text:await zs(e)}}function Vs(){return{kind:`reply`,text:`✅ Session reset.`}}function Hs(e){let t=Gs(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Ks(r):null,a=n??i?.text,o=a?ps(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?qs(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Js(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Us(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=Ss({message:e.messageForRun??``,skills:t});if(n.kind===`reply`)return{kind:`reply`,replyText:n.text,transcriptMessage:e.transcriptMessage};if(n.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:n.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(n.kind===`rewrite`){let t=e.inputMode===`text`?n.message:qs(e.promptInput,n.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Js(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Ws(e){let t=Us(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 is({replyText:(t.action===`reset`?Vs():await Bs(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 is({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};let n=await Ps({entries:e.runParams.channel===`CRON`?[]:await r(e.runParams.dataDir,e.sessionId,Z(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 is({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 Gs(e){return typeof e.message==`string`}function Ks(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 qs(e,t){let n=Ks(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 Js(e){return typeof e==`string`?e:JSON.stringify(e)}function Ys(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 Xs=[`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.`],Zs={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Qs(e,t){return e.map(e=>$s(e,t))}function $s(e,t){let n=new Date(e.timestamp).getTime();if(ec(e))return{role:`user`,content:e.content,timestamp:n};if(tc(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:Zs,stopReason:`stop`,timestamp:n}}let r=e;return{role:`toolResult`,toolCallId:r.toolCallId,toolName:r.toolName,content:[{type:`text`,text:nc(r)}],isError:r.isError,timestamp:n}}function ec(e){return e.role===`user`}function tc(e){return e.role===`assistant`}function nc(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:`,...Xs];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
|
|
32
|
+
`)}const rc=[`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 ic(e){let t=T(e.dataDir,e.sessionId,e),n=new Map,r=new Map,i=[],a=[],o=[],c,l,u=0,d,f,p=await lc(t);for(let e of p.readStates)n.set(ac(e.path,e.offset,e.limit),e);for(let e of p.toolResults)r.set(e.toolCallId,e);i.push(...p.compaction.budgets),a.push(...p.compaction.snips),o.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 s={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:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}};await H.mkdir(U.dirname(t),{recursive:!0});let p=e.encryptSessions??!1;await g(t,JSON.stringify(s,null,2),p)};return{async findReusableRead(e,t,r){let i=ac(e,t,r),a=n.get(i);if(!a)return null;let o=await sc(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:cc(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await sc(e.path)??Date.now()};return n.set(ac(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())oc(i.path)===oc(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 a=t.previewChars??2e3,o=s(e.dataDir,e.sessionId,e),c=`${t.toolCallId}.txt`,l=U.join(o,c);await H.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await g(l,t.content,u);let p=U.relative(e.dataDir,l).split(U.sep).join(`/`),h=pc(t.content,a),_={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(_.toolCallId,_),i.push({toolCallId:_.toolCallId,toolName:_.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:h.length,strategy:`persist`,createdAt:_.createdAt}),d=_.createdAt,f=`L2`,await m(),{content:fc(_),reference:_}},async recordSnip(e){a.push(e),d=e.createdAt,f=e.reason===`context_dedup`?`L1`:e.reason===`microcompact`?`L4`:`L3`,await m()},async recordCollapse(e){o.push(e),d=e.createdAt,f=e.layer,await m()},async setSessionMemory(t){c=t,await mc(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:a.slice(-200),collapseSpans:o.slice(-100),consecutiveAutocompactFailures:u,lastCompactionAt:d,lastCompactionLayer:f}}}}}function ac(e,t,n){return`${oc(e)}::${t??``}::${n??``}`}function oc(e){return U.normalize(e)}async function sc(e){try{return(await H.stat(e)).mtimeMs}catch{return null}}function cc(e){return Oe(`sha1`).update(e).digest(`hex`)}async function lc(e){try{let t=await _(e);if(t===null)return uc();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?uc():{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:dc(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 uc()}}function uc(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function dc(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 fc(e){let t=e.preview.length<e.originalChars?`
|
|
33
|
+
...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...rc,`Preview:`,e.preview+t].join(`
|
|
34
|
+
`)}function pc(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
|
|
35
|
+
`),r=n>t*.5?n:t;return e.slice(0,r)}async function mc(e,t,n,r){let i=f(e,t,r);await H.mkdir(U.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await g(i,JSON.stringify(n,null,2),a)}const hc=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function gc(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,signal:c,hooks:l,hookCtx:u,contextStore:d,dataDir:f,sessionId:p,sessionStoreName:m,sessionPathScope:h}=e,g,_=Oc(t),v=_>=0?t.slice(_+1):t;_>=0&&(g=t[_].content);let y=t.length,b=Ns(Ys(v,a)),x=[];d&&(g=await _c({entries:b,existingSummary:g,llm:i,contextStore:d,signal:c,hooks:l,hookCtx:u}));let S=b;if(S=await vc({entries:S,maxInlineResults:8,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:d,compactionEvents:x}),S=await yc({entries:S,contextStore:d,compactionEvents:x}),S=await bc({entries:S,contextStore:d,compactionEvents:x,dataDir:f,sessionId:p,sessionStoreName:m,sessionPathScope:h}),!o)return{messages:Qs(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:Q(S),compacted:!1},compactionEvents:x};let C=d?.getSnapshot(),w=Math.max(1e3,Math.floor(r*.7)),T=kc({entries:t,workingEntries:S,pendingUserMessage:s,checkpoint:C?.compaction.modelUsage}).projectedInputTokens>=w,E=C?.compaction.consecutiveAutocompactFailures??0;if(!T||E>=3)return{messages:Qs(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:Q(S),compacted:!1},compactionEvents:x};let{toKeep:D,toSummarise:O}=Ms(S,r);if(O.length===0)return{messages:Qs(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:Q(S),compacted:!1},compactionEvents:x};let k=new Date().toISOString();try{let e=C?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Es({entries:O,llm:i,previousSummary:g,signal:c,hooks:l,hookCtx:u}),r={role:`compaction`,content:t,keptCount:D.length,droppedCount:O.length,timestamp:k};return await d?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:k}),x.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${O.length} entries with session memory`:`Autocompact summarised ${O.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,Q(O)),affectedEntries:O.length,snapshotVersion:2}),{messages:Qs(Ns(D),n),priorSummary:t,compactionEntry:r,stats:{originalCount:y,keptCount:D.length,estimatedTokens:Q(D),compacted:!0},compactionEvents:x}}catch{return await d?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:k}),{messages:Qs(S,n),priorSummary:g,compactionEntry:void 0,stats:{originalCount:y,keptCount:S.length,estimatedTokens:Q(S),compacted:!1},compactionEvents:[...x,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function _c(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,signal:a,hooks:o,hookCtx:s}=e,c=Q(t),l=i.getSnapshot().compaction.sessionMemory,u=!l&&c>=8e3,d=!!l&&c>=(l?.tokenEstimate??0)+15e3&&Dc(t)>=3;if(!u&&!d)return n??l?.summary;let f=await Es({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 vc(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Sc).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(!Sc(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=Cc(n)?wc(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
|
|
36
|
+
`);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}),Ns(l.reverse())}async function yc(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(!Sc(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=Cc(r)?wc(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(`
|
|
37
|
+
`);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}),vc({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function bc(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(Sc).filter(e=>hc.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=xc(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(Q(r)-Q([g])));let _={id:ke(),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 Ac(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 xc(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(`
|
|
38
38
|
`),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
|
|
39
39
|
`);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
|
|
40
40
|
|
|
41
|
-
`)}function
|
|
42
|
-
`)}function
|
|
43
|
-
`)}function
|
|
44
|
-
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const
|
|
45
|
-
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return
|
|
46
|
-
`);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
|
|
47
|
-
`),
|
|
48
|
-
`),
|
|
49
|
-
`),lineCount:
|
|
50
|
-
`),lines:
|
|
51
|
-
`)||`(empty directory)`}],details:{entries:a}}}}}const
|
|
52
|
-
`)}function
|
|
53
|
-
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=
|
|
54
|
-
`)}function
|
|
55
|
-
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function
|
|
56
|
-
`)}],details:{matches:i}}}}}const
|
|
57
|
-
`)||`(empty)`}],details:{lines:i}}}}}const
|
|
41
|
+
`)}function Sc(e){return e.role===`tool_result`}function Cc(e){return e.toolName===`skill_load`}function wc(e){let t=Tc(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(`
|
|
42
|
+
`)}function Tc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Ec(t);if(e.name||e.path)return e}return{}}function Ec(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 Dc(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Oc(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function kc(e){let t=e.pendingUserMessage?.trim()?Q([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=Q(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=Q(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 Ac(e,t,n,r){let i=ee(e,t,r);await H.mkdir(U.dirname(i),{recursive:!0}),await H.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function jc(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await ic({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 gc({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Mc(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName}):gc({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName})}const Nc=G.Object({command:G.String({description:`Shell command to execute`}),workdir:G.Optional(G.String({description:`Working directory (relative to workspace root)`})),env:G.Optional(G.Record(G.String(),G.String())),timeout:G.Optional(G.Number({description:`Timeout in seconds (default: 1800)`})),yieldMs:G.Optional(G.Number({description:`Wait this many milliseconds before returning running state`})),background:G.Optional(G.Boolean({description:`Return immediately with running session`}))});function Pc(e,t,n){return Math.max(t,Math.min(n,e))}function Fc(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Ic(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?1e4:Pc(Math.floor(e),0,12e4)}function Lc(e,t){if(!t?.trim())return e;let n=U.isAbsolute(t)?U.normalize(t):U.normalize(U.join(e,t));if(!n.startsWith(e+U.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Rc(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 zc(e){return Vc({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
|
|
43
|
+
`)}function Bc(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Vc(e){let t=Bc(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 Hc(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:Nc,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=Lc(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Fc(n.timeout),o=e.registry.start({command:n.command,cwd:i,env:n.env,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s&&!c){let t=await e.registry.wait(o.sessionId,e.scopeKey,void 0);t&&(l=t)}else if(!s){let t=await e.registry.wait(o.sessionId,e.scopeKey,Ic(n.yieldMs));t&&(l=t)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Rc(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?Vc({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[zc(l)],p=Bc(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(`
|
|
44
|
+
`)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Uc=G.Object({action:G.String({description:`Process action: list | poll | log | kill`}),sessionId:G.Optional(G.String({description:`Session id for non-list actions`})),offset:G.Optional(G.Number({description:`Log line offset (0-based)`})),limit:G.Optional(G.Number({description:`Maximum lines to return`})),timeout:G.Optional(G.Number({description:`Poll wait time in milliseconds`}))});function Wc(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Gc(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Kc(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill.`,parameters:Uc,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(`
|
|
45
|
+
`)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Gc(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Wc(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`}}:Gc(`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}}:Gc(`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}}:Gc(`No session found for ${i}`)}return Gc(`Unsupported action: ${n.action}`)}}}const qc=2e5;function Jc(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Yc(e,t){let n=e+t;return n.length<=qc?{text:n,truncated:!1}:{text:n.slice(-qc),truncated:!0}}function Xc(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Yc(e.output,r);e.output=i.text;let a=Yc(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Zc(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:Jc(e.output),stdoutTail:Jc(e.stdout),stderrTail:Jc(e.stderr),outputTruncated:e.outputTruncated}}function Qc(e,t){return t?e.scopeKey===t:!0}function $c(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function el(e){return e?e.split(/\r?\n/):[]}function tl(e){let t=el(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=$c(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(`
|
|
46
|
+
`);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 nl(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function rl(){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),nl(e))};return{start(t){let n=Je(`bash`,[`-lc`,t.command],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`]}),r=()=>{},a=new Promise(e=>{r=e}),o={sessionId:ke(),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=>Xc(o,`stdout`,e)),n.stderr.on(`data`,e=>Xc(o,`stderr`,e));let s=$c(t.timeoutSec,1800);return o.timeoutTimer=setTimeout(()=>{o.status===`running`&&(o.status=`timeout`,Xc(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`),Xc(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`)})}),Zc(o)},get(e,t){let n=r(e);return!n||!Qc(n,t)?null:Zc(n)},list(n){return[...e.values(),...t.values()].filter(e=>Qc(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Zc(e))},async wait(e,t,n){let i=r(e);if(!i||!Qc(i,t))return null;if(i.status!==`running`)return Zc(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||!Qc(a,t)?null:Zc(a)},readLog(e){let t=r(e.sessionId);return!t||!Qc(t,e.scopeKey)?null:tl({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Qc(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||!Qc(n,t))return null;if(n.status!==`running`)return Zc(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?Zc(i):null}}}function il(e){return Hc({workspaceDir:e,registry:rl(),scopeKey:e})}const al=5*1024*1024,ol=2e3;async function sl(e,t){e&&await e(t).catch(()=>{})}function cl(e,t){return U.isAbsolute(e)?U.normalize(e):U.normalize(U.join(t,e))}const ll=G.Object({path:G.String({description:`File path (relative to workspace or absolute)`}),offset:G.Optional(G.Number({description:`Line offset (1-based, default: 1)`})),limit:G.Optional(G.Number({description:`Maximum lines to read (default: 2000)`}))});function ul(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:ll,async execute(n,r){let i;try{i=cl(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 H.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 Ye(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>al){let e=o.slice(0,al).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${al} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
|
|
47
|
+
`),l=Math.max(1,r.offset??1),u=Math.min(ol,r.limit??ol),d=c.slice(l-1,l-1+u),f=d.length<c.length-(l-1),p=d.map((e,t)=>`${(l+t).toString().padStart(4)} ${e}`).join(`
|
|
48
|
+
`),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
|
|
49
|
+
`),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
|
|
50
|
+
`),lines:d.length,truncated:f}}}}}const dl=G.Object({path:G.String({description:`File path (relative to workspace or absolute)`}),content:G.String({description:`File content to write`})});function fl(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:dl,async execute(r,i){let a;try{a=cl(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await H.mkdir(U.dirname(a),{recursive:!0}),await H.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await sl(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 pl=G.Object({path:G.String({description:`File path (relative to workspace or absolute)`}),old_string:G.String({description:`Exact text to replace`}),new_string:G.String({description:`Replacement text`})});function ml(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:pl,async execute(r,i){let a;try{a=cl(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 H.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 H.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await sl(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 hl=G.Object({path:G.Optional(G.String({description:`Directory path (default: workspace root)`}))});function gl(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:hl,async execute(t,n){let r=n.path??`.`,i;try{i=cl(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await H.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(`
|
|
51
|
+
`)||`(empty directory)`}],details:{entries:a}}}}}const _l=G.Object({input:G.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function vl(e,t){let n=U.isAbsolute(e)?U.normalize(e):U.normalize(U.join(t,e));if(!n.startsWith(t+U.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function yl(e,t){let n=U.relative(t,e);return!n||n===``?U.basename(e):n.startsWith(`..`)||U.isAbsolute(n)?e:n}async function bl(e){await H.mkdir(U.dirname(e),{recursive:!0})}async function xl(e,t){e&&await e(t).catch(()=>{})}function Sl(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(`
|
|
52
|
+
`)}function Cl(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:_l,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=Tl(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=vl(r.path,e);await bl(i),await H.writeFile(i,r.contents,`utf-8`),await xl(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),wl(o,s,`added`,yl(i,e));continue}if(r.kind===`delete`){let i=vl(r.path,e);await H.rm(i,{force:!0,recursive:!1}),await xl(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),wl(o,s,`deleted`,yl(i,e));continue}let i=vl(r.path,e),a=await kl(i,r.chunks);if(r.movePath){let c=vl(r.movePath,e);await bl(c),await H.writeFile(c,a,`utf-8`),await H.rm(i,{force:!0,recursive:!1}),await xl(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),wl(o,s,`modified`,yl(c,e))}else await H.writeFile(i,a,`utf-8`),await xl(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),wl(o,s,`modified`,yl(i,e))}return{content:[{type:`text`,text:Sl(o)}],details:{summary:o}}}catch(e){if(Tr(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function wl(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Tl(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);El(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Dl(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function El(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 Dl(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}=Ol(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 Ol(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 kl(e,t){let n=(await H.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
|
|
53
|
+
`);n.length>0&&n[n.length-1]===``&&n.pop();let r=jl(n,Al(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
|
|
54
|
+
`)}function Al(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Ml(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=Ml(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=Ml(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
|
|
55
|
+
`)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function jl(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 Ml(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(Nl(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Nl(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Nl(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Nl(e,t,n,e=>Pl(e.trim())))return n;return null}function Nl(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 Pl(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 Fl(e){return U.join(e,`.aimax`)}function Il(e){return U.join(Fl(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 Ll(e,t){let n=Fl(e),r=B({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:A({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function Rl(e){return te(Fl(e))}async function zl(e){try{return await H.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Bl(e){return zl(Il(e))}async function Vl(e,t,n){let{provider:r}=Ll(e,n);return await r.search(t)}async function Hl(e,t,n,r,i){try{let{provider:a}=Ll(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Ul(e,t,n){let{provider:r,resolvedProviderId:i}=Ll(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 Wl(e,t,n,r){let{provider:i,resolvedProviderId:a}=Ll(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 Gl(e,t,n,r){let{provider:i,resolvedProviderId:a}=Ll(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 Kl(e,t,n){let{provider:r,resolvedProviderId:i}=Ll(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 ql=G.Object({query:G.String({description:`Search query (case-insensitive substring match)`})});function Jl(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:ql,async execute(n,r){let i=(await Vl(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(`
|
|
56
|
+
`)}],details:{matches:i}}}}}const Yl=G.Object({file:G.String({description:`Memory file path (from memory_search results)`}),start_line:G.Number({description:`Start line number (1-based)`}),end_line:G.Number({description:`End line number (1-based)`})});function Xl(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:Yl,async execute(n,r){let i=await Hl(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(`
|
|
57
|
+
`)||`(empty)`}],details:{lines:i}}}}}const Zl=G.Object({content:G.String({description:`Content to write to memory`})});function Ql(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:Zl,async execute(n,r){try{return await Ul(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 $l=G.Object({section:G.Optional(G.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:G.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:G.Union([G.Literal(`append`),G.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function eu(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:$l,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Ul(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 Gl(e,`MEMORY.md`,tu(await Bl(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Ul(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 tu(e,t,n){let r=e.split(`
|
|
58
58
|
`),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(`
|
|
59
59
|
`).trimEnd(),a,r.slice(s).join(`
|
|
60
60
|
`).trimStart()].filter(e=>e.length>0).join(`
|
|
61
|
-
`)}\n`}function
|
|
61
|
+
`)}\n`}function nu(e,t){let n=e.split(`
|
|
62
62
|
`),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(`
|
|
63
63
|
`).trimEnd(),n.slice(a).join(`
|
|
64
64
|
`).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
|
|
65
|
-
`)}\n`:``}function
|
|
65
|
+
`)}\n`:``}function ru(e,t){let n=e.split(`
|
|
66
66
|
`);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
|
|
67
|
-
`)}\n`:``)}function
|
|
67
|
+
`)}\n`:``)}function iu(e,t,n){let r=e.split(`
|
|
68
68
|
`);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
|
|
69
|
-
`)}\n`)}function
|
|
70
|
-
`);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
|
|
71
|
-
`),t=
|
|
69
|
+
`)}\n`)}function au(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 ou(e,t){let n=[],r=t.split(`
|
|
70
|
+
`);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 su=G.Object({content:G.String({description:`Note to append to today's daily log`}),scope:G.Optional(G.Union([G.Literal(`daily`),G.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function cu(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:su,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Wl(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 lu=G.Object({scope:G.Optional(G.Union([G.Literal(`long-term`),G.Literal(`recent`),G.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function uu(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:lu,async execute(n,r){try{let n=r.scope??`all`,i=await Rl(e),a=[];for(let n of i.slice(0,30)){let r=await Hl(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
|
|
71
|
+
`),t=ou(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(`
|
|
72
72
|
`):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
|
|
73
73
|
|
|
74
|
-
`)||`(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
|
|
75
|
-
`),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await
|
|
76
|
-
`),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
|
|
77
|
-
`),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await
|
|
78
|
-
`);for(let t of r){let r=t.trim();if(!r||!
|
|
79
|
-
`)}function
|
|
80
|
-
`)}`}async function Bu(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 Vu=G.Object({category:G.Optional(G.String({description:`Reserved category filter field. Not used yet.`}))}),Hu=G.Object({name:G.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:G.Optional(G.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Uu(e,t,n=[]){return[...n,...t,gt(e)]}function Wu(e,t,n=[]){let r=Uu(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Vu,async execute(e,t){let n=await St(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 Gu(e){let t=Uu(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:Hu,async execute(r,i){let a=await Tt(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``}}}}}const Ku=G.Object({task:G.String({description:`The task description for the subagent to execute`}),label:G.Optional(G.String({description:`Optional short label to identify this subagent`})),agent:G.Optional(G.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.`}))}),qu=G.Object({task:G.String({description:`The task description for the subagent to execute`}),label:G.Optional(G.String({description:`Optional short label to identify this subagent`})),agent:G.Optional(G.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.`}))}),Ju=G.Object({tasks:G.Array(Ku,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Yu(e){let t=e.label?`"${e.label}"`:`task: ${De(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${Xu(e.result??`(no output)`)}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function Xu(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 Zu(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(J.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:hi(p)}),!p){let e={status:`error`,error:`task must not be empty`};return J.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 J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Ie(),v=new AbortController,y=t,b=ar(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return J.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 A(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 J.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}J.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let C=f({dataDir:s,sessionId:y,message:b?dr(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,C),J.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,J.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let w=Yu({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 J.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:w}],details:e}}let T=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return J.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:T.status,error:T.error}),{content:[{type:`text`,text:w}],isError:!0,details:T}}function Qu(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:qu,async execute(e,t){return Zu(u,e,t)}}}function $u(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:Ju,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}}J.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 Zu(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`[Batch subagents ${f}] ${o.length-d.length}/${o.length} completed`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${Xu(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
|
|
74
|
+
`)||`(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 du=G.Object({id:G.Optional(G.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:G.Optional(G.String({description:`Search query used to find memories to delete`})),limit:G.Optional(G.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:G.Optional(G.Union([G.Literal(`long-term`),G.Literal(`recent`),G.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function fu(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:du,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=au(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=nu(await Bl(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 Gl(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 Hl(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=nu(n.join(`
|
|
75
|
+
`),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Gl(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 Hl(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=ru(n.join(`
|
|
76
|
+
`),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 Gl(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 Kl(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 Vl(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await Kl(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 pu=G.Object({id:G.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:G.String({description:`New content to replace the existing memory with`})});function mu(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:pu,async execute(n,r){try{let n=au(r.id);if(n.section){let i=tu(await Bl(e)??``,n.section,r.content);return await Gl(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 Hl(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=iu(i.join(`
|
|
77
|
+
`),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Gl(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 Gl(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 hu=G.Object({query:G.Optional(G.String({description:`Search query; omit to browse recent sessions.`})),role_filter:G.Optional(G.Union([G.Literal(`user`),G.Literal(`assistant`),G.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:G.Optional(G.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:G.Optional(G.Union([G.Literal(`llm`),G.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function gu(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:hu,async execute(n,i){let a=_u(i.limit),o=i.summary_mode??`llm`,s=i.query?.trim(),c=i.role_filter;if(!s){let n=await vu(e,a,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let l=await yu({dataDir:e,query:s,roleFilter:c,messageLimit:50,sessionLimit:a,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(l.length===0){let e={mode:`query`,query:s,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let u=[];for(let n of l){let i=Mu(s,n.snippets);if(o===`off`){u.push({session_id:n.sessionId,summary:i,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){u.push({session_id:n.sessionId,summary:i,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let a=await Es({entries:ku(Ou(await r(e,n.sessionId,{storeName:t?.sessionStoreName})),s,1e5),llm:t.llm,instructions:ju({query:s})});u.push({session_id:n.sessionId,summary:a.trim()||i,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){u.push({session_id:n.sessionId,summary:i,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let d={mode:`query`,query:s,count:u.length,results:u};return{content:[{type:`text`,text:JSON.stringify(d,null,2)}],details:d}}}}function _u(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function vu(e,t,n){let r=await m(e,{storeName:n?.sessionStoreName}),a=[];for(let t of r){if(t===n?.sessionId)continue;let r=await i(e,t,{storeName:n?.sessionStoreName});r&&a.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return a.sort((e,t)=>t.when.localeCompare(e.when)),a.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function yu(e){let t=e.messageLimit??50,n=(await m(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Cu(e.query),a=(await Nu(n,6,async t=>bu({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Du).slice(0,t);if(a.length===0)return[];let o=new Map;for(let e of a){let t=o.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),o.set(e.sessionId,t)}let s=Array.from(o.values());for(let t of s){let n=await i(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return s.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),s.slice(0,e.sessionLimit)}async function bu(e){let t=await _(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
|
|
78
|
+
`);for(let t of r){let r=t.trim();if(!r||!xu(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!Su(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Tu(i.content,e.terms,i.role);if(a<=0)continue;let o=Eu(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(Du),n.length=20)}return n.sort(Du),n}function xu(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Su(e){return e===`user`||e===`assistant`||e===`tool_result`}function Cu(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=>wu(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 wu(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 Tu(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 Eu(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Du(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Ou(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function ku(e,t,n){if(e.length===0)return e;let r=Cu(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 Au(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 Au(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 ju(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(`
|
|
79
|
+
`)}function Mu(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(`
|
|
80
|
+
`)}`}async function Nu(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 Pu=G.Object({category:G.Optional(G.String({description:`Reserved category filter field. Not used yet.`}))}),Fu=G.Object({name:G.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:G.Optional(G.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Iu(e,t,n=[]){return[...n,...t,lt(e)]}function Lu(e,t,n=[]){let r=Iu(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Pu,async execute(e,t){let n=await ht(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 Ru(e){let t=Iu(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:Fu,async execute(r,i){let a=await vt(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``}}}}}const zu=G.Object({task:G.String({description:`The task description for the subagent to execute`}),label:G.Optional(G.String({description:`Optional short label to identify this subagent`})),agent:G.Optional(G.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.`}))}),Bu=G.Object({task:G.String({description:`The task description for the subagent to execute`}),label:G.Optional(G.String({description:`Optional short label to identify this subagent`})),agent:G.Optional(G.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.`}))}),Vu=G.Object({tasks:G.Array(zu,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Hu(e){let t=e.label?`"${e.label}"`:`task: ${be(e.task)}`;return e.status===`done`?`[Subagent completed] ${t}\n\n${Uu(e.result??`(no output)`)}`:e.status===`error`?`[Subagent failed] ${t}\n\nError: ${e.error??`unknown error`}`:`[Subagent killed] ${t}`}function Uu(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 Wu(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:si(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 _=ke(),v=new AbortController,y=t,b=Zn(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 w(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 C=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,C),Y.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,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=Hu({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 Gu(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:Bu,async execute(e,t){return Wu(u,e,t)}}}function Ku(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:Vu,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 Wu(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`[Batch subagents ${f}] ${o.length-d.length}/${o.length} completed`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${Uu(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
|
|
81
81
|
|
|
82
|
-
`);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const
|
|
83
|
-
`)};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=
|
|
82
|
+
`);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const qu=G.Object({action:G.Union([`list`,`kill`].map(e=>G.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:G.Optional(G.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Ju(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 Yu(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 Xu(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:qu,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} (${Ju(e.runtimeMs)})${n}`})).join(`
|
|
83
|
+
`)};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=Yu(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}const Zu=G.Object({image:G.String({description:`Image path or URL`}),prompt:G.Optional(G.String({description:`Prompt for image analysis`})),model:G.Optional(G.String({description:`Optional model override`})),maxBytesMb:G.Optional(G.Number({description:`Optional size cap in MB`}))});function Qu(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Zu,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 $u=G.Object({reason:G.String({description:`A brief explanation of why user input is needed through this UI form.`})});function ed(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??$u,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=Ce(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 Er(e,i,t,e,o,s,n);throw Fr(r),r}}}function td(e,t){let n=U.join(e,`workspace`),r=t?.memoryOptions,i=rl(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await P(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[Hc({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume}),Kc({registry:i,scopeKey:n}),ul(n,t?.contextManager),fl(n,t?.contextManager,s),ml(n,t?.contextManager,s),gl(n),Cl(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),Jl(e,r),gu(e,r),Xl(e,r),eu(e,r),cu(e,r),uu(e,r),fu(e,r),mu(e,r),Lu(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Ru({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(na(e),ra(e),ia(e),aa(e)),t&&c.push(Gu(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Ku(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Xu(t.registry,t.parentSessionId)),c}function nd(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(`
|
|
84
84
|
`),`</auto_skill_categories>`,``].join(`
|
|
85
|
-
`)}const
|
|
85
|
+
`)}const rd={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`},id=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`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 ad(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:[...id.filter(e=>t.has(e)),...n.filter(e=>!id.includes(e)).sort()],displayName:t}}function od(e){let{ordered:t,displayName:n}=ad(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)??rd[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
|
|
86
86
|
`),``].join(`
|
|
87
|
-
`)}function
|
|
88
|
-
`)}function
|
|
89
|
-
`)}function
|
|
90
|
-
`)}function
|
|
87
|
+
`)}function sd(){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(`
|
|
88
|
+
`)}function cd(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
|
|
89
|
+
`)}function ld(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(`
|
|
90
|
+
`)}function ud(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` </skill>`].join(`
|
|
91
91
|
`)).join(`
|
|
92
92
|
`)}\n</available_skills>`,``].join(`
|
|
93
|
-
`)}function
|
|
94
|
-
`)}function
|
|
95
|
-
`)}function
|
|
96
|
-
`)}function
|
|
97
|
-
`)}function
|
|
98
|
-
`)}function
|
|
99
|
-
`)}function
|
|
100
|
-
`)}function
|
|
101
|
-
`)}function
|
|
102
|
-
`)}function
|
|
103
|
-
`)}function
|
|
104
|
-
`)}function
|
|
105
|
-
`):``}function
|
|
106
|
-
`)}const
|
|
107
|
-
`).trim()}function qd(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Hd(e)}function Jd(e,t,n,r){if(r!==void 0)return`error:${Wd(qd(r))}`;if(!Bd(n))return n===void 0?void 0:Wd(n);let i=Bd(n.details)?n.details:{},a=Kd(n);if(Gd(e,t)&&e===`process`&&Bd(t)){let e=t.action;if(e===`poll`)return Wd({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Wd({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 Wd({details:i,text:a})}function Yd(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 Xd(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 Zd(e,t){return[e,t].toSorted().join(`|`)}function Qd(e,t,n,r){let i=zd(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Vd(t,n),s=Yd(a,t,o),c=s.count,l=Gd(t,n),u=Xd(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:${Zd(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 $d(e,t,n,r,i){let a=zd(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Vd(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function ef(e,t){let n=zd(t.config),r=Jd(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Vd(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 tf(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 nf(e){return e&&e.trim()||`tool`}function rf(e,t,n){if(!e.execute)return e;let r=nf(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Qd(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);tf(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}$d(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return ef(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw ef(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function af(e,t,n){return e.map(e=>rf(e,t,n))}async function of(e){let{session:{runParams:t,sessionId:n,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:s},runtimeInputs:{contextFiles:c,bootstrapWarnings:l,skills:u,autoSkillCategories:d,effectivePromptText:p,pluginTools:m,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 r(t.dataDir,n,X(t)),E={model:t.llm.model,api:`openai-completions`},D=await zc({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 Bc({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,pendingUserMessage:p,signal:x,hooks:i,hookCtx:a,contextManager:D,dataDir:t.dataDir,sessionId:n});await cf({sessionId:n,historyResult:O,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let k=t.subagentContext?.depth??0,A=f(t.dataDir,n,X(t)),j=lr([...cd(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,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy,sessionEncryption:t.sessionEncryption},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:h,skillsLoadPaths:g,reportSkillUsed:async e=>{await s.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,spawnFn:y}),...m],C),M=j.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),ee={};for(let e of j){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||ee[t]||(ee[t]=n)}let N=t.messaging?.enabled??t.channel!==`CRON`,te=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],P=Md({dataDir:t.dataDir,projectDir:t.projectDir,skills:cr(u,C),autoSkillCategories:S?d:[],contextFiles:c,toolNames:M,toolSummaries:ee,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:N,channels:te},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:et.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});P=await sf({systemPrompt:P,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let F=await i.dispatch(`before_prompt_build`,{prompt:p},a,{eventDispatcher:s});for(let e of F)e&&(e.systemPrompt&&(P=e.systemPrompt),e.prependContext&&(P=`${e.prependContext}\n\n${P}`));await i.dispatch(`after_prompt_build`,{prompt:p,systemPrompt:P},a,{eventDispatcher:s});let I=af(Id(j,i,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},Lo),L=C?.model??t.llm.model,R=await i.dispatch(`before_model_resolve`,{prompt:p},a,{eventDispatcher:s});for(let e of R)e&&e.modelOverride&&(L=e.modelOverride);let z=b({...t.llm,model:L},n,t.messageId,t.channel),B=new Le({initialState:{systemPrompt:P,model:z,tools:I,messages:[]},getApiKey:e=>t.llm.apiKey});return O.messages.length>0&&B.replaceMessages(O.messages),{agent:B,resolvedModelId:L,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:o.workspaceDir}}async function sf(e){if((await re(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 ${w(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 cf(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=lf(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 lf(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(`
|
|
108
|
-
|
|
109
|
-
`):void 0}}async function
|
|
93
|
+
`)}function dd(e=[]){let t=nd(e).trim();return t?`${t}\n`:``}function fd(){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(`
|
|
94
|
+
`)}function pd(){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(`
|
|
95
|
+
`)}function md(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(`
|
|
96
|
+
`)}function hd(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(`
|
|
97
|
+
`)}function gd(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(`
|
|
98
|
+
`)}function _d(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=vd(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
|
|
99
|
+
`)}function vd(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 yd(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(`
|
|
100
|
+
`)}function bd(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(`
|
|
101
|
+
`)}function xd(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(`
|
|
102
|
+
`)}function Sd(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(`
|
|
103
|
+
`)}function Cd(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(`
|
|
104
|
+
`)}function wd(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(`
|
|
105
|
+
`):``}function Td(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:[...id],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Cd(e.subagentDepth??0),od({toolNames:i,toolSummaries:e.toolSummaries}),ld(n),sd(),nr(e.availableAgents??[]),ud(a),dd(e.autoSkillCategories),fd(),pd(),md(e.memoryCitationsMode??`off`),hd({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),gd(e.sandboxInfo),_d({currentDate:e.currentDate,timezone:e.timezone}),cd(),yd({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),xd({isMinimal:n}),bd(e.runtimeInfo),Sd({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),wd(e.priorConversationSummary)].filter(Boolean).join(`
|
|
106
|
+
`)}const Ed=Symbol(`pluginToolOwner`);var Dd=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,Ed,{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=ed({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,Ed,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Od(e){return e[Ed]}function kd(e,t,n,r){return e.map(e=>{let i=e,a=e.name??`unknown`,o=Od(e);return{...i,async execute(e,s,c,l){let u=Date.now(),d=s??{},f=!1,p,m=async e=>o?await ur({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(Tr(e))return jr(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(Tr(i)){jr(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 Ad={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function jd(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Md(e){let t=jd(e?.warningThreshold,Ad.warningThreshold),n=jd(e?.criticalThreshold,Ad.criticalThreshold),r=jd(e?.globalCircuitBreakerThreshold,Ad.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Ad.enabled,historySize:jd(e?.historySize,Ad.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Ad.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Ad.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Ad.detectors.pingPong}}}function Nd(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Pd(e,t){return`${e}:${Ld(t)}`}function Fd(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Fd).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Fd(t[e])}`).join(`,`)}}`}function Id(e){try{return Fd(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 Ld(e){let t=Id(e);return Oe(`sha256`).update(t).digest(`hex`)}function Rd(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Nd(t))return!1;let n=t.action;return n===`poll`||n===`log`}function zd(e){return!Nd(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Nd(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
107
|
+
`).trim()}function Bd(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Fd(e)}function Vd(e,t,n,r){if(r!==void 0)return`error:${Ld(Bd(r))}`;if(!Nd(n))return n===void 0?void 0:Ld(n);let i=Nd(n.details)?n.details:{},a=zd(n);if(Rd(e,t)&&e===`process`&&Nd(t)){let e=t.action;if(e===`poll`)return Ld({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Ld({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 Ld({details:i,text:a})}function Hd(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 Ud(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 Wd(e,t){return[e,t].toSorted().join(`|`)}function Gd(e,t,n,r){let i=Md(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Pd(t,n),s=Hd(a,t,o),c=s.count,l=Rd(t,n),u=Ud(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:${Wd(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 Kd(e,t,n,r,i){let a=Md(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Pd(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function qd(e,t){let n=Md(t.config),r=Vd(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Pd(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 Jd(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 Yd(e){return e&&e.trim()||`tool`}function Xd(e,t,n){if(!e.execute)return e;let r=Yd(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Gd(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Jd(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Kd(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return qd(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw qd(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Zd(e,t,n){return e.map(e=>Xd(e,t,n))}async function Qd(e){let{session:{runParams:t,sessionId:n,hookRegistry:i,hookContext:a,runContext:o,eventDispatcher:s},runtimeInputs:{contextFiles:c,bootstrapWarnings:u,skills:d,autoSkillCategories:f,effectivePromptText:p,pluginTools:m,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 r(t.dataDir,n,Z(t)),E={model:t.llm.model,api:`openai-completions`},D=await jc({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 Mc({entries:T,modelInfo:E,contextWindowTokens:t.llm.contextWindow??2e5,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},historyLimit:t.historyLimit,compactionEnabled:!0,pendingUserMessage:p,signal:x,hooks:i,hookCtx:a,contextManager:D,dataDir:t.dataDir,sessionId:n});await ef({sessionId:n,historyResult:O,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let k=t.subagentContext?.depth??0,ee=l(t.dataDir,n,Z(t)),A=tr([...td(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:ee,registry:v,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:g,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,autoSkills:t.autoSkills,onProgress:t.onProgress,messageId:t.messageId,agentPolicy:t.agentPolicy},loopDetection:t.loopDetection,autoSkillsLoadEnabled:S,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:h,skillsLoadPaths:g,reportSkillUsed:async e=>{await s.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,spawnFn:y}),...m],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 N=t.messaging?.enabled??t.channel!==`CRON`,te=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],P=Td({dataDir:t.dataDir,projectDir:t.projectDir,skills:er(d,C),autoSkillCategories:S?f:[],contextFiles:c,toolNames:j,toolSummaries:M,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:u,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:N,channels:te},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:qe.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:_,activeAgentSystemPrompt:C?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});P=await $d({systemPrompt:P,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let F=await i.dispatch(`before_prompt_build`,{prompt:p},a,{eventDispatcher:s});for(let e of F)e&&(e.systemPrompt&&(P=e.systemPrompt),e.prependContext&&(P=`${e.prependContext}\n\n${P}`));await i.dispatch(`after_prompt_build`,{prompt:p,systemPrompt:P},a,{eventDispatcher:s});let I=Zd(kd(A,i,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},ko),L=C?.model??t.llm.model,R=await i.dispatch(`before_model_resolve`,{prompt:p},a,{eventDispatcher:s});for(let e of R)e&&e.modelOverride&&(L=e.modelOverride);let z=b({...t.llm,model:L},n,t.messageId,t.channel),B=new Ae({initialState:{systemPrompt:P,model:z,tools:I,messages:[]},getApiKey:e=>t.llm.apiKey});return O.messages.length>0&&B.replaceMessages(O.messages),{agent:B,resolvedModelId:L,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:T.length,workspaceDir:o.workspaceDir}}async function $d(e){if((await I(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 ${v(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 ef(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=tf(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 tf(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(`
|
|
108
|
+
|
|
109
|
+
`):void 0}}async function nf(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=rf(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await ci({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 rf(e){if(e.length===1){let t=e[0];return Hu({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Hu({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
|
|
110
110
|
|
|
111
111
|
---
|
|
112
112
|
|
|
113
|
-
`)}`}function ff(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 pf(e){let t=ff(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=U.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 mf(e){let t=e.watchFactory??((e,t,n)=>W.watch(e,t,n)),n=U.join(e.dataDir,`.aimax`),r=[{target:U.join(n,`MEMORY.md`),kind:`memory-file`},{target:U.join(n,`memory.md`),kind:`memory-file-lower`},{target:U.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=pf({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}async function hf(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=U.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=vf(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??h.id})`:`memory_log routed to ${t} (provider=${p.providerId??h.id})`,details:{providerId:p.providerId??h.id,resolvedProviderId:m?.registration.id??h.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof h.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=U.join(t.dataDir,`.aimax`),m=se({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=m?.provider??F({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g=m?.registration.id??h.id,_=m?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:g,pluginId:_,providerSource:m?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!m}}).catch(()=>{});let v=mf({dataDir:t.dataDir,sessionId:i,providerId:o??s??g,provider:h,onMemoryChanged:f});h.sync&&h.sync(`session-start`).catch(()=>{});let y=async e=>{await k(t.dataDir,i,e,_f({sessionOptions:X(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:y,persistInitialUserEntry:async e=>d?!1:(await y({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{v()}}}function gf(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function _f(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 vf(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}function yf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bf(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function xf(){let e=et.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Sf(e){let t=e.trim(),n=xf();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?U.join(n,t.slice(2)):void 0:U.resolve(t)}const Cf=new rt({allErrors:!0,strict:!1}),wf=new Map;function Tf(e,t){let n=wf.get(t);if(n)return n;let r=Cf.compile(e);return wf.set(t,r),r}function Ef(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Tf(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Df(e){let t=bf(e?.allow),n=bf(e?.deny),r=bf(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 Of(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=Ef({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 kf(e){try{return W.realpathSync(e)}catch{return null}}function Af(e){try{return W.statSync(e)}catch{return null}}function jf(e,t){let n=U.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!U.isAbsolute(n)}function Mf(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Nf=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Pf=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Ff(e){let t=U.join(e,`package.json`);if(W.existsSync(t))try{let e=JSON.parse(W.readFileSync(t,`utf-8`));return yf(e)?e:void 0}catch{return}}function If(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 Lf(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Rf(e){let t=kf(e.source),n=kf(e.rootDir);return!t||!n||jf(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function zf(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=U.resolve(r);if(n.has(t))continue;n.add(t);let i=Af(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 Bf(e){return Rf({source:e.source,rootDir:e.rootDir})||zf({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Lf(e.ownershipUid)})}function Vf(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=${Mf(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Hf(e){let t=Bf({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Vf(t),source:e.source}),!0):!1}function Uf(e){return U.basename(e,U.extname(e))}function Wf(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 Gf(e){for(let t of Pf){let n=U.join(e,t);if(W.existsSync(n))return n}return null}function Kf(e){let t;try{t=W.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=U.join(e.rootDir,n.name);if(n.isFile()){if(!Nf.has(U.extname(n.name)))continue;let r=U.dirname(t);if(Hf({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Wf({idHint:Uf(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Ff(t),i=If(r);if(i.status===`ok`){for(let n of i.entries){let i=U.resolve(t,n);if(!jf(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!W.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Nf.has(U.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Hf({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Uf(i)}`:Uf(i);e.candidates.push(Wf({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=Gf(t);a&&(Hf({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Wf({idHint:U.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function qf(e){return e?e.map(Sf).filter(e=>typeof e==`string`&&e.length>0):[]}function Jf(){let e=xf();if(e)return U.join(e,`.aimax`,`extensions`)}function Yf(e){return U.join(e,`.aimax`,`extensions`)}function Xf(e){return U.join(e,`.aimax`,`extensions`)}function Zf(e={}){let t=[],n=[],r=qf(e.extraPaths);for(let i of r){if(!W.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Af(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Nf.has(U.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=U.dirname(i);if(Hf({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Wf({idHint:Uf(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Kf({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Kf({rootDir:Yf(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Kf({rootDir:Xf(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Jf();return i?Kf({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&&Kf({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Qf(e){let t=e.rejectHardlinks??!0,n=kf(e.rootPath),r=kf(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!jf(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=W.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:W.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const $f=`aimax.plugin.json`,ep=[$f];function tp(e){for(let t of ep){let n=U.join(e,t);if(W.existsSync(n))return n}return U.join(e,$f)}function np(e,t=!0){let n=tp(e),r=Qf({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(W.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{W.closeSync(r.fd)}if(!yf(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=yf(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=bf(i.skills),f;return yf(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 rp(e){let t=new Map,n=[];for(let r of e){let e=np(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 ip=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function ap(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===ip.ERROR){J.error(i);return}if(e===ip.WARN){J.warn(i);return}J.info(i)}function op(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>ap(ip.INFO,e.pluginId,t,n),warn:n=>ap(ip.WARN,e.pluginId,t,n),error:n=>ap(ip.ERROR,e.pluginId,t,n)})}}}function sp(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 cp(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 lp(e){let t=[...e.registry.diagnostics],n=new Pd,r=new br,i=[],a=[],o=e.runtime?.llm?Sr({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=up(e.runtime?.llmAllowlist),c=it(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=sp({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=cp({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=op({pluginId:l.id}),g=e.plugins.entries[l.id]?.config,_={id:l.id,source:l.source,rootDir:l.rootDir,config:g,runtime:h,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!dp(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`);M({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);ce({pluginId:l.id,id:e.id,create:e.create,config:g,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=U.isAbsolute(e)?e:U.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>yr(l.id)};try{m(_)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=U.isAbsolute(e)?e:U.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function up(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function dp(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function fp(e={}){let t=Df(e.config),n=Zf({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=rp(n.candidates),i=Of({config:t,registry:r}),a=lp({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 pp(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?fp({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new br,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 mp(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=U.join(t.dataDir,`workspace`),a=n,o=!a,s=X(t);a?(await p(t.dataDir,a,s)||(o=!0),await V(t.dataDir,a,s)):a=await A(t.dataDir,t.channel,{...s});let c={sessionId:a,workspaceDir:i,channel:t.channel},l=pp({runParams:t,hookContext:c,sessionId:a,eventDispatcher:r}),u=l.hookRegistry,d=await hf({runParams:t,sessionId:a,hookContext:c,memoryProviderId:t.memory?.providerId,memoryPluginId:l.memoryPluginId,eventDispatcher:r,hookRegistry:u});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:c,hookRegistry:u,pluginContext:l,runContext:d,start:e=>us({sessionId:a,runParams:t,hookRegistry:u,hookContext:c,eventDispatcher:r,...e})}}function hp(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function gp(e){if(!(e instanceof Error))return{errorValue:hp(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]=hp(n[e]));return t}async function _p(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...gp(e.error)}})}function vp(e,t,n){return U.join(f(e,t,n),`pending-hitl.json`)}function yp(e,t,n){return U.join(f(e,t,n),`hitl-history.jsonl`)}async function bp(e,t,n,r){let i=f(e,t,r);await H.mkdir(i,{recursive:!0});let a=vp(e,t,r),o=r?.encryptSessions??!1;await S(a,JSON.stringify(n,null,2),o,r?.sessionEncryption)}async function xp(e,n,r,i){let a=f(e,n,i);await H.mkdir(a,{recursive:!0}),await t(yp(e,n,i),JSON.stringify(r)+`
|
|
114
|
-
`,
|
|
115
|
-
`)){let t=e.trim();if(t)try{i.push(JSON.parse(t))}catch{}}return i}async function wp(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await bp(e,t,c,o),await xp(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function Tp(e,t,n,r,i,a){let o=await Sp(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await bp(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await xp(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function Ep(e,t,n,r){let i=await Sp(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function Dp(e,t,n){let r=vp(e,t,n);try{await H.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function Op(e,t,n){return U.join(f(e,t,n),`pending-ui-tool.json`)}async function kp(e,t,n,r){let i=f(e,t,r);await H.mkdir(i,{recursive:!0}),await S(Op(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions,r?.sessionEncryption)}async function Ap(e,t,n){let r=await R(Op(e,t,n),n?.sessionEncryption);return r===null?null:JSON.parse(r)}async function jp(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await kp(e,t,a,r),a}async function Mp(e,t,n,r,i){let a=await Ap(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 kp(e,t,o,i),o}async function Np(e,t,n){try{await H.unlink(Op(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const Pp=`crons`;function Fp(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:hi(e.message)}}function Yn(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}function Ip(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!ke(t))}async function Lp(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=Lr();if(i=await Rr(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Nr(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Rp(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 Rp(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 zp(e,t){mi(e.dataDir),as();let n=Date.now(),i=new xr(e),a=Xs(e);J.info(`agent invocation prepared`,{requestedSessionId:a.requestedSessionId,previousSessionId:a.previousSessionId,inputMode:a.inputMode,hasSlashCommand:!!a.slashCommandSource,resetAction:a.resetCommand?.action,resetShortCircuit:a.resetShortCircuit,transcriptLength:a.transcriptMessage.length,messageForRunLength:a.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let o=a.transcriptMessage,s=!1,c=a.previousSessionId,l=await mp({runParams:e,requestedSessionId:a.requestedSessionId,eventDispatcher:i}),u=l.sessionId,d=l.isNewSession,f=l.workspaceDir,p=l.hookContext,m=l.hookRegistry,h=l.pluginContext,g=l.runContext,_=(await r(e.dataDir,u,{storeName:e.sessionStoreName})).length;J.info(`agent run started`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:d,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:d,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),J.info(d?`session created`:`session resumed`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}),await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:d?`session_created`:`session_resumed`,message:d?`session created`:`session resumed`,details:{requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}}),d&&await ee(e.dataDir,gf({sessionId:u,title:ls(o),channel:e.channel}),X(e)),a.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(s=await g.persistInitialUserEntry(o)),await l.start({resetCommand:a.resetCommand,previousSessionId:c,resetMessage:a.slashCommandSource,startMessage:typeof a.promptInput==`string`?a.promptInput:o});let v=new AbortController;e.abortSignal?.aborted?v.abort():e.abortSignal?.addEventListener(`abort`,()=>v.abort());let y=await lt(e.dataDir),b=[],x=ft(y,{warn:e=>b.push(e)}),S=await ht();await i.dispatchDiagnostic(u,{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}}),J.info(`bootstrap context loaded`,{sessionId:u,bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length});let C=e.skillsLoadPaths??[],w=await xt(e.dataDir,h.pluginSkillDirs,C),T=await nr({dataDir:e.dataDir,projectDir:e.projectDir,systemAgentsDir:e.systemAgentsDir,agentPolicy:e.agentPolicy}),E=T.stats(),D=e.agentPolicy?.activeAgent??T.findPublic(e.agentPolicy?.requestedAgentName);if(e.agentPolicy?.requestedAgentName&&!D)throw Error(`Unknown custom agent: ${e.agentPolicy.requestedAgentName}`);let O={...T,...D?{activeAgent:D}:{},...e.agentPolicy?.requestedAgentName?{requestedAgentName:e.agentPolicy.requestedAgentName}:{}},k={...e,agentPolicy:O};await i.dispatchDiagnostic(u,{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}))}}),J.info(`skills loaded`,{sessionId:u,skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length}),await i.dispatchDiagnostic(u,{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}))}}),J.info(`custom agents loaded`,{sessionId:u,agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:O.activeAgent?.name,requestedAgentName:O.requestedAgentName});let A=await Bp({dataDir:e.dataDir,sessionId:u,eventDispatcher:i,enabled:e.autoSkills?.load?.enabled===!0}),j=e=>g.appendTranscriptEntry(e),M=await Qs({invocation:a,skills:w,sessionId:u,isNewSession:d,initialUserEntryPersisted:s,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i});if(M.kind===`completed`)return J.info(`agent run short-circuited`,{sessionId:u,durationMs:Date.now()-n,hasError:!!M.result.error,paused:!!M.result.paused,uiToolPending:!!M.result.uiToolPending,textLength:M.result.text.length}),M.result;let N=M.effectivePrompt;o=M.transcriptMessage;let te=typeof N==`string`?N:o;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof N==`string`?`string`:`messages`,transcriptLength:o.length}}),J.info(`invocation resolved`,{sessionId:u,promptType:typeof N==`string`?`string`:`messages`,transcriptLength:o.length});let P=await of({session:{runParams:k,sessionId:u,hookRegistry:m,hookContext:p,runContext:g,eventDispatcher:i},runtimeInputs:{contextFiles:x,bootstrapWarnings:b,skills:w,autoSkillCategories:A,effectivePromptText:te,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:C,presetSystemPrompt:S.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>zp(e,new Fo),createModel:Yn,abortSignal:v.signal}}),F=P.agent,I=P.resolvedModelId;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:I,historyMessageCount:P.historyMessages.length,pluginToolCount:h.pluginTools.length}}),J.info(`agent runtime created`,{sessionId:u,modelId:I,historyMessageCount:P.historyMessages.length,pluginToolCount:h.pluginTools.length}),v.signal.addEventListener(`abort`,()=>F.abort());let L=0,R=0,z=``,B,ne=!1;try{if(Ip(e)){let t=await Lp({params:e,agent:F,sessionId:u,eventDispatcher:i,appendEntry:j,abortSignal:v.signal});return z=t.text,ps({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i,text:z,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(o);ne=e,s=e||s}await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`}),J.info(`first agent turn started`,{sessionId:u,modelId:I});let r=await gi({agent:F,message:N,continueFromHistory:!!e.uiToolResume,sessionId:u,modelId:I,historyMessages:P.historyMessages,eventDispatcher:i,hooks:m,hookCtx:p,abortSignal:v.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await j(e);for(let e of t)await j(e)}});z=r.text,L+=r.inputTokens,R+=r.outputTokens,r.error&&(B=r.error),await i.dispatchDiagnostic(u,{level:r.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!r.error,error:r.error,inputTokens:r.inputTokens,outputTokens:r.outputTokens}});let a={sessionId:u,hasError:!!r.error,error:r.error,inputTokens:r.inputTokens,outputTokens:r.outputTokens};r.error?J.warn(`first agent turn completed with error`,a):J.info(`first agent turn completed`,a),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),J.info(`announce loop started`,{sessionId:u});let c=await uf({agent:F,registry:t,sessionId:u,resolvedModelId:I,eventDispatcher:i,hookRegistry:m,hookContext:p,abortSignal:v.signal,retry:e.llmRetry,appendEntry:j});c.text&&(z=c.text),L+=c.inputTokens,R+=c.outputTokens,c.error&&!B&&(B=c.error),await i.dispatchDiagnostic(u,{level:c.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let l={sessionId:u,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?J.warn(`announce loop completed with error`,l):J.info(`announce loop completed`,l)}catch(t){if(Nr(t)){let r=t,a=e.subagentContext?.parentSessionId??u,s=a===r.request.sessionId?r.request:{...r.request,sessionId:a};await wp(e.dataDir,a,s,r.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},r.toolContext),await i.dispatchProgress(a,{type:`hitl_requested`,request:s}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),J.info(`agent paused for HITL`,{sessionId:u,requestId:s.requestId,kind:s.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:L,output:R,total:L+R};return await Vp({runtime:P,resolvedModelId:I,usage:c,currentUserEntryCoveredByUsage:ne}),ps({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i,text:z||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Fr(t)){let r=t,a=r.request.outputSchema.properties??{};await jp(e.dataDir,u,r.request,X(e)),await i.dispatchProgress(u,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(u,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${r.request.toolName}`,details:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(a).length}}),J.info(`agent paused for UI tool input`,{sessionId:u,requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(a).length});let s={input:L,output:R,total:L+R};return await Vp({runtime:P,resolvedModelId:I,usage:s,currentUserEntryCoveredByUsage:ne}),ps({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i,text:z||``,usage:s,error:void 0,uiToolPending:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchema:r.request.outputSchema,extra:r.request.extra}})}throw await _p({dispatcher:i,sessionId:u,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:d}}),J.error(`agent run failed`,{sessionId:u,channel:e.channel,isNewSession:d,error:t instanceof Error?t.message:String(t)}),t}finally{Ro(u),g.stop()}let V={input:L,output:R,total:L+R};await i.dispatchDiagnostic(u,{level:B?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!B,error:B}});let re={sessionId:u,durationMs:Date.now()-n,inputTokens:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!B,error:B};return B?J.warn(`agent run completed with error`,re):J.info(`agent run completed`,re),await Vp({runtime:P,resolvedModelId:I,usage:V,currentUserEntryCoveredByUsage:ne}),await mo({sessionId:u,runParams:k,eventDispatcher:i,transcriptStartIndex:_,result:{text:z,usage:V,durationMs:Date.now()-n,error:B}}),ps({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i,text:z,usage:V,error:B})}async function Bp(e){if(!e.enabled)return[];try{let t=await new kn({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 Vp(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 Hp(t){mi(t.dataDir);let n=Date.now(),r=new xr(t),i=Xs(t),a=i.transcriptMessage.trim()||`CRON task`,o=t.sessionStoreName;J.info(`cron run started`,{requestedSessionId:i.requestedSessionId,channel:t.channel,sessionStoreName:o,...Fp(t)});let s=i.requestedSessionId,l=!s;s?(await p(t.dataDir,s,{storeName:o})||(l=!0),await V(t.dataDir,s,{storeName:o})):s=await A(t.dataDir,t.channel,{storeName:o}),l&&await ee(t.dataDir,gf({sessionId:s,title:ls(a),channel:t.channel}),{storeName:o});let u=await A(t.dataDir,t.channel,{storeName:Pp});await r.dispatchProgress(s,{type:`subagent_spawn`,childSessionId:u,task:a}),J.info(`cron child subagent spawned`,{parentSessionId:s,childSessionId:u,taskLength:a.length,taskPreview:hi(a)});let d={...t,sessionId:u,sessionStoreName:Pp,subagentContext:{depth:1,parentSessionId:s}},f,m=`done`;try{f=await zp(d,new Fo),f.error&&(m=`error`)}catch(e){let r=e instanceof Error?e.message:String(e);f={sessionId:u,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:j(t.dataDir,u,{storeName:Pp}),toolResultsDir:c(t.dataDir,u,{storeName:Pp})}},m=`error`,J.error(`cron child run failed`,{parentSessionId:s,childSessionId:u,error:r})}await r.dispatchProgress(s,{type:`subagent_complete`,childSessionId:u,task:a,status:m}),J.info(`cron child subagent completed`,{parentSessionId:s,childSessionId:u,status:m,durationMs:Date.now()-n,hasError:!!f.error});let h=Yu({task:a,status:m,result:f.text,error:f.error}),_=new Date().toISOString();await k(t.dataDir,s,{role:`assistant`,content:h,timestamp:_,source:`cron`},{storeName:o});let v={task:a,status:m,content:h,childSessionId:u,createdAt:_};return await O(t.dataDir,s,v,{storeName:o}),await e(t.dataDir,s,e=>Up(e,8),{storeName:o}),await g(t.dataDir,s,{},{storeName:o}),{...f,sessionId:s,context:{snapshotPath:j(t.dataDir,s,{storeName:o}),toolResultsDir:c(t.dataDir,s,{storeName:o})}}}function Up(e,t){if(t<=0)return e.filter(e=>!Wp(e));let n=e.reduce((e,t,n)=>(Wp(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Wp(e)||r.has(t))}function Wp(e){return`source`in e&&e.source===`cron`}async function Gp(e,t){if(C(e.sessionEncryption),mi(e.dataDir),J.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,...Fp(e)}),e.channel===`CRON`&&!e.subagentContext)return Hp(e);let n=t??new Fo;try{return await zp(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:gp(t)}),J.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}}const Kp={"AGENTS.md":`---
|
|
113
|
+
`)}`}function af(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 of(e){let t=af(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=U.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 sf(e){let t=e.watchFactory??((e,t,n)=>W.watch(e,t,n)),n=U.join(e.dataDir,`.aimax`),r=[{target:U.join(n,`MEMORY.md`),kind:`memory-file`},{target:U.join(n,`memory.md`),kind:`memory-file-lower`},{target:U.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=of({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}async function cf(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=U.join(t.dataDir,`workspace`),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=df(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??h.id})`:`memory_log routed to ${t} (provider=${p.providerId??h.id})`,details:{providerId:p.providerId??h.id,resolvedProviderId:m?.registration.id??h.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof h.appendRecent==`function`}}).catch(()=>{})}await n.dispatchProgress(e.sessionId??i,{type:`memory_changed`,reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}).catch(()=>{}),await r.dispatch(`memory_changed`,p,{...a,sessionId:p.sessionId??a.sessionId},{eventDispatcher:n}).catch(()=>{})},p=U.join(t.dataDir,`.aimax`),m=B({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),h=m?.provider??A({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g=m?.registration.id??h.id,_=m?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:g,pluginId:_,providerSource:m?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!m}}).catch(()=>{});let v=sf({dataDir:t.dataDir,sessionId:i,providerId:o??s??g,provider:h,onMemoryChanged:f});h.sync&&h.sync(`session-start`).catch(()=>{});let y=async e=>{await C(t.dataDir,i,e,uf({sessionOptions:Z(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:y,persistInitialUserEntry:async e=>d?!1:(await y({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{v()}}}function lf(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function uf(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 df(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}function ff(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pf(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function mf(){let e=qe.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function hf(e){let t=e.trim(),n=mf();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?U.join(n,t.slice(2)):void 0:U.resolve(t)}const gf=new Xe({allErrors:!0,strict:!1}),_f=new Map;function vf(e,t){let n=_f.get(t);if(n)return n;let r=gf.compile(e);return _f.set(t,r),r}function yf(e){let t=e.cacheKey??JSON.stringify(e.schema),n=vf(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function bf(e){let t=pf(e?.allow),n=pf(e?.deny),r=pf(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 xf(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=yf({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 Sf(e){try{return W.realpathSync(e)}catch{return null}}function Cf(e){try{return W.statSync(e)}catch{return null}}function wf(e,t){let n=U.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!U.isAbsolute(n)}function Tf(e){return`0o${e.toString(8).padStart(3,`0`)}`}const Ef=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Df=[`index.ts`,`index.js`,`index.mts`,`index.cts`,`index.mjs`,`index.cjs`];function Of(e){let t=U.join(e,`package.json`);if(W.existsSync(t))try{let e=JSON.parse(W.readFileSync(t,`utf-8`));return ff(e)?e:void 0}catch{return}}function kf(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 Af(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function jf(e){let t=Sf(e.source),n=Sf(e.rootDir);return!t||!n||wf(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Mf(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=U.resolve(r);if(n.has(t))continue;n.add(t);let i=Cf(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 Nf(e){return jf({source:e.source,rootDir:e.rootDir})||Mf({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Af(e.ownershipUid)})}function Pf(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=${Tf(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Ff(e){let t=Nf({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Pf(t),source:e.source}),!0):!1}function If(e){return U.basename(e,U.extname(e))}function Lf(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 Rf(e){for(let t of Df){let n=U.join(e,t);if(W.existsSync(n))return n}return null}function zf(e){let t;try{t=W.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=U.join(e.rootDir,n.name);if(n.isFile()){if(!Ef.has(U.extname(n.name)))continue;let r=U.dirname(t);if(Ff({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Lf({idHint:If(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Of(t),i=kf(r);if(i.status===`ok`){for(let n of i.entries){let i=U.resolve(t,n);if(!wf(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!W.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!Ef.has(U.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Ff({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${If(i)}`:If(i);e.candidates.push(Lf({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=Rf(t);a&&(Ff({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Lf({idHint:U.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Bf(e){return e?e.map(hf).filter(e=>typeof e==`string`&&e.length>0):[]}function Vf(){let e=mf();if(e)return U.join(e,`.aimax`,`extensions`)}function Hf(e){return U.join(e,`.aimax`,`extensions`)}function Uf(e){return U.join(e,`.aimax`,`extensions`)}function Wf(e={}){let t=[],n=[],r=Bf(e.extraPaths);for(let i of r){if(!W.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=Cf(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!Ef.has(U.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=U.dirname(i);if(Ff({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Lf({idHint:If(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&zf({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?zf({rootDir:Hf(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&zf({rootDir:Uf(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Vf();return i?zf({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&&zf({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Gf(e){let t=e.rejectHardlinks??!0,n=Sf(e.rootPath),r=Sf(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!wf(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=W.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:W.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Kf=`aimax.plugin.json`,qf=[Kf];function Jf(e){for(let t of qf){let n=U.join(e,t);if(W.existsSync(n))return n}return U.join(e,Kf)}function Yf(e,t=!0){let n=Jf(e),r=Gf({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(W.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{W.closeSync(r.fd)}if(!ff(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=ff(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=pf(i.skills),f;return ff(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 Xf(e){let t=new Map,n=[];for(let r of e){let e=Yf(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 Zf=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Qf(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Zf.ERROR){Y.error(i);return}if(e===Zf.WARN){Y.warn(i);return}Y.info(i)}function $f(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Qf(Zf.INFO,e.pluginId,t,n),warn:n=>Qf(Zf.WARN,e.pluginId,t,n),error:n=>Qf(Zf.ERROR,e.pluginId,t,n)})}}}function ep(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 tp(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 np(e){let t=[...e.registry.diagnostics],n=new Dd,r=new fr,i=[],a=[],o=e.runtime?.llm?mr({baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=rp(e.runtime?.llmAllowlist),c=Ze(import.meta.url,{interopDefault:!0,requireCache:!1});for(let l of e.registry.manifests.values()){let u=ep({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=tp({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=$f({pluginId:l.id}),g=e.plugins.entries[l.id]?.config,_={id:l.id,source:l.source,rootDir:l.rootDir,config:g,runtime:h,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!ip(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`);E({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`);ne({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=U.isAbsolute(e)?e:U.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>dr(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=U.isAbsolute(e)?e:U.resolve(l.rootDir,e);i.push(t)}a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function rp(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function ip(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}function ap(e={}){let t=bf(e.config),n=Wf({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Xf(n.candidates),i=xf({config:t,registry:r}),a=np({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 op(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i}=e,a=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},o=t.plugins?ap({...t.plugins,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist}}):void 0;if(!o)a({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`});else{a({level:o.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:o.registry.plugins.length,enabledPluginCount:o.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:o.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:o.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:o.diagnostics.length}});for(let e of o.registry.plugins)a({level:e.status===`error`?`error`:e.status===`disabled`?`warn`:`info`,scope:`plugin`,phase:`plugin_${e.status}`,message:e.status===`error`?`plugin failed to initialize`:e.status===`disabled`?`plugin disabled`:`plugin enabled`,details:{pluginId:e.id,origin:e.origin,toolCount:e.toolCount,hookCount:e.hookCount,skillCount:e.skills.length,source:e.source,errorMessage:e.error}});for(let e of o.diagnostics)a({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}})}return{hookRegistry:o?.registry.hooks??new fr,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 sp(e){let{runParams:t,requestedSessionId:n,eventDispatcher:r}=e,i=U.join(t.dataDir,`workspace`),a=n,o=!a,s=Z(t);a?(await u(t.dataDir,a,s)||(o=!0),await F(t.dataDir,a,s)):a=await w(t.dataDir,t.channel,{...s});let c={sessionId:a,workspaceDir:i,channel:t.channel},l=op({runParams:t,hookContext:c,sessionId:a,eventDispatcher:r}),d=l.hookRegistry,f=await cf({runParams:t,sessionId:a,hookContext:c,memoryProviderId:t.memory?.providerId,memoryPluginId:l.memoryPluginId,eventDispatcher:r,hookRegistry:d});return{sessionId:a,isNewSession:o,workspaceDir:i,hookContext:c,hookRegistry:d,pluginContext:l,runContext:f,start:e=>ns({sessionId:a,runParams:t,hookRegistry:d,hookContext:c,eventDispatcher:r,...e})}}function cp(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function lp(e){if(!(e instanceof Error))return{errorValue:cp(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]=cp(n[e]));return t}async function up(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...lp(e.error)}})}function dp(e,t,n){return U.join(l(e,t,n),`pending-hitl.json`)}function fp(e,t,n){return U.join(l(e,t,n),`hitl-history.jsonl`)}async function pp(e,t,n,r){let i=l(e,t,r);await H.mkdir(i,{recursive:!0});let a=dp(e,t,r),o=r?.encryptSessions??!1;await g(a,JSON.stringify(n,null,2),o)}async function mp(e,t,n,r){let i=l(e,t,r);await H.mkdir(i,{recursive:!0}),await z(fp(e,t,r),JSON.stringify(n)+`
|
|
114
|
+
`,r?.encryptSessions??!1)}async function hp(e,t,n){let r=await _(dp(e,t,n));if(r===null)return null;try{return JSON.parse(r)}catch{return null}}async function gp(e,t,n){let r=await _(fp(e,t,n));if(r===null)return[];let i=[];for(let e of r.split(`
|
|
115
|
+
`)){let t=e.trim();if(t)try{i.push(JSON.parse(t))}catch{}}return i}async function _p(e,t,n,r,i,a,o){let s=new Date().toISOString(),c={version:1,sessionId:t,request:n,status:`pending`,checkpoint:r,context:i,toolContext:a,createdAt:s,updatedAt:s};return await pp(e,t,c,o),await mp(e,t,{requestId:n.requestId,sessionId:t,action:`requested`,payload:n,timestamp:s},o),c}async function vp(e,t,n,r,i,a){let o=await hp(e,t,a);if(!o||o.request.requestId!==n||o.status!==`pending`)return null;let s=new Date().toISOString(),c={...o,status:r,resolution:i,updatedAt:s};await pp(e,t,c,a);let l={resolved:`resolved`,expired:`expired`,cancelled:`cancelled`}[r];return await mp(e,t,{requestId:n,sessionId:t,action:l,payload:i??o.request,timestamp:s},a),c}async function yp(e,t,n,r){let i=await hp(e,t,r);return!i||i.request.requestId!==n?null:i.status===`resolved`?i:null}async function bp(e,t,n){let r=dp(e,t,n);try{await H.unlink(r)}catch(e){if(e.code===`ENOENT`)return;throw e}}function xp(e,t,n){return U.join(l(e,t,n),`pending-ui-tool.json`)}async function Sp(e,t,n,r){let i=l(e,t,r);await H.mkdir(i,{recursive:!0}),await g(xp(e,t,r),JSON.stringify(n,null,2),r?.encryptSessions)}async function Cp(e,t,n){let r=await _(xp(e,t,n));return r===null?null:JSON.parse(r)}async function wp(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Sp(e,t,a,r),a}async function Tp(e,t,n,r,i){let a=await Cp(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 Sp(e,t,o,i),o}async function Ep(e,t,n){try{await H.unlink(xp(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}const Dp=`crons`;function Op(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:si(e.message)}}function Vn(e,t,n,r){let i={"Client-Code":`AIMax`,"X-Session-Id":t};return n&&(i[`X-Message-Id`]=n),r&&(i[`X-Channel`]=r),{id:e.model,name:e.model,api:`openai-completions`,provider:`openai`,baseUrl:e.baseUrl,reasoning:!1,input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:i,compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1,supportsUsageInStreaming:!0}}}function kp(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Se(t))}async function Ap(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=kr();if(i=await Ar(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Tr(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=jp(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 jp(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 Mp(e,t){oi(e.dataDir),Zo();let n=Date.now(),i=new pr(e),a=Hs(e);Y.info(`agent invocation prepared`,{requestedSessionId:a.requestedSessionId,previousSessionId:a.previousSessionId,inputMode:a.inputMode,hasSlashCommand:!!a.slashCommandSource,resetAction:a.resetCommand?.action,resetShortCircuit:a.resetShortCircuit,transcriptLength:a.transcriptMessage.length,messageForRunLength:a.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let o=a.transcriptMessage,s=!1,c=a.previousSessionId,l=await sp({runParams:e,requestedSessionId:a.requestedSessionId,eventDispatcher:i}),u=l.sessionId,d=l.isNewSession,f=l.workspaceDir,p=l.hookContext,m=l.hookRegistry,h=l.pluginContext,g=l.runContext,_=(await r(e.dataDir,u,{storeName:e.sessionStoreName})).length;Y.info(`agent run started`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:d,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:d,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),Y.info(d?`session created`:`session resumed`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}),await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:d?`session_created`:`session_resumed`,message:d?`session created`:`session resumed`,details:{requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}}),d&&await D(e.dataDir,lf({sessionId:u,title:ts(o),channel:e.channel}),Z(e)),a.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(s=await g.persistInitialUserEntry(o)),await l.start({resetCommand:a.resetCommand,previousSessionId:c,resetMessage:a.slashCommandSource,startMessage:typeof a.promptInput==`string`?a.promptInput:o});let v=new AbortController;e.abortSignal?.aborted?v.abort():e.abortSignal?.addEventListener(`abort`,()=>v.abort());let y=await nt(e.dataDir),b=[],x=at(y,{warn:e=>b.push(e)}),S=await ct();await i.dispatchDiagnostic(u,{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:u,bootstrapFileCount:y.length,contextFileCount:x.length,warningCount:b.length});let C=e.skillsLoadPaths??[],w=await mt(e.dataDir,h.pluginSkillDirs,C),T=await Jn({dataDir:e.dataDir,projectDir:e.projectDir,systemAgentsDir:e.systemAgentsDir,agentPolicy:e.agentPolicy}),E=T.stats(),O=e.agentPolicy?.activeAgent??T.findPublic(e.agentPolicy?.requestedAgentName);if(e.agentPolicy?.requestedAgentName&&!O)throw Error(`Unknown custom agent: ${e.agentPolicy.requestedAgentName}`);let k={...T,...O?{activeAgent:O}:{},...e.agentPolicy?.requestedAgentName?{requestedAgentName:e.agentPolicy.requestedAgentName}:{}},ee={...e,agentPolicy:k};await i.dispatchDiagnostic(u,{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:u,skillCount:w.length,pluginSkillDirCount:h.pluginSkillDirs.length,skillsLoadPathCount:C.length}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:k.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:u,agentCount:E.public,allAgentCount:E.total,internalAgentCount:E.internal,activeAgent:k.activeAgent?.name,requestedAgentName:k.requestedAgentName});let A=await Np({dataDir:e.dataDir,sessionId:u,eventDispatcher:i,enabled:e.autoSkills?.load?.enabled===!0}),j=e=>g.appendTranscriptEntry(e),M=await Ws({invocation:a,skills:w,sessionId:u,isNewSession:d,initialUserEntryPersisted:s,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i});if(M.kind===`completed`)return Y.info(`agent run short-circuited`,{sessionId:u,durationMs:Date.now()-n,hasError:!!M.result.error,paused:!!M.result.paused,uiToolPending:!!M.result.uiToolPending,textLength:M.result.text.length}),M.result;let N=M.effectivePrompt;o=M.transcriptMessage;let te=typeof N==`string`?N:o;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof N==`string`?`string`:`messages`,transcriptLength:o.length}}),Y.info(`invocation resolved`,{sessionId:u,promptType:typeof N==`string`?`string`:`messages`,transcriptLength:o.length});let P=await Qd({session:{runParams:ee,sessionId:u,hookRegistry:m,hookContext:p,runContext:g,eventDispatcher:i},runtimeInputs:{contextFiles:x,bootstrapWarnings:b,skills:w,autoSkillCategories:A,effectivePromptText:te,pluginTools:h.pluginTools,pluginSkillDirs:h.pluginSkillDirs,skillsLoadPaths:C,presetSystemPrompt:S.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>Mp(e,new Do),createModel:Vn,abortSignal:v.signal}}),F=P.agent,I=P.resolvedModelId;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:I,historyMessageCount:P.historyMessages.length,pluginToolCount:h.pluginTools.length}}),Y.info(`agent runtime created`,{sessionId:u,modelId:I,historyMessageCount:P.historyMessages.length,pluginToolCount:h.pluginTools.length}),v.signal.addEventListener(`abort`,()=>F.abort());let L=0,R=0,z=``,B,ne=!1;try{if(kp(e)){let t=await Ap({params:e,agent:F,sessionId:u,eventDispatcher:i,appendEntry:j,abortSignal:v.signal});return z=t.text,as({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i,text:z,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let e=await g.persistInitialUserEntry(o);ne=e,s=e||s}await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`}),Y.info(`first agent turn started`,{sessionId:u,modelId:I});let r=await ci({agent:F,message:N,continueFromHistory:!!e.uiToolResume,sessionId:u,modelId:I,historyMessages:P.historyMessages,eventDispatcher:i,hooks:m,hookCtx:p,abortSignal:v.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await j(e);for(let e of t)await j(e)}});z=r.text,L+=r.inputTokens,R+=r.outputTokens,r.error&&(B=r.error),await i.dispatchDiagnostic(u,{level:r.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!r.error,error:r.error,inputTokens:r.inputTokens,outputTokens:r.outputTokens}});let a={sessionId:u,hasError:!!r.error,error:r.error,inputTokens:r.inputTokens,outputTokens:r.outputTokens};r.error?Y.warn(`first agent turn completed with error`,a):Y.info(`first agent turn completed`,a),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),Y.info(`announce loop started`,{sessionId:u});let c=await nf({agent:F,registry:t,sessionId:u,resolvedModelId:I,eventDispatcher:i,hookRegistry:m,hookContext:p,abortSignal:v.signal,retry:e.llmRetry,appendEntry:j});c.text&&(z=c.text),L+=c.inputTokens,R+=c.outputTokens,c.error&&!B&&(B=c.error),await i.dispatchDiagnostic(u,{level:c.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens}});let l={sessionId:u,hasError:!!c.error,error:c.error,inputTokens:c.inputTokens,outputTokens:c.outputTokens};c.error?Y.warn(`announce loop completed with error`,l):Y.info(`announce loop completed`,l)}catch(t){if(Tr(t)){let r=t,a=e.subagentContext?.parentSessionId??u,s=a===r.request.sessionId?r.request:{...r.request,sessionId:a};await _p(e.dataDir,a,s,r.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},r.toolContext),await i.dispatchProgress(a,{type:`hitl_requested`,request:s}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),Y.info(`agent paused for HITL`,{sessionId:u,requestId:s.requestId,kind:s.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={input:L,output:R,total:L+R};return await Pp({runtime:P,resolvedModelId:I,usage:c,currentUserEntryCoveredByUsage:ne}),as({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i,text:z||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(Dr(t)){let r=t,a=r.request.outputSchema.properties??{};await wp(e.dataDir,u,r.request,Z(e)),await i.dispatchProgress(u,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(u,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${r.request.toolName}`,details:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(a).length}}),Y.info(`agent paused for UI tool input`,{sessionId:u,requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(a).length});let s={input:L,output:R,total:L+R};return await Pp({runtime:P,resolvedModelId:I,usage:s,currentUserEntryCoveredByUsage:ne}),as({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i,text:z||``,usage:s,error:void 0,uiToolPending:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchema:r.request.outputSchema,extra:r.request.extra}})}throw await up({dispatcher:i,sessionId:u,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:d}}),Y.error(`agent run failed`,{sessionId:u,channel:e.channel,isNewSession:d,error:t instanceof Error?t.message:String(t)}),t}finally{Ao(u),g.stop()}let V={input:L,output:R,total:L+R};await i.dispatchDiagnostic(u,{level:B?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!B,error:B}});let re={sessionId:u,durationMs:Date.now()-n,inputTokens:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!B,error:B};return B?Y.warn(`agent run completed with error`,re):Y.info(`agent run completed`,re),await Pp({runtime:P,resolvedModelId:I,usage:V,currentUserEntryCoveredByUsage:ne}),await ao({sessionId:u,runParams:ee,eventDispatcher:i,transcriptStartIndex:_,result:{text:z,usage:V,durationMs:Date.now()-n,error:B}}),as({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:m,hookContext:p,startTime:n,eventDispatcher:i,text:z,usage:V,error:B})}async function Np(e){if(!e.enabled)return[];try{let t=await new q({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 Pp(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 Fp(t){oi(t.dataDir);let n=Date.now(),r=new pr(t),i=Hs(t),a=i.transcriptMessage.trim()||`CRON task`,o=t.sessionStoreName;Y.info(`cron run started`,{requestedSessionId:i.requestedSessionId,channel:t.channel,sessionStoreName:o,...Op(t)});let c=i.requestedSessionId,l=!c;c?(await u(t.dataDir,c,{storeName:o})||(l=!0),await F(t.dataDir,c,{storeName:o})):c=await w(t.dataDir,t.channel,{storeName:o}),l&&await D(t.dataDir,lf({sessionId:c,title:ts(a),channel:t.channel}),{storeName:o});let d=await w(t.dataDir,t.channel,{storeName:Dp});await r.dispatchProgress(c,{type:`subagent_spawn`,childSessionId:d,task:a}),Y.info(`cron child subagent spawned`,{parentSessionId:c,childSessionId:d,taskLength:a.length,taskPreview:si(a)});let f={...t,sessionId:d,sessionStoreName:Dp,subagentContext:{depth:1,parentSessionId:c}},m,h=`done`;try{m=await Mp(f,new Do),m.error&&(h=`error`)}catch(e){let r=e instanceof Error?e.message:String(e);m={sessionId:d,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-n,error:r,context:{snapshotPath:T(t.dataDir,d,{storeName:Dp}),toolResultsDir:s(t.dataDir,d,{storeName:Dp})}},h=`error`,Y.error(`cron child run failed`,{parentSessionId:c,childSessionId:d,error:r})}await r.dispatchProgress(c,{type:`subagent_complete`,childSessionId:d,task:a,status:h}),Y.info(`cron child subagent completed`,{parentSessionId:c,childSessionId:d,status:h,durationMs:Date.now()-n,hasError:!!m.error});let g=Hu({task:a,status:h,result:m.text,error:m.error}),_=new Date().toISOString();await C(t.dataDir,c,{role:`assistant`,content:g,timestamp:_,source:`cron`},{storeName:o});let v={task:a,status:h,content:g,childSessionId:d,createdAt:_};return await S(t.dataDir,c,v,{storeName:o}),await e(t.dataDir,c,e=>Ip(e,8),{storeName:o}),await p(t.dataDir,c,{},{storeName:o}),{...m,sessionId:c,context:{snapshotPath:T(t.dataDir,c,{storeName:o}),toolResultsDir:s(t.dataDir,c,{storeName:o})}}}function Ip(e,t){if(t<=0)return e.filter(e=>!Lp(e));let n=e.reduce((e,t,n)=>(Lp(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Lp(e)||r.has(t))}function Lp(e){return`source`in e&&e.source===`cron`}async function Rp(e,t){if(oi(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,...Op(e)}),e.channel===`CRON`&&!e.subagentContext)return Fp(e);let n=t??new Do;try{return await Mp(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:lp(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}}const zp={"AGENTS.md":`---
|
|
116
116
|
title: "AGENTS.md Template"
|
|
117
117
|
summary: ".aimax template for AGENTS.md"
|
|
118
118
|
read_when:
|
|
@@ -405,7 +405,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
|
|
|
405
405
|
This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
|
|
406
406
|
|
|
407
407
|
Add whatever helps you do your job. This is your cheat sheet.
|
|
408
|
-
`},
|
|
408
|
+
`},Bp=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Vp(e,t){try{if(!(await H.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 H.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Hp(e,t,n){try{if(!(await H.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 H.mkdir(U.dirname(e),{recursive:!0});try{await H.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 Up(e){let t=tt(e);return[e,t,U.join(t,`skills`),U.join(t,`sessions`),U.join(t,`memory`),U.join(e,`workspace`)]}function Wp(e){let t=tt(e);return[...Bp.filter(e=>e!==`BOOTSTRAP.md`).map(e=>U.join(t,e)),U.join(t,`MEMORY.md`)]}function Gp(e){return U.join(tt(e),`.bootstrapped`)}async function Kp(e){try{return(await H.stat(Gp(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function qp(e){let t=Gp(e);await H.mkdir(U.dirname(t),{recursive:!0}),await H.writeFile(t,``,{encoding:`utf-8`})}async function Jp(e){let t=[],n=[];for(let n of Up(e))try{(await H.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Wp(e))try{(await H.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 Yp(e){return(await Jp(e)).ready}async function Xp(e){if(await Kp(e))return{ready:!0,performedBootstrap:!1};if((await Jp(e)).ready)return await qp(e),{ready:!0,performedBootstrap:!1};let t=await Zp(e);return await qp(e),{ready:!0,performedBootstrap:!0,result:t}}async function Zp(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=tt(e),r=U.join(e,`workspace`),i=U.join(n,`skills`),a=U.join(n,`sessions`),o=U.join(n,`memory`);await Vp(e,t),await Vp(n,t),await Vp(i,t),await Vp(a,t),await Vp(o,t),await Vp(r,t);for(let e of Bp){let r=zp[e]??``;await Hp(U.join(n,e),r,t)}return await Hp(U.join(n,`MEMORY.md`),``,t),t}async function Qp(e){let t=U.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await H.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 $p(e,t){let n=U.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 H.mkdir(U.dirname(n),{recursive:!0}),await H.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function em(e,t){let n=await Qp(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 tm(e,t=7){let n=await Qp(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 $p(e,n),i}async function nm(e,t,n,r){let i=await hp(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?xe(i.request)?(await vp(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 rm(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await yp(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 nm(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await vp(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 im={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 am(e){return e.action===`timeout`?im.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?im.approval.summary.approved:im.approval.summary.denied}function om(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:am(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function sm(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 cm(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 lm(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
|
|
409
409
|
`)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
|
|
410
410
|
`)):(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(`
|
|
411
|
-
`))}export{
|
|
411
|
+
`))}export{q as AutoSkillsLoader,et as BOOTSTRAP_FILE_NAMES,Qe as BOOTSTRAP_MAX_CHARS,$e as BOOTSTRAP_TOTAL_MAX_CHARS,x as DEFAULT_SESSION_STORE_NAME,im as HITL_MESSAGES,wr as HitlPauseSignal,k as MAX_ARTIFACT_CONTENT_CHARS,Eo as MAX_CHILDREN_PER_SESSION,To as MAX_SUBAGENT_DEPTH,N as MemoryIndexManager,Kf as PLUGIN_MANIFEST_FILENAME,qf as PLUGIN_MANIFEST_FILENAMES,fr as PluginHookRegistry,Dd as PluginToolRegistry,Hn as SYSTEM_AGENTS_DIR,Do as SubagentRegistry,Er as UiToolPauseSignal,_e as addAgent,pe as addBinding,Wn as agentDirCandidates,Qn as agentVisibility,tt as aimaxDir,P as appendArtifactOperation,S as appendCronExecutionRecord,Wl as appendRecentToMemory,z as appendSessionFile,Ul as appendToMemory,C as appendTranscriptEntry,am as approvalSummaryFromResolution,M as artifactsPath,t as atomicWriteSessionFile,nn as autoSkillsDir,Zp as bootstrapMountLayout,nr as buildAgentDelegationPrompt,rr as buildAgentTaskPrompt,at as buildBootstrapContextFiles,lm as buildResumeNarration,yt as buildSkillsPrompt,Hu as buildSubagentAnnounceMessage,Td as buildSystemPrompt,tm as cleanupOldSubagentRecords,bp as clearPendingHitl,Ep as clearPendingUiTool,ee as collapseLogPath,T as contextSnapshotPath,Kn as createAgentDefinitionsContext,td as createAgentTools,Cl as createApplyPatchTool,na as createAutoSkillCategoriesTool,ra as createAutoSkillListTool,ia as createAutoSkillSearchTool,aa as createAutoSkillViewTool,bn as createAutoSkillsLoader,il as createBashTool,Ku as createBatchSubagentSpawnTool,A as createBuiltinMemoryProvider,jc as createContextManager,ml as createEditFileTool,Hc as createExecTool,Qu as createImageTool,gl as createListDirTool,Ql as createMemoryAppendTool,fu as createMemoryForgetTool,Xl as createMemoryGetTool,uu as createMemoryListTool,cu as createMemoryLogTool,Jl as createMemorySearchTool,mu as createMemoryUpdateTool,eu as createMemoryWriteTool,_p as createPendingHitl,wp as createPendingUiTool,dr as createPluginProgressEmitter,$f as createPluginRuntime,Kc as createProcessTool,ul as createReadFileTool,w as createSession,ic as createSessionContextStore,gu as createSessionSearchTool,Lu as createSkillListTool,Ru as createSkillLoadTool,Gu as createSubagentSpawnTool,Xu as createSubagentsTool,ed as createUiTool,fl as createWriteFileTool,v as cronExecutionsPath,$u as defaultUiToolInputSchema,Kl as deleteMemoryFile,Wf as discoverAIMaxPlugins,Xp as ensureBootstrapMountLayout,F as ensureSession,R as exportSession,er as filterSkillsForAgent,tr as filterToolsForAgent,Zn as findAgentDefinition,gt as findSkillByName,om as formatApprovalResolution,sm as formatClarifyResolution,cm as formatReviewResolution,$o as generateSessionTitle,ue as getAgentConfig,Hl as getMemoryLines,Kp as hasBootstrapSentinel,fp as hitlHistoryPath,ap as initializePluginSystem,Jp as inspectBootstrapMountLayout,b as inspectSession,Yp as isBootstrapMountLayoutReady,Tr as isHitlPauseSignal,Dr as isUiToolPauseSignal,ie as listAgents,us as listAvailableSlashCommands,me as listBindings,Rl as listMemoryFiles,L as listSessionSummaries,m as listSessions,em as listSubagentRunsFromDisk,Yn as loadAgentDefinitionsFromDir,ge as loadAgentsConfig,n as loadArtifactOperations,nt as loadBootstrapFiles,I as loadCronExecutionRecords,hp as loadPendingHitl,hp as readPendingHitl,Cp as loadPendingUiTool,Cp as readPendingUiTool,Yf as loadPluginManifest,Xf as loadPluginManifestRegistry,np as loadPlugins,h as loadSessionContextSnapshot,i as loadSessionMetadata,vt as loadSkillView,pt as loadSkills,ht as loadSkillsFromDirs,mt as loadSkillsWithPluginDirs,Qp as loadSubagentRegistryFromDisk,r as loadTranscript,Fl as memoryDir,d as metadataPath,ae as normalizeAgentId,bf as normalizePluginsConfig,O as normalizeSessionStoreName,Xn as parseAgentDefinition,dp as pendingHitlPath,xp as pendingUiToolPath,Il as primaryMemoryPath,$n as publicAgentDefinitions,gp as readHitlHistory,zl as readMemoryFile,Bl as readPrimaryMemory,_ as readSessionFile,o as readSessionFileContent,E as registerEmbeddingProvider,ne as registerMemoryProvider,de as removeAgent,ve as removeBindings,Gl as replaceMemoryFile,y as resetEmbeddingProviderRegistryForTests,V as resetMemoryProviderRegistryForTests,Jn as resolveAgentDefinitionsContext,oe as resolveAgentDir,se as resolveAgentIdByBinding,he as resolveAgentsConfigPath,fe as resolveDefaultAgentId,j as resolveEmbeddingProvider,rm as resolveHitlRequest,rm as resolvePendingHitl,B as resolveMemoryProvider,le as resolveModelFallbacks,ce as resolveModelString,Tp as resolvePendingUiTool,Jf as resolvePluginManifestPath,e as rewriteTranscript,Rp as runAgent,re as saveAgentsConfig,D as saveSessionMetadata,$p as saveSubagentRegistryToDisk,Gn as scanAgentDefinitions,Vl as searchMemory,l as sessionDir,f as sessionMemoryPath,a as sessionsDir,lt as skillsDir,s as toolResultsDir,c as transcriptPath,vp as transitionHitlStatus,ye as updateAgentIdentity,p as updateSessionMetadata,xf as validatePluginsConfig,nm as validateResume,kd as wrapToolsWithHooks,g as writeSessionFile};
|