@gencode/agents 0.17.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,R as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,j as C,k as w,l as T,m as E,n as D,o as O,p as k,r as A,s as j,t as M,u as N,v as P,w as ee,x as F,y as I,z as L}from"./session-BpKaF-Gk.js";import{n as R,t as te}from"./goal-events-CocRykqc.js";import{c as z,i as B,l as V,n as ne,o as re,r as ie,s as H,t as ae,u as U}from"./goal-store-M3_Nx3ky.js";import{A as oe,C as se,D as W,E as ce,F as le,I as ue,M as de,N as fe,O as pe,P as me,S as he,T as ge,_ as _e,a as ve,b as ye,c as be,d as xe,f as Se,g as Ce,h as we,i as Te,j as Ee,k as De,l as Oe,m as ke,n as Ae,o as je,p as Me,r as Ne,s as Pe,t as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./system-runtime-BwN5oJYF.js";import{a as Ve,c as He,i as Ue,l as We,o as Ge,r as Ke,s as qe,t as Je,u as Ye}from"./default-provider-BV9gmV00.js";import{a as Xe,i as Ze,n as Qe,o as $e,r as et,t as tt}from"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";import{t as nt}from"./host-BC9sAhdH.js";import{a as rt,i as it,l as at,n as ot,o as st,r as ct,s as lt,t as ut}from"./session-store-BwYOp-2K.js";import{_ as dt,a as ft,c as pt,d as mt,f as ht,g as gt,h as _t,i as vt,l as yt,m as bt,n as xt,o as St,p as Ct,s as wt,t as Tt,u as Et,v as Dt,y as Ot}from"./config-DDlWxQf7.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as kt,formatTaskForDisplay as At,isHitlExpired as jt,isHitlTool as Mt}from"@gencode/shared";import G,{readFile as Nt}from"node:fs/promises";import K,{join as Pt}from"node:path";import{createHash as Ft,randomBytes as It,randomUUID as Lt}from"node:crypto";import Rt from"node:os";import{spawn as zt}from"node:child_process";import{TextDecoder as Bt}from"node:util";import Vt from"gray-matter";import{Agent as Ht}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as Ut}from"node:async_hooks";import Wt from"node:fs";import Gt from"openai";import{Type as q,calculateCost as Kt,clampThinkingLevel as qt,createAssistantMessageEventStream as Jt,getEnvApiKey as Yt,parseStreamingJson as Xt,registerApiProvider as Zt,registerBuiltInApiProviders as Qt,streamSimple as $t}from"@earendil-works/pi-ai";import{fileURLToPath as en}from"node:url";import{isBinaryFile as tn}from"isbinaryfile";import{parse as nn}from"yaml";import rn from"ajv";var an=class{turn=null;wallClock={activeGoalId:null,lastAccountedAt:Date.now()};resetWallClock(){this.wallClock.lastAccountedAt=Date.now()}markActiveGoal(e,t,n){e&&(this.turn&&this.turn.turnId===e?(this.turn.activeGoalId=t,this.turn.lastTokenUsage=n):this.turn={turnId:e,activeGoalId:t,lastTokenUsage:n}),this.wallClock.activeGoalId!==t&&this.resetWallClock(),this.wallClock.activeGoalId=t}clearActiveGoal(){this.turn&&(this.turn.activeGoalId=null),this.wallClock.activeGoalId=null,this.resetWallClock()}tokenDeltaSinceLastAccounting(e){if(!this.turn||!this.turn.activeGoalId)return 0;let t=this.turn.lastTokenUsage;return Math.max(0,e.input-t.input)+Math.max(0,e.output-t.output)}timeDeltaSecondsSinceLastAccounting(){if(!this.wallClock.activeGoalId)return 0;let e=Date.now()-this.wallClock.lastAccountedAt;return Math.floor(e/1e3)}markAccounted(e,t){this.turn&&(this.turn.lastTokenUsage=e),t>0&&(this.wallClock.lastAccountedAt+=t*1e3),this.wallClock.lastAccountedAt>Date.now()&&(this.wallClock.lastAccountedAt=Date.now())}};async function on(e,t,n,r,i){let a=await H(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await V(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const sn=`clarify plan and acceptance`,cn=`补齐后续 task list、每个 task 的验收项和当前下一步`,ln={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},un=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function dn(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function fn(e,t){let n=dn(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function pn(e){let t=e.split(/\r?\n/),n=[];for(let e of t){let t=e.trim();if(!t)continue;let r=t.match(/^(?:[-*•]|\d+[.)])\s+(.+)$/);if(r?.[1]){n.push(r[1].trim());continue}t.length>=8&&n.push(t)}return n.filter(e=>e.length>=4)}function mn(e){let t={raw:e.trim()},n=/(?:^|\n)\s*(?:【([^】]+)】|(?:#{1,3}\s*)?([A-Za-z\u4e00-\u9fff][^:\n]{0,30}))\s*[::]\s*/g,r=[],i;for(;(i=n.exec(e))!==null;){let e=(i[1]??i[2]??``).trim();e&&r.push({label:e,start:i.index,contentStart:i.index+i[0].length})}for(let n=0;n<r.length;n+=1){let i=r[n],a=r[n+1],o=e.slice(i.contentStart,a?.start??e.length).trim();for(let[e,n]of Object.entries(ln))fn(i.label,n)&&(t[e]=t[e]?`${t[e]}\n${o}`:o)}return{goal:t.goal?.trim()||e.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>=8)||e.trim(),scope:t.scope?.trim()??``,steps:t.steps?pn(t.steps):[],acceptance:t.acceptance?pn(t.acceptance):[],raw:e.trim()}}function hn(e){let t=e.toLowerCase();return un.some(e=>t.includes(e.toLowerCase()))}function gn(e){return e.some(hn)}function _n(e,t){return{id:e,text:t,required:!0}}function vn(e){return{id:e.id,kind:e.kind,title:e.title,required:!0,status:e.status,acceptanceCriteria:e.acceptanceCriteria,acceptanceEvidence:[],evidenceRefs:[],blockedReason:null,updatedAt:e.updatedAt}}function yn(e){return vn({id:`task-1`,kind:`clarify`,title:sn,status:`doing`,acceptanceCriteria:[_n(`ac-1`,cn)],updatedAt:e})}function bn(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>_n(`ac-${t+1}`,e)):[_n(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>vn({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[_n(`ac-1`,`完成:${e}`)],updatedAt:n}))}function xn(e){let t=new Date().toISOString(),n=mn(e),r=n.goal||n.raw,i=n.scope?[n.scope]:[],a=[];if(n.steps.length>=2)return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&gn(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&gn(pn(n.raw))){let e=pn(n.raw).filter(hn);return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[yn(t)]}}function Sn(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function Cn(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>Sn(n.has(e.id),e)),``].join(`
1
+ import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P as u,R as d,S as f,T as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,j as C,k as w,l as T,m as E,n as D,o as O,p as k,r as A,s as j,t as M,u as N,v as P,w as ee,x as F,y as I,z as L}from"./session-RhwZxWME.js";import{n as R,t as te}from"./goal-events-B5anors9.js";import{c as z,i as B,l as V,n as ne,o as re,r as ie,s as H,t as ae,u as U}from"./goal-store-CGUkaQtk.js";import{A as oe,C as se,D as W,E as ce,F as le,I as ue,M as de,N as fe,O as pe,P as me,S as he,T as ge,_ as _e,a as ve,b as ye,c as be,d as xe,f as Se,g as Ce,h as we,i as Te,j as Ee,k as De,l as Oe,m as ke,n as Ae,o as je,p as Me,r as Ne,s as Pe,t as Fe,u as Ie,v as Le,w as Re,x as ze,y as Be}from"./system-runtime-BwN5oJYF.js";import{a as Ve,c as He,i as Ue,l as We,o as Ge,r as Ke,s as qe,t as Je,u as Ye}from"./default-provider-DeT3IzGN.js";import{a as Xe,i as Ze,n as Qe,o as $e,r as et,t as tt}from"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";import{t as nt}from"./host-BC9sAhdH.js";import{a as rt,i as it,l as at,n as ot,o as st,r as ct,s as lt,t as ut}from"./session-store-Bj0MvQOw.js";import{_ as dt,a as ft,c as pt,d as mt,f as ht,g as gt,h as _t,i as vt,l as yt,m as bt,n as xt,o as St,p as Ct,s as wt,t as Tt,u as Et,v as Dt,y as Ot}from"./config-DDlWxQf7.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as kt,formatTaskForDisplay as At,isHitlExpired as jt,isHitlTool as Mt}from"@gencode/shared";import G,{readFile as Nt}from"node:fs/promises";import K,{join as Pt}from"node:path";import{createHash as Ft,randomBytes as It,randomUUID as Lt}from"node:crypto";import Rt from"node:os";import{spawn as zt}from"node:child_process";import{TextDecoder as Bt}from"node:util";import Vt from"gray-matter";import{Agent as Ht}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as Ut}from"node:async_hooks";import Wt from"node:fs";import Gt from"openai";import{Type as q,calculateCost as Kt,clampThinkingLevel as qt,createAssistantMessageEventStream as Jt,getEnvApiKey as Yt,parseStreamingJson as Xt,registerApiProvider as Zt,registerBuiltInApiProviders as Qt,streamSimple as $t}from"@earendil-works/pi-ai";import{fileURLToPath as en}from"node:url";import{isBinaryFile as tn}from"isbinaryfile";import{parse as nn}from"yaml";import rn from"ajv";var an=class{turn=null;wallClock={activeGoalId:null,lastAccountedAt:Date.now()};resetWallClock(){this.wallClock.lastAccountedAt=Date.now()}markActiveGoal(e,t,n){e&&(this.turn&&this.turn.turnId===e?(this.turn.activeGoalId=t,this.turn.lastTokenUsage=n):this.turn={turnId:e,activeGoalId:t,lastTokenUsage:n}),this.wallClock.activeGoalId!==t&&this.resetWallClock(),this.wallClock.activeGoalId=t}clearActiveGoal(){this.turn&&(this.turn.activeGoalId=null),this.wallClock.activeGoalId=null,this.resetWallClock()}tokenDeltaSinceLastAccounting(e){if(!this.turn||!this.turn.activeGoalId)return 0;let t=this.turn.lastTokenUsage;return Math.max(0,e.input-t.input)+Math.max(0,e.output-t.output)}timeDeltaSecondsSinceLastAccounting(){if(!this.wallClock.activeGoalId)return 0;let e=Date.now()-this.wallClock.lastAccountedAt;return Math.floor(e/1e3)}markAccounted(e,t){this.turn&&(this.turn.lastTokenUsage=e),t>0&&(this.wallClock.lastAccountedAt+=t*1e3),this.wallClock.lastAccountedAt>Date.now()&&(this.wallClock.lastAccountedAt=Date.now())}};async function on(e,t,n,r,i){let a=await H(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await V(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const sn=`clarify plan and acceptance`,cn=`补齐后续 task list、每个 task 的验收项和当前下一步`,ln={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},un=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function dn(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function fn(e,t){let n=dn(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function pn(e){let t=e.split(/\r?\n/),n=[];for(let e of t){let t=e.trim();if(!t)continue;let r=t.match(/^(?:[-*•]|\d+[.)])\s+(.+)$/);if(r?.[1]){n.push(r[1].trim());continue}t.length>=8&&n.push(t)}return n.filter(e=>e.length>=4)}function mn(e){let t={raw:e.trim()},n=/(?:^|\n)\s*(?:【([^】]+)】|(?:#{1,3}\s*)?([A-Za-z\u4e00-\u9fff][^:\n]{0,30}))\s*[::]\s*/g,r=[],i;for(;(i=n.exec(e))!==null;){let e=(i[1]??i[2]??``).trim();e&&r.push({label:e,start:i.index,contentStart:i.index+i[0].length})}for(let n=0;n<r.length;n+=1){let i=r[n],a=r[n+1],o=e.slice(i.contentStart,a?.start??e.length).trim();for(let[e,n]of Object.entries(ln))fn(i.label,n)&&(t[e]=t[e]?`${t[e]}\n${o}`:o)}return{goal:t.goal?.trim()||e.split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>=8)||e.trim(),scope:t.scope?.trim()??``,steps:t.steps?pn(t.steps):[],acceptance:t.acceptance?pn(t.acceptance):[],raw:e.trim()}}function hn(e){let t=e.toLowerCase();return un.some(e=>t.includes(e.toLowerCase()))}function gn(e){return e.some(hn)}function _n(e,t){return{id:e,text:t,required:!0}}function vn(e){return{id:e.id,kind:e.kind,title:e.title,required:!0,status:e.status,acceptanceCriteria:e.acceptanceCriteria,acceptanceEvidence:[],evidenceRefs:[],blockedReason:null,updatedAt:e.updatedAt}}function yn(e){return vn({id:`task-1`,kind:`clarify`,title:sn,status:`doing`,acceptanceCriteria:[_n(`ac-1`,cn)],updatedAt:e})}function bn(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>_n(`ac-${t+1}`,e)):[_n(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>vn({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[_n(`ac-1`,`完成:${e}`)],updatedAt:n}))}function xn(e){let t=new Date().toISOString(),n=mn(e),r=n.goal||n.raw,i=n.scope?[n.scope]:[],a=[];if(n.steps.length>=2)return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&gn(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&gn(pn(n.raw))){let e=pn(n.raw).filter(hn);return{interpretation:r,assumptions:i,openQuestions:a,tasks:bn([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[yn(t)]}}function Sn(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function Cn(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>Sn(n.has(e.id),e)),``].join(`
2
2
  `)}function wn(e,t){let n=e.tasks.find(t=>t.id===e.currentTaskId),r=t?.interpretation?.trim()||e.objective,i=t?.assumptions??[],a=t?.openQuestions??[],o=t?.progressLog??[`${new Date(e.updatedAt).toISOString().slice(0,16).replace(`T`,` `)}: 创建目标并生成初始任务。`],s=t?.evidence?.length?t.evidence:e.finalEvidenceRefs.length>0?e.finalEvidenceRefs:[],c=t?.risks??(e.blockedReason?[e.blockedReason]:[]),l=[`# Goal Plan`,``,`## Objective`,``,e.objective,``,`## Interpretation`,``,r,``,`## Assumptions`,``,...i.length>0?i.map(e=>`- ${e}`):[`- 暂无`],``];return t?.taskPlanNotes?.trim()&&l.push(`## Task Plan Notes`,``,t.taskPlanNotes.trim(),``),l.push(`## Current Focus`,``,`- Current task: ${e.currentTaskId??`none`}`,`- Status: ${e.status}`,`- Next step: ${n?.title??`无当前任务`}`,...e.blockedReason?[`- Blocked: ${e.blockedReason}`]:[],``,`## Task List`,``,...e.tasks.flatMap(e=>{let n=new Set,r=t?.criterionEvidence?.[e.id];if(r)for(let t of e.acceptanceCriteria)r.includes(t.id)&&n.add(t.id);else if(e.status===`done`)for(let t of e.acceptanceCriteria)n.add(t.id);return[Cn(e,n)]}),`## Progress Log`,``,...o.map(e=>`- ${e}`),``,`## Open Questions`,``,...a.length>0?a.map(e=>`- ${e}`):[`- 暂无`],``,`## Evidence`,``,...s.length>0?s.map(e=>`- ${e}`):[`- 暂无`],``,`## Risks`,``,...c.length>0?c.map(e=>`- ${e}`):[`- 暂无`],``),t?.finalSummary?.trim()&&l.push(`## Final Summary`,``,t.finalSummary.trim(),``),l.join(`
3
3
  `)}const Tn=process.platform===`win32`;function En(e){return Tn?{shell:!0,file:process.env.ComSpec||process.env.COMSPEC||`cmd.exe`,args:[`/d`,`/s`,`/c`,`chcp 65001>nul & ${e}`]}:{file:`bash`,args:[`-lc`,e],shell:void 0}}function Dn(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(Tn&&typeof e.pid==`number`){let n=[`/pid`,String(e.pid),`/T`];t===`SIGKILL`&&n.push(`/F`);try{zt(`taskkill`,n,{windowsHide:!0,stdio:`ignore`})}catch{try{e.kill()}catch{}}return}try{if(typeof e.pid==`number`){process.kill(-e.pid,t);return}e.kill(t)}catch{try{e.kill(t)}catch{}}}}const On=2e5;function kn(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function An(e,t){let n=e+t;return n.length<=On?{text:n,truncated:!1}:{text:n.slice(-On),truncated:!0}}function jn(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=An(e.output,r);e.output=i.text;let a=An(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Mn(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:kn(e.output),stdoutTail:kn(e.stdout),stderrTail:kn(e.stderr),outputTruncated:e.outputTruncated}}function Nn(e,t){return t?e.scopeKey===t:!0}function Pn(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function Fn(e){return e?e.split(/\r?\n/):[]}function In(e){let t=Fn(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Pn(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(`
4
4
  `);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 Ln(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Rn(){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),Ln(e))};return{start(t){let{file:n,args:r,shell:a}=En(t.command),o=zt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!Tn}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:Lt(),scopeKey:t.scopeKey,command:t.command,cwd:t.cwd,startedAt:Date.now(),child:o,status:`running`,output:``,stdout:``,stderr:``,outputTruncated:!1,donePromise:c,resolveDone:s};e.set(l.sessionId,l),o.stdout.on(`data`,e=>jn(l,`stdout`,e)),o.stderr.on(`data`,e=>jn(l,`stderr`,e));let u=e=>t=>{jn(l,`stderr`,Buffer.from(`\n[${e} stream error: ${t.message}]\n`))};o.stdout.on(`error`,u(`stdout`)),o.stderr.on(`error`,u(`stderr`)),o.stdin.on(`error`,u(`stdin`));try{o.stdin.end()}catch{}let d=Pn(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,jn(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Dn(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Dn(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),jn(l,`stderr`,Buffer.from(`\n[Process error: ${e.message}]\n`))})}),o.on(`close`,(e,t)=>{i(l,()=>{l.exitCode=e,l.exitSignal=t,l.status===`running`?l.status=e===0?`completed`:`failed`:l.status===`killed`&&e===0&&(l.status=`completed`)})}),Mn(l)},get(e,t){let n=r(e);return!n||!Nn(n,t)?null:Mn(n)},list(n){return[...e.values(),...t.values()].filter(e=>Nn(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Mn(e))},async wait(e,t,n){let i=r(e);if(!i||!Nn(i,t))return null;if(i.status!==`running`)return Mn(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||!Nn(a,t)?null:Mn(a)},readLog(e){let t=r(e.sessionId);return!t||!Nn(t,e.scopeKey)?null:In({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Nn(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||!Nn(n,t))return null;if(n.status!==`running`)return Mn(n);n.status=`killed`,Dn(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Dn(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?Mn(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Dn(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Dn(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const zn=1;var Bn=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},Vn=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},Hn=class extends Error{rawContentPreview;constructor(e,t){super(e),this.name=`CorruptGoalWorkflowStateError`,t?.cause!==void 0&&(this.cause=t.cause),this.rawContentPreview=t?.rawContentPreview}};const Un=new Map;function Wn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function Gn(e,t,n,r){let i=Wn(e,t,n),a=Un.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});Un.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function Kn(e,t,n){return K.join(ne(e,t,n),`state.json`)}function qn(e,t,n){return K.join(ne(e,t,n),`plan.md`)}function Jn(e,t,n){return K.join(ne(e,t,n),`artifacts`)}async function Yn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${It(4).toString(`hex`)}.tmp`;try{await G.writeFile(n,t,`utf-8`),await G.rename(n,e)}finally{await G.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function Xn(e){if(e.version!==1)throw new Bn(e.version)}function Zn(e){let t=e.currentTaskId?e.tasks.find(t=>t.id===e.currentTaskId)??null:null,n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`done`).length,i=n.filter(e=>e.status!==`done`).length;return{workflowStatus:e.status,currentTaskId:e.currentTaskId,currentTaskTitle:t?.title??null,currentTaskStatus:t?.status??null,blockedReason:e.blockedReason,openRequiredTasks:i,doneRequiredTasks:r,finalEvidenceRefs:[...e.finalEvidenceRefs]}}async function Qn(e,t,n){let r=Kn(e,t,n);try{let e=await G.readFile(r,`utf-8`);try{let t=JSON.parse(e);return Xn(t),t}catch(t){throw t instanceof Bn?t:new Hn(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof Hn||e instanceof Bn?e:new Hn(`corrupt_goal_workflow_state`,{cause:e})}}async function $n(e,t,n){let r=Kn(e,t,n),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return Xn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof Bn)throw e}let a=await H(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await z(e,t,a,n)).trim();if(!o)throw Error(`repairGoalWorkflowState requires a non-empty objective`);let s=`${r}.corrupt.${new Date().toISOString().replace(/[:.]/g,`-`)}.bak`,c=null;try{await G.writeFile(s,i,`utf-8`),c=s}catch{}return await rr(e,t,{goalId:a.goalId,objective:o},n),await vr(e,t,{type:`goal_workflow_repaired`,goalId:a.goalId,mode:`reinitialized`,backupPath:c},n),{ok:!0,mode:`reinitialized`,goalId:a.goalId,backedUpState:c}}async function er(e,t,n){let r=await Qn(e,t,n);return r?Zn(r):null}async function tr(e,t,n){let r=await Qn(e,t,n);return r?{goalState:Zn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function nr(e,t,n){let r=Kn(e,t,n),i=qn(e,t,n),a=Jn(e,t,n);await Promise.all([G.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),G.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),G.rm(a,{recursive:!0,force:!0})])}async function rr(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await nr(e,t,r);let a=xn(i),o=new Date().toISOString(),s=a.tasks.find(e=>e.status===`doing`)?.id??a.tasks[0]?.id??null,c={version:1,goalId:n.goalId,status:`active`,objective:i,currentTaskId:s,tasks:a.tasks,blockedReason:null,finalEvidenceRefs:[],completedAt:null,updatedAt:o},l=ne(e,t,r);await G.mkdir(l,{recursive:!0}),await Yn(Kn(e,t,r),JSON.stringify(c,null,2));let u=wn(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await Yn(qn(e,t,r),u),c}const ir=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g];function ar(e,t,n){return K.join(Jn(e,t,n),`registry.jsonl`)}function or(e,t,n){return K.join(Jn(e,t,n),`notes`)}function sr(e,t,n){return K.join(ne(e,t,n),`plan-meta.json`)}function cr(e){let t=e,n=!1;for(let e of ir)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function lr(e){return`${e}-${Date.now().toString(36)}-${It(3).toString(`hex`)}`}async function ur(e,t,n,r){let i=await dr(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${lr(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function dr(e,t,n){let r=ar(e,t,n);try{let e=await G.readFile(r,`utf-8`),t=[],n=e.split(/\r?\n/).map((e,t)=>({line:e,index:t})).filter(e=>e.line.trim().length>0);for(let[e,r]of n.entries())try{t.push(JSON.parse(r.line))}catch{if(e===n.length-1)continue;throw new Vn(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function fr(e,t,n,r){let i=ar(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0}),await G.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function pr(e,t,n,r){Xn(n),await Yn(Kn(e,t,r),JSON.stringify(n,null,2))}async function mr(e,t,n){let r=sr(e,t,n);try{let e=await G.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function hr(e,t,n,r){await Yn(sr(e,t,r),JSON.stringify(n,null,2))}async function gr(e,t,n,r){let i=await mr(e,t,r),a={...i,...n,assumptions:n.assumptions??i.assumptions,openQuestions:n.openQuestions??i.openQuestions,progressLog:n.progressLog??i.progressLog,evidence:n.evidence??i.evidence,risks:n.risks??i.risks,criterionEvidence:{...i.criterionEvidence,...n.criterionEvidence}};return await hr(e,t,a,r),a}async function _r(e,t,n,r){try{let i=wn(n,await mr(e,t,r));return await Yn(qn(e,t,r),i),{ok:!0}}catch(e){return{ok:!1,warning:`plan_update_failed`,message:e instanceof Error?e.message:String(e)}}}async function vr(e,t,n,r){let{type:i,...a}=n,o={timestamp:new Date().toISOString(),sessionId:t,goalId:n.goalId??null,action:i,detail:a},s=R(e,t,r);await G.mkdir(K.dirname(s),{recursive:!0}),await G.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}async function yr(e,t,n,r){if(n.kind===`manual`&&!n.source?.trim())return{error:`manual evidence requires source`};if(Buffer.byteLength(n.content,`utf-8`)>65536)return{error:`note_content_too_large`};let i=await ur(e,t,n.kind,r),a=i.split(`:`)[1]??lr(n.kind),o=or(e,t,r);await G.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=K.join(or(e,t,r),`${a}.md`),l=cr(n.content);await G.writeFile(c,l.text,`utf-8`);let u={id:i,kind:n.kind,summary:n.summary,source:n.source??`model`,createdAt:new Date().toISOString(),notePath:s,contentBytes:Buffer.byteLength(l.text,`utf-8`),redactionIncomplete:l.redactionIncomplete};try{await fr(e,t,u,r)}catch{return await G.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}function br(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function xr(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${br(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${br(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${br(e.taskBlockedReason)}`),e.acceptanceCriteria.length>0){t.push(``,`Acceptance criteria (current task):`);for(let n of e.acceptanceCriteria){let e=n.required===!1?``:` [required]`;t.push(`- ${n.id}${e}: ${br(n.text)}`)}}if(e.requiredTasks.length>0){t.push(``,`Completion report required tasks:`);for(let n of e.requiredTasks){t.push(`- ${n.taskId} [${n.status}]: ${br(n.title)}`);for(let e of n.acceptanceCriteria)e.required!==!1&&t.push(` - ${e.id} [required]: ${br(e.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${br(n)}`)}return t}function Sr(e){let t=[`- Treat goal/state.json as the only task workflow machine state; use goal/plan.md for human-readable context.`,`- Work on the current task and acceptance criteria shown in this context.`,`- Do not expose internal workflow files or task mechanics to the user unless they ask for implementation details.`,`- If the overall goal is genuinely achieved, submit goal({ status: "complete", summary, completedTasks }) with every required task and acceptance criterion covered by evidence summaries and sources.`,`- If the goal cannot continue without user input or external state, submit goal({ status: "blocked", reason, neededInput }).`,`- Use the current worktree, files, command output, and test results as authoritative evidence.`,`- Do not rely solely on conversation memory to assess completion.`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress on the current task.`,`- Do not inform the user about this continuation context; treat it as internal steering.`];return(e.currentTaskKind===`clarify`||e.currentTaskTitle===sn)&&t.unshift(`- Current task is "${sn}": explore, clarify, and refine the plan and acceptance criteria.`,`- Do NOT implement deliverables yet; use normal conversation to clarify scope and acceptance before execution work.`),t}function Cr(){return[`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- If the overall goal is genuinely achieved, submit goal({ status: "complete", summary, completedTasks }) with every required task and acceptance criterion covered by evidence summaries and sources.`,`- If the goal cannot continue without user input or external state, submit goal({ status: "blocked", reason, neededInput }).`,`- Do NOT mark complete merely because the budget is nearly exhausted or you are stopping work.`,`- If you cannot finish in this turn, make concrete progress and the goal remains active.`,`- Do not inform the user about this continuation context; treat it as internal steering.`]}const wr=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function Tr(e,t,n){return Er(e,t,n,{introLine:wr})}function Er(e,t,n,r){let i=br(t),a=e.tokenBudget===null?`none`:String(e.tokenBudget),o=String(e.tokensUsed),s=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed)),c=n?`The user's thread goal is still active. Continue working on the current workflow task below.`:`The user's thread goal is still active. Continue working toward the objective below.`,l=[`<goal_context>`,``,r?.introLine??c,``,`<objective>`,i,`</objective>`,``,`Token budget: ${a}`,`Tokens used: ${o}`,`Tokens remaining: ${s}`,`Time used: ${e.timeUsedSeconds}s`,``];return n?l.push(`<workflow>`,...xr(n),`</workflow>`,``,`Rules:`,...Sr(n)):l.push(`Rules:`,...Cr()),l.push(``,`</goal_context>`),l.join(`
5
5
  `)}function Dr(e,t){let n=br(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed);return[`<goal_context>`,``,`The token budget for the current thread goal has been exhausted.`,`The goal status has been set to "budget_limited" automatically.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Instructions:`,`- Wrap up the current turn soon. Do not start new substantive work.`,`- Summarize progress made, any blockers, and what would be needed next.`,`- Do NOT submit goal complete unless the objective is truly achieved.`,`- The user can increase the budget or resume the goal later via the CLI.`,``,`</goal_context>`].join(`
6
6
  `)}function Or(e,t){let n=br(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The thread goal objective has been edited by the user.`,`The following objective supersedes any previous thread goal objective.`,`Adjust your work direction accordingly.`,``,`<untrusted_objective>`,n,`</untrusted_objective>`,``,`Token budget: ${r}`,`Tokens remaining: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Use the goal tool only for terminal complete or blocked status; do not use it for routine progress notes.`,``,`</goal_context>`].join(`
7
- `)}function kr(e){return{role:`user`,content:e}}function Ar(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const jr=`AIMAX_GOAL_CONTINUATION`;var Mr=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function Nr(e,t,n){let r=await Qn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await mr(e,t,{storeName:n?.storeName}),a=r.currentTaskId?r.tasks.find(e=>e.id===r.currentTaskId)??null:null;return{workflowStatus:r.status,currentTaskId:r.currentTaskId,currentTaskTitle:a?.title??null,currentTaskKind:a?.kind??null,currentTaskStatus:a?.status??null,blockedReason:r.blockedReason,taskBlockedReason:a?.blockedReason??null,acceptanceCriteria:a?.acceptanceCriteria??[],requiredTasks:r.tasks.filter(e=>e.required!==!1).map(e=>({taskId:e.id,title:e.title,status:e.status,acceptanceCriteria:e.acceptanceCriteria})),openQuestions:i.openQuestions??[]}}function Pr(){let e=process.env[jr];return e===void 0||e===``||e!==`0`}async function Fr(e,t,n,r){if(!Pr()||n.continuationCount>=kt)return!1;let i=await H(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-BwYOp-2K.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Ir(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Lr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await Fr(n,r,a,{storeName:i}))return!1;let u=await H(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await z(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await Nr(n,r,{storeName:i}),h=kr(p?Dr(u,f):Er(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Ir(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=kt){let e=await H(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-M3_Nx3ky.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-CocRykqc.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${kt}), goal paused`)}}return!0}async function Rr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function zr(e,t,n){let r=await Qn(e,t,{storeName:n?.storeName});if(!r||r.status!==`blocked`)return{recovered:!1};let i=r.currentTaskId,a=r.blockedReason,o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await pr(e,t,c,{storeName:n?.storeName}),await vr(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await mr(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await gr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await _r(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Br(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await Nr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=kr(Tr(i,await z(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Vr(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=kr(Or(i,await z(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function Hr(e,t,n){(await H(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await V(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const Ur=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Wr(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===sn}function Gr(e){return Ur.has(e)}function Kr(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before running commands.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before executing deliverables directly.`].join(` `)}function qr(e){let t=!0;return e.hookRegistry.register({pluginId:`goal-clarify-first-turn-gate`,hookName:`before_tool_call`,source:`agents/goal/clarify-first-turn-gate`,priority:100,handler:n=>{if(!(!t||!e.isGateActive())&&Gr(n.toolName))return{block:!0,blockReason:Kr(n.toolName)}}}),()=>{t=!1}}function Jr(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 Yr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(ri(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}ii(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 Xr(e,t={}){let n=ti(t.limit,`limit`),r=ni(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!ii(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:ei(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Zr(e,t){let n=ni(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 Qr(e,t=80){let n=ni(e,`totalEntryCount`),r=ni(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function $r(e,t){return e.slice(t.startIndex,t.endIndex)}function ei(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function ti(e,t){return e===void 0?1/0:ni(e,t)}function ni(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function ri(e){return e.role===`assistant`}function ii(e){return e.role===`tool_result`}const ai=24e3;async function oi(e){return mi({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function si(e){return mi({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ci(e){return mi({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function li(e){let t=Si(e),n=await di(e),r=await vi(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:fi(e.dataDir,e.sessionId,e.sessionOptions)}}function ui(e){return{maxEntries:Ci(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Ci(e?.maxBytes??ai,`limits.maxBytes`)}}async function di(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=hi(await gi(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 _i({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function fi(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function pi(e,t,n){let r=wi(e.startIndex,`startIndex`),i=wi(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 mi(e){let t=Si(e.params),n=pi(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=yi(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:fi(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function hi(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 gi(e,t,n){let[r,i]=await Promise.all([F(e,t,n),P(e,t,n)]),a=new Map;for(let e of r)Di(e)&&e.toolResultRef?.sessionId===t&&a.set(Oi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(Oi(e),e);return Array.from(a.values())}async function _i(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(K.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=r(e.dataDir,e.sessionId,e.sessionOptions),i=K.resolve(e.dataDir,e.reference.storagePath);if(!Ei(K.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Ei(K.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([Ti(t),Ti(n),Ti(i)]);if(!Ei(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Ei(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function vi(e,t){let n=await G.stat(e),r=await G.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:xi(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function yi(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=bi(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 bi(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:xi(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function xi(e){let t=new Bt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function Si(e){return ui(e.limits)}function Ci(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function wi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function Ti(e){try{return await G.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${ki(e)}`)}}function Ei(e,t){let n=K.relative(e,t);return n===``||!n.startsWith(`..`)&&!K.isAbsolute(n)}function Di(e){return e.role===`tool_result`}function Oi(e){return`${e.toolCallId}\n${e.storagePath}`}function ki(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ai(e){return K.join(e,`.aimax`,`auto-skills`)}function ji(e){return K.join(e,`categories.json`)}function Mi(e){return K.join(e,`.auto_skills_prompt_snapshot.json`)}const Ni=/^[a-z0-9][a-z0-9-]*$/,Pi=/^[a-z0-9][a-z0-9-]*$/;function Fi(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||K.win32.isAbsolute(t)||K.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!Ni.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Ii(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(`.`)||!Pi.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Li(e,t){return`auto:${Fi(e)}/${Ii(t)}`}function Ri(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=Fi(n.slice(0,r)),a=Ii(n.slice(r+1));return{skillId:Li(i,a),categoryPath:i,skillName:a}}function zi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Bi(e,t,n){let r=K.resolve(e),i=K.resolve(r,...Fi(t).split(`/`),Ii(n));return Hi(r,i),i}function Vi(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||K.win32.isAbsolute(n)||K.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=K.resolve(e),a=K.resolve(i,...r);return Hi(i,a),a}function Hi(e,t){let n=K.resolve(e),r=K.resolve(t),i=K.relative(n,r);if(i.startsWith(`..`)||K.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Ui(e){let t=ji(e),n;try{n=await G.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=Fi(e),r=Gi(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 Wi(e){return new Map(e.map(e=>[e.path,e]))}function Gi(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 Ki=32*1024,qi=new Map;function Ji(e){return new Xi(e)}async function Yi(e){let t=K.resolve(e);for(let e of Array.from(qi.keys()))e.startsWith(`${t}|`)&&qi.delete(e);await G.rm(Mi(t),{force:!0}).catch(()=>{})}var Xi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Ai(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Qi(Wi((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Fi(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>$i(e.categoryPath,t)).map(Zi)}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:ea(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})=>({...Zi(e),score:t}))}async autoSkillView(e){let t=Ri(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=Vi(n.skillDir,e.filePath),r=await la(t,this.maxResourceBytes);return{...Zi(n),status:n.status,content:r,path:fa(K.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:fa(K.relative(n.skillDir,t))}}let r=await la(n.skillFile,this.maxSkillBytes);return{...Zi(n),status:n.status,content:r,path:fa(K.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await ta(this.rootDir),i=qi.get(n);if(!e&&i&&oa(i.manifest,r))return i;let a=e?void 0:await ia(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return qi.set(n,e),e}let o=await Ui(this.rootDir),s=Wi(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return qi.set(n,c),await aa(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 ha({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Ki})}async loadEntry(e){try{let t=K.dirname(e),n=Ii(K.basename(t)),r=fa(K.relative(this.rootDir,t)),i=Fi(K.posix.dirname(r)),a=Li(i,n),o=K.join(t,`metadata.json`),s=await sa(o);if(s?.skillId&&Ri(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Fi(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=zi(s?.status);return{skillId:a,name:n,description:ua(await ca(e,Ki)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:da(s?.tags),relatedSkills:da(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}: ${pa(t)}\n`);return}}};function Zi(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Qi(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function $i(e,t){return t?e===t:!0}function ea(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 ta(e){let t;try{t=await G.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await ra(K.join(e,`categories.json`),`categories`,n),await na(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function na(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=K.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await ra(t,`skill`,n),await ra(K.join(e,`metadata.json`),`metadata`,n),await ra(K.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await G.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await na(t,i,n)}}async function ra(e,t,n){try{let r=await G.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function ia(e,t,n){let r;try{r=await G.readFile(Mi(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)||!oa(e.manifest,n)?void 0:e}catch{return}}async function aa(e,t){if(!await ma(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await G.writeFile(Mi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function oa(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 sa(e){try{let t=await G.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function ca(e,t){let n=await G.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function la(e,t){if((await G.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return G.readFile(e,`utf-8`)}function ua(e){let t=Vt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
7
+ `)}function kr(e){return{role:`user`,content:e}}function Ar(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const jr=`AIMAX_GOAL_CONTINUATION`;var Mr=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function Nr(e,t,n){let r=await Qn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await mr(e,t,{storeName:n?.storeName}),a=r.currentTaskId?r.tasks.find(e=>e.id===r.currentTaskId)??null:null;return{workflowStatus:r.status,currentTaskId:r.currentTaskId,currentTaskTitle:a?.title??null,currentTaskKind:a?.kind??null,currentTaskStatus:a?.status??null,blockedReason:r.blockedReason,taskBlockedReason:a?.blockedReason??null,acceptanceCriteria:a?.acceptanceCriteria??[],requiredTasks:r.tasks.filter(e=>e.required!==!1).map(e=>({taskId:e.id,title:e.title,status:e.status,acceptanceCriteria:e.acceptanceCriteria})),openQuestions:i.openQuestions??[]}}function Pr(){let e=process.env[jr];return e===void 0||e===``||e!==`0`}async function Fr(e,t,n,r){if(!Pr()||n.continuationCount>=kt)return!1;let i=await H(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-Bj0MvQOw.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Ir(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Lr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await Fr(n,r,a,{storeName:i}))return!1;let u=await H(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await z(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await Nr(n,r,{storeName:i}),h=kr(p?Dr(u,f):Er(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Ir(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=kt){let e=await H(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-CGUkaQtk.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-B5anors9.js`).then(e=>e.r),s={storeName:i,eventSource:`runner`};await t(n,r,{status:`paused`},s),await o(n,r,{goalId:e?.goalId??null,action:`continuation_paused`,status:`paused`,source:`runner`,detail:{continuationCount:a.continuationCount}},s),console.error(`goal continuation limit reached (${kt}), goal paused`)}}return!0}async function Rr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function zr(e,t,n){let r=await Qn(e,t,{storeName:n?.storeName});if(!r||r.status!==`blocked`)return{recovered:!1};let i=r.currentTaskId,a=r.blockedReason,o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await pr(e,t,c,{storeName:n?.storeName}),await vr(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await mr(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await gr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await _r(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Br(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await Nr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=kr(Tr(i,await z(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Vr(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=kr(Or(i,await z(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function Hr(e,t,n){(await H(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await V(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const Ur=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Wr(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===sn}function Gr(e){return Ur.has(e)}function Kr(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before running commands.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use non-destructive reading and normal conversation to clarify scope and acceptance before executing deliverables directly.`].join(` `)}function qr(e){let t=!0;return e.hookRegistry.register({pluginId:`goal-clarify-first-turn-gate`,hookName:`before_tool_call`,source:`agents/goal/clarify-first-turn-gate`,priority:100,handler:n=>{if(!(!t||!e.isGateActive())&&Gr(n.toolName))return{block:!0,blockReason:Kr(n.toolName)}}}),()=>{t=!1}}function Jr(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 Yr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(ri(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}ii(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 Xr(e,t={}){let n=ti(t.limit,`limit`),r=ni(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!ii(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:ei(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Zr(e,t){let n=ni(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 Qr(e,t=80){let n=ni(e,`totalEntryCount`),r=ni(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function $r(e,t){return e.slice(t.startIndex,t.endIndex)}function ei(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function ti(e,t){return e===void 0?1/0:ni(e,t)}function ni(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function ri(e){return e.role===`assistant`}function ii(e){return e.role===`tool_result`}const ai=24e3;async function oi(e){return mi({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function si(e){return mi({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ci(e){return mi({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function li(e){let t=Si(e),n=await di(e),r=await vi(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:fi(e.dataDir,e.sessionId,e.sessionOptions)}}function ui(e){return{maxEntries:Ci(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Ci(e?.maxBytes??ai,`limits.maxBytes`)}}async function di(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=hi(await gi(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 _i({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function fi(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function pi(e,t,n){let r=wi(e.startIndex,`startIndex`),i=wi(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 mi(e){let t=Si(e.params),n=pi(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=yi(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:fi(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function hi(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 gi(e,t,n){let[r,i]=await Promise.all([F(e,t,n),P(e,t,n)]),a=new Map;for(let e of r)Di(e)&&e.toolResultRef?.sessionId===t&&a.set(Oi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(Oi(e),e);return Array.from(a.values())}async function _i(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(K.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=r(e.dataDir,e.sessionId,e.sessionOptions),i=K.resolve(e.dataDir,e.reference.storagePath);if(!Ei(K.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Ei(K.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([Ti(t),Ti(n),Ti(i)]);if(!Ei(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Ei(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function vi(e,t){let n=await G.stat(e),r=await G.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:xi(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function yi(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=bi(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 bi(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:xi(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function xi(e){let t=new Bt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function Si(e){return ui(e.limits)}function Ci(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function wi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function Ti(e){try{return await G.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${ki(e)}`)}}function Ei(e,t){let n=K.relative(e,t);return n===``||!n.startsWith(`..`)&&!K.isAbsolute(n)}function Di(e){return e.role===`tool_result`}function Oi(e){return`${e.toolCallId}\n${e.storagePath}`}function ki(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ai(e){return K.join(e,`.aimax`,`auto-skills`)}function ji(e){return K.join(e,`categories.json`)}function Mi(e){return K.join(e,`.auto_skills_prompt_snapshot.json`)}const Ni=/^[a-z0-9][a-z0-9-]*$/,Pi=/^[a-z0-9][a-z0-9-]*$/;function Fi(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||K.win32.isAbsolute(t)||K.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!Ni.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Ii(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(`.`)||!Pi.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Li(e,t){return`auto:${Fi(e)}/${Ii(t)}`}function Ri(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=Fi(n.slice(0,r)),a=Ii(n.slice(r+1));return{skillId:Li(i,a),categoryPath:i,skillName:a}}function zi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Bi(e,t,n){let r=K.resolve(e),i=K.resolve(r,...Fi(t).split(`/`),Ii(n));return Hi(r,i),i}function Vi(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||K.win32.isAbsolute(n)||K.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=K.resolve(e),a=K.resolve(i,...r);return Hi(i,a),a}function Hi(e,t){let n=K.resolve(e),r=K.resolve(t),i=K.relative(n,r);if(i.startsWith(`..`)||K.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Ui(e){let t=ji(e),n;try{n=await G.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=Fi(e),r=Gi(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 Wi(e){return new Map(e.map(e=>[e.path,e]))}function Gi(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 Ki=32*1024,qi=new Map;function Ji(e){return new Xi(e)}async function Yi(e){let t=K.resolve(e);for(let e of Array.from(qi.keys()))e.startsWith(`${t}|`)&&qi.delete(e);await G.rm(Mi(t),{force:!0}).catch(()=>{})}var Xi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Ai(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Qi(Wi((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Fi(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>$i(e.categoryPath,t)).map(Zi)}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:ea(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})=>({...Zi(e),score:t}))}async autoSkillView(e){let t=Ri(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=Vi(n.skillDir,e.filePath),r=await la(t,this.maxResourceBytes);return{...Zi(n),status:n.status,content:r,path:fa(K.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:fa(K.relative(n.skillDir,t))}}let r=await la(n.skillFile,this.maxSkillBytes);return{...Zi(n),status:n.status,content:r,path:fa(K.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await ta(this.rootDir),i=qi.get(n);if(!e&&i&&oa(i.manifest,r))return i;let a=e?void 0:await ia(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return qi.set(n,e),e}let o=await Ui(this.rootDir),s=Wi(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return qi.set(n,c),await aa(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 ha({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Ki})}async loadEntry(e){try{let t=K.dirname(e),n=Ii(K.basename(t)),r=fa(K.relative(this.rootDir,t)),i=Fi(K.posix.dirname(r)),a=Li(i,n),o=K.join(t,`metadata.json`),s=await sa(o);if(s?.skillId&&Ri(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Fi(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=zi(s?.status);return{skillId:a,name:n,description:ua(await ca(e,Ki)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:da(s?.tags),relatedSkills:da(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}: ${pa(t)}\n`);return}}};function Zi(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Qi(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function $i(e,t){return t?e===t:!0}function ea(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 ta(e){let t;try{t=await G.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await ra(K.join(e,`categories.json`),`categories`,n),await na(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function na(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=K.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await ra(t,`skill`,n),await ra(K.join(e,`metadata.json`),`metadata`,n),await ra(K.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await G.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await na(t,i,n)}}async function ra(e,t,n){try{let r=await G.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function ia(e,t,n){let r;try{r=await G.readFile(Mi(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)||!oa(e.manifest,n)?void 0:e}catch{return}}async function aa(e,t){if(!await ma(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await G.writeFile(Mi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function oa(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 sa(e){try{let t=await G.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function ca(e,t){let n=await G.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function la(e,t){if((await G.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return G.readFile(e,`utf-8`)}function ua(e){let t=Vt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
8
8
  `)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function da(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function fa(e){return e.split(K.sep).join(`/`)}function pa(e){return e instanceof Error?e.message:String(e)}async function ma(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ha(e){return Ft(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function ga(e,t,n,r){return le(ue(e.apiFormat)).createModel(e,t,n,r)}const _a=`/aimax/agents`,va=/^[a-z]+(?:-[a-z]+)*$/;function ya(e){let t=[{dir:e.systemAgentsDir??_a,source:`system`},{dir:K.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:K.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function ba(e){let t=new Map;for(let n of ya(e)){let e=await wa(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function xa(e={}){let t=e.allAgents??e.availableAgents??[],n=Oa(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Ea(n,e),findAny:e=>Ea(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function Sa(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 Ca(e){return Sa(e.agentPolicy)?e.agentPolicy:xa({allAgents:await ba(e)})}async function wa(e,t){let n;try{n=await G.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=K.join(e,i.name),a=Ta(await G.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function Ta(e,t){let n=Vt(e),r=Na(n.data.name)?.trim(),i=Na(n.data.description)?.trim();if(!r||!va.test(r)||!i)return;let a=Na(n.data.model)?.trim(),o=Na(n.data.initPrompt)?.trim()??Na(n.data.initialPrompt)?.trim(),s=Pa(n.data.maxTurns),c=Fa(n.data.tools),l=Fa(n.data.disallowedTools),u=Fa(n.data.skills),d=Ia(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 Ea(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Da(e)===`public`))}function Da(e){return e.visibility??`public`}function Oa(e){return e.filter(e=>Da(e)===`public`)}function ka(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Aa(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(La)):void 0,r=new Set((t.disallowedTools??[]).map(La));return e.filter(e=>{let t=typeof e.name==`string`?La(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function ja(e){let t=Oa(e).filter(e=>e.source!==`system`);return t.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name exactly matches one of the listed custom agents, that mention is an explicit delegation request.","For such a matching `@<agent-name>` request, you MUST call `subagent_spawn` to run the request through that custom agent, with the `agent` field set to the exact matched agent name.","Do not answer the request yourself, do not merely describe the agent, and do not omit the tool call when a matching `@<agent-name>` is present.",`If the mention does not exactly match a listed custom agent, do not invent a match; continue with the current agent or ask a concise clarification if needed.`,t.map(e=>`- ${e.name}: ${e.description}`).join(`
9
9
  `),``].join(`
10
10
  `)}function Ma(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Na(e){return typeof e==`string`?e:void 0}function Pa(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Fa(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 Ia(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function La(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}var Ra=class{constructor(e){this.params=e}async dispatchProgress(e,t){let n={...t,sessionId:e,...this.params.messageId?{messageId:this.params.messageId}:{},...this.params.subagentContext?{parentSessionId:this.params.subagentContext.parentSessionId,depth:this.params.subagentContext.depth}:{}};try{await this.params.onProgress?.(n)}catch(n){W.warn(`progress handler failed; event dropped`,{sessionId:e,eventType:t.type,error:n instanceof Error?n.message:String(n)})}}async dispatchDiagnostic(e,t){await this.dispatchProgress(e,{type:`diagnostic`,...t})}};const za=`<aimax_artifacts>`,Ba=`</aimax_artifacts>`;function Va(e,t={}){let n=[];if(!e.includes(za))return{cleanedText:e,artifacts:[],warnings:n};let r=e,i,a=[];for(;;){let e=r.indexOf(za);if(e===-1)break;let o=r.indexOf(Ba,e+17);if(o===-1){n.push(`Artifacts block is missing the closing tag; stripping the malformed block`),r=r.slice(0,e).trimEnd();break}let s=r.slice(e+17,o).trim();s&&(i??=(t.now??(()=>new Date))().toISOString(),a.push(...Ha(s,{warnings:n,timestamp:i,workspaceDir:t.workspaceDir}))),r=[r.slice(0,e).trimEnd(),r.slice(o+18).trimStart()].filter(e=>e.length>0).join(`
@@ -13,80 +13,80 @@ import{A as e,C as t,D as n,E as r,F as i,I as a,L as o,M as s,N as c,O as l,P a
13
13
 
14
14
  `);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(`
15
15
  `))}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(`
16
- `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:Do(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 ts(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function ns(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 rs(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`deepseek`||n.includes(`deepseek.com`),a=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||i||r||t===`opencode`||n.includes(`opencode.ai`),o=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),s=t===`xai`||n.includes(`api.x.ai`),c=t===`mistral`||n.includes(`mistral.ai`),l=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!a,supportsDeveloperRole:!a,supportsReasoningEffort:!s&&!r,supportsUsageInStreaming:!0,maxTokensField:o?`max_tokens`:`max_completion_tokens`,requiresToolResultName:c,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:c,requiresReasoningContentOnAssistantMessages:i,thinkingFormat:i?`deepseek`:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:!1,supportsStrictMode:!0,cacheControlFormat:l,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!0}}function is(e){let t=rs(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,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}const as=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function os(e){return e instanceof Error?!(e instanceof ge)&&!ss(e)&&cs(e)?new ge({message:`LLM network request failed: ${e.message}`,code:`network_error`,retryable:!0,cause:e}):e:cs(e)?new ge({message:`LLM network request failed: ${String(e)}`,code:`network_error`,retryable:!0,cause:e}):Error(typeof e==`string`?e:JSON.stringify(e))}function ss(e){return e instanceof Error&&e.name===`AbortError`?!0:(e&&typeof e==`object`?e.code:void 0)===`aborted`}function cs(e){let t=new Set;for(let n=e;n!=null&&!t.has(n);){t.add(n);let e=n&&typeof n==`object`?n.code:void 0;if(typeof e==`string`&&as.has(e.toLowerCase()))return!0;let r=typeof n==`string`?n:n&&typeof n==`object`?n.message:void 0;if(typeof r==`string`&&r.trim().toLowerCase()===`terminated`)return!0;n=n&&typeof n==`object`?n.cause:void 0}return!1}const ls=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),us=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),ds=[`llmrequesterror`],fs=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function ps(e){let t=_s(e?.maxAttempts,3),n=vs(e?.initialDelayMs,250),r=vs(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function ms(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function hs(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 gs(e){if(xs(e))return!1;let t=ys(e),n=bs(e),r=t?.message??n;if(js(r))return!0;if(t?.statusCode!==void 0)return Os(t.statusCode);if(t?.providerCode!==void 0)return Ds(t.providerCode);let i=ks(r);if(i!==void 0)return Os(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(ls.has(e))return!0;if(us.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;if(Ss(e))return!0;let a=As(r);return a===void 0?t?.retryable===!0:a}function _s(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function vs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function ys(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 bs(e){if(typeof e==`string`)return e;if(e instanceof Error&&typeof e.message==`string`||e&&typeof e==`object`&&typeof e.message==`string`)return e.message}function xs(e){return ys(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function Ss(e){let t=new Set;for(let n=e;n!=null&&!t.has(n);){t.add(n);let e=Cs(n);if(e!==void 0&&fs.has(e.toLowerCase()))return!0;let r=ws(n);if(r!==void 0&&Ts(r))return!0;n=Es(n)}return!1}function Cs(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`&&t.length>0?t:void 0}function ws(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return;let t=e.message;return typeof t==`string`?t:void 0}function Ts(e){return e.trim().toLowerCase()===`terminated`}function Es(e){if(!(!e||typeof e!=`object`))return e.cause}function Ds(e){return/^\d+$/.test(e)?Os(Number(e)):!1}function Os(e){return e===408||e===409||e===425||e===429||e>=500}function ks(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function As(e){if(!e)return;let t=Ms(e);for(let e of us)if(t.includes(e))return!1;for(let e of ls)if(t.includes(e))return!0}function js(e){if(!e)return!1;let t=Ms(e);return ds.some(e=>t.includes(e))}function Ms(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const Ns=Symbol(`omit-json-value`);function Ps(e,t=new WeakSet){if(e===void 0)return Ns;if(typeof e==`bigint`)return e.toString();if(typeof e==`function`)return`[Function]`;if(typeof e==`symbol`)return`[Symbol]`;if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=Ps(r,t);e!==Ns&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=Ps(i,t);e!==Ns&&(n[r]=e)}return n}finally{t.delete(e)}}function Fs(e,t,n){return K.join(K.dirname(C(e,t,n)),`session-tools.json`)}function Is(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:Ps(e.parameters??{})}))}async function Ls(e,t,n){let r=await o(Fs(e,t,n));if(!r?.trim())return null;try{let e=JSON.parse(r);if(e.version!==1||!Array.isArray(e.tools))return null;let t=e.tools.filter(e=>!!(e&&typeof e.name==`string`)).map(e=>({name:e.name,description:typeof e.description==`string`?e.description:``,parameters:e.parameters??{}}));return{version:1,recordedAt:typeof e.recordedAt==`string`?e.recordedAt:new Date(0).toISOString(),tools:t}}catch{return null}}async function Rs(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:Is(n.tools)},a=`${JSON.stringify(i,null,2)}\n`;await Promise.all([L(C(e,t,r),n.systemPrompt,r?.encryptSessions),L(Fs(e,t,r),a,r?.encryptSessions)])}async function zs(e,t,n){let[r,i]=await Promise.all([g(e,t,n),Ls(e,t,n)]);return{...r?.trim()?{systemPrompt:r}:{},...i&&i.tools.length>0?{tools:i.tools}:{}}}function Bs(e){return Math.ceil(e.length/4*1.2)}function Vs(e){if(e.role===`user`)return Bs(e.content);if(e.role===`assistant`){let t=Bs(e.content),n=e.thinking?.trim();n&&(t+=Bs(n)),e.errorMessage&&(t+=Bs(e.errorMessage));for(let n of e.toolCalls??[])t+=Bs(n.name)+Bs(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(`
17
- `):e.content;return Bs(e.toolName)+Bs(t)}function J(e){return e.reduce((e,t)=>e+Vs(t),0)}function Hs(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}function Us(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}const Ws=[`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.`],Gs={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Ks(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function qs(e,t,n){return e.map(e=>Js(e,t,n))}function Js(e,t,n){let r=new Date(e.timestamp).getTime();if(Ys(e))return{role:`user`,content:e.content,timestamp:r};if(Xs(e)){let i=[],a=e.thinking?.trim();n?.replayThinking&&a&&i.push({type:`thinking`,thinking:a,...n.thinkingSignature?{thinkingSignature:n.thinkingSignature}:{}}),e.content&&i.push({type:`text`,text:e.content});for(let t of e.toolCalls??[])i.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});return{role:`assistant`,content:i,api:t.api,provider:`openai`,model:t.model,usage:Gs,stopReason:e.stopReason??`stop`,errorMessage:e.errorMessage,timestamp:r}}let i=e;return{role:`toolResult`,toolCallId:i.toolCallId,toolName:i.toolName,content:[{type:`text`,text:Zs(i)}],isError:i.isError,timestamp:r}}function Ys(e){return e.role===`user`}function Xs(e){return e.role===`assistant`}function Zs(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:`,...Ws];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
18
- `)}const Qs=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,"- Any unfinished plan submitted through `update_task`, especially pending and in_progress tasks, current progress, and necessary constraints.",`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- A list of skill names and their locations/paths mentioned or loaded in the compressed content, especially skill_load names and paths`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
19
- `);async function $s(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=tc(t,r,i,a),u=nc(a),d,f=ce({apiFormat:n.apiFormat,baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:n.model,hooks:s,hookCtx:c});for(let e=1;e<=3;e++)try{let e=(await f.chat({system:Qs,user:l,temperature:0,maxTokens:u,signal:o})).text.trim();if(!e)throw Error(`LLM summarisation returned empty content`);return e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;d=t,e<3&&await ec(500*e)}throw d}function ec(e){return new Promise(t=>setTimeout(t,e))}function tc(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${oc(t.trim(),rc(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=ic(e,t,n,r),o=ac(t,n,r);for(let[t,n]of e.entries()){if(o<=0){i.push(`[${e.length-t} entries omitted because the summarisation input budget was exhausted]`);break}let r=``;if(n.role===`user`)r=`User: ${oc(n.content,Math.min(a,o))}`;else if(n.role===`assistant`)r=`Assistant:${n.toolCalls&&n.toolCalls.length>0?` [called tools: ${n.toolCalls.map(e=>e.name).join(`, `)}]`:``} ${oc(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?sc(n):n.toolResultRef?[`[tool result persisted] ${n.toolResultRef.toolName} (${n.toolResultRef.originalChars} chars).`,`Full output: ${n.toolResultRef.storagePath}`,n.toolResultRef.preview.trim()?`Preview:\n${n.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
20
- `):n.content;r=`Tool(${n.toolName})[${e}]: ${oc(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
21
- `)}function nc(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function rc(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function ic(e,t,n,r){let i=ac(t,n,r);if(!r||r<=0)return 2e3;let a=nc(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=Qs.length+(t?.length??0)+(n?.length??0)+1e3,c=Math.max(1e3,o*4-s);return Math.max(120,Math.min(2e3,i,Math.floor(c/Math.max(1,e.length))))}function ac(e,t,n){if(!n||n<=0)return 1/0;let r=nc(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=Qs.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function oc(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function sc(e){let t=cc(e),n=t.name??`<skill-name>`,r=t.path,i=r?`skill_load(name="${n}", skillPath="${r}")`:`skill_load(name="${n}")`;return[`[skill content folded] skill_load result for "${n}" is not a reliable source for future instructions.`,r?`Original path: ${r}`:``,`If this skill is needed later, call ${i} again.`,`Do not summarize, infer, or reconstruct SKILL.md instructions from this history.`].filter(Boolean).join(`
22
- `)}function cc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=lc(t);if(e.name||e.path)return e}return{}}function lc(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 uc(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Vs(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function dc(e){return pc((await ce({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:gc,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.segments},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}async function fc(e){return mc((await ce({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:_c,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedTurns:e.maxSelectedTurns,turns:e.turns},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}function pc(e){let t=hc(e);if(t.version!==1||!Array.isArray(t.selectedSegmentIds))throw Error(`Topic segment selection decision has invalid schema.`);return{version:1,selectedSegmentIds:t.selectedSegmentIds.filter(e=>typeof e==`string`),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function mc(e){let t=hc(e);if(t.version!==1||!Array.isArray(t.selectedTurns))throw Error(`Topic turn selection decision has invalid schema.`);return{version:1,selectedTurns:t.selectedTurns.filter(e=>!!(e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:typeof e.topicLabel==`string`?e.topicLabel.trim():void 0,keywords:Array.isArray(e.keywords)?e.keywords.filter(e=>typeof e==`string`&&e.trim().length>0):void 0})),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function hc(e){let t=e.trim();if(!t)throw Error(`Topic segmentation model returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t;return JSON.parse(r)}[`You maintain SeCom-style conversation segments for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"action":"merge|split","reason":"...","topicLabel":"optional","summary":"...","compressedSummary":"...","keywords":["..."]}`,`Task: compare the active segment with the new user turn.`,`Use action=merge only when the new turn continues the same topic, task, artifact, bug, document, or refinement thread.`,`Use action=split when the new turn starts a different topic.`,`Always provide summary, compressedSummary, and concise keywords for the resulting segment after your decision.`,`Do not answer the user.`].join(`
23
- `);const gc=[`You select relevant conversation segments for an IM assistant before final turn-level topic classification.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedSegmentIds":["..."],"reason":"...","confidence":"high|medium|low"}`,`Task: choose which prior segments are relevant to the current user message.`,`Relevant includes same task continuation, explicit topic return, reuse of prior artifact, correction, or combining multiple earlier topics.`,`Prefer recall over over-pruning when the user explicitly refers to older topics by name.`,`Do not answer the user.`].join(`
24
- `),_c=[`You select relevant historical conversation turns for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurns":[{"turnId":"...","summary":"...","topicLabel":"optional","keywords":["..."]}],"reason":"...","confidence":"high|medium|low"}`,`Task: from the provided turns, select any turn that may be relevant to the current user message.`,`This is recall-first. It is better to include possibly relevant turns than to miss a relevant one.`,`Select turns for same task continuation, explicit old-topic return, reuse of prior artifact, corrections, or combinations of multiple earlier topics.`,`For every selected turn, provide a concise reusable summary, an optional topicLabel, and short keywords.`,`Prefer the provided summary/topicLabel fields when they exist; use raw user/assistant content only when needed.`,`Do not answer the user.`].join(`
25
- `);async function vc(e){let t=Cc(e);if(t)try{let e=await G.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(zc);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function yc(e){let t=Cc(e);t&&(await G.mkdir(K.dirname(t),{recursive:!0}),await G.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function bc(e){let t=wc(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||Tc(t,e)){r.push(e);continue}n.push(Dc(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(Dc(r,n.length+1,!0)),n}function xc(e,t){let n=wc(t);if(n.length===0)return[];if(!e||e.length===0)return bc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return bc(t);if(r.length===n.length)return e;let a=e.map(e=>({...e,turnIds:[...e.turnIds],toolNames:[...e.toolNames],keywords:[...e.keywords]})),o=n.slice(r.length);for(let e of o){let t=a[a.length-1];if(t&&Ec(t,e)){a[a.length-1]=Mc(t,e);continue}t&&(t.status=`closed`),a.push(Dc([e],a.length+1,!0))}if(a.length>1){for(let e=0;e<a.length-1;e+=1)a[e]={...a[e],status:`closed`};a[a.length-1]={...a[a.length-1],status:`active`}}return a}function Sc(e,t){if(!e||e.length===0||t.length===0)return e??[];let n=new Map(t.map(e=>[e.turnId,e])),r=!1,i=e.map(e=>{let t=new Map((e.turnMemories??[]).map(e=>[e.turnId,e])),i=!1;for(let r of e.turnIds){let e=n.get(r);if(!e)continue;let a=t.get(r);(!a||a.summary!==e.summary||a.topicLabel!==e.topicLabel||a.keywords.join(`|`)!==e.keywords.join(`|`))&&(t.set(r,e),i=!0)}if(!i)return e;r=!0;let a=[...t.values()].sort((e,t)=>e.turnId.localeCompare(t.turnId)),o=a.find(t=>e.turnIds.includes(t.turnId)),s=[...new Set([...e.keywords,...a.flatMap(e=>e.keywords)])];return{...e,keywords:s,topicLabel:o?.topicLabel??e.topicLabel,turnMemories:a,updatedAt:o?.updatedAt??e.updatedAt}});return r?i:e}function Cc(e){if(!(!e.dataDir||!e.sessionId))return K.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function wc(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,user:a.content,timestamp:a.timestamp,toolNames:[]};continue}if(n){if(n.endIndex=i,a.role===`assistant`){let e=(a.content||a.errorMessage||``).trim();e&&(n.assistant=e);for(let e of a.toolCalls??[])n.toolNames.push(e.name);continue}a.role===`tool_result`&&n.toolNames.push(a.toolName)}}return r(),t.map(e=>({...e,toolNames:[...new Set(e.toolNames)].sort()}))}function Tc(e,t){return Fc(Pc(e.user,e.assistant),Pc(t.user,t.assistant))>0}function Ec(e,t){return Fc(Pc(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),Pc(t.user,t.assistant,t.toolNames.join(` `)))>0}function Dc(e,t,n){return Oc(e,t,n)}function Oc(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=kc(e,o),c=Rc(r?.summary||s),l=Nc(r?.keywords,c,o),u=Rc(r?.compressedSummary||jc(c,o));return{version:1,segmentId:`segment-${t}`,turnIds:e.map(e=>e.turnId),startTurnId:i.turnId,endTurnId:a.turnId,startIndex:i.startIndex,endIndex:a.endIndex,userSummary:e.map(e=>e.user).join(`
16
+ `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:Do(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 ts(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function ns(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 rs(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`deepseek`||n.includes(`deepseek.com`),a=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||i||r||t===`opencode`||n.includes(`opencode.ai`),o=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),s=t===`xai`||n.includes(`api.x.ai`),c=t===`mistral`||n.includes(`mistral.ai`),l=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!a,supportsDeveloperRole:!a,supportsReasoningEffort:!s&&!r,supportsUsageInStreaming:!0,maxTokensField:o?`max_tokens`:`max_completion_tokens`,requiresToolResultName:c,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:c,requiresReasoningContentOnAssistantMessages:i,thinkingFormat:i?`deepseek`:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:!1,supportsStrictMode:!0,cacheControlFormat:l,sendSessionAffinityHeaders:!1,supportsLongCacheRetention:!0}}function is(e){let t=rs(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,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}const as=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function os(e){return e instanceof Error?!(e instanceof ge)&&!ss(e)&&cs(e)?new ge({message:`LLM network request failed: ${e.message}`,code:`network_error`,retryable:!0,cause:e}):e:cs(e)?new ge({message:`LLM network request failed: ${String(e)}`,code:`network_error`,retryable:!0,cause:e}):Error(typeof e==`string`?e:JSON.stringify(e))}function ss(e){return e instanceof Error&&e.name===`AbortError`?!0:(e&&typeof e==`object`?e.code:void 0)===`aborted`}function cs(e){let t=new Set;for(let n=e;n!=null&&!t.has(n);){t.add(n);let e=n&&typeof n==`object`?n.code:void 0;if(typeof e==`string`&&as.has(e.toLowerCase()))return!0;let r=typeof n==`string`?n:n&&typeof n==`object`?n.message:void 0;if(typeof r==`string`&&r.trim().toLowerCase()===`terminated`)return!0;n=n&&typeof n==`object`?n.cause:void 0}return!1}const ls=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),us=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),ds=[`llmrequesterror`],fs=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function ps(e){let t=_s(e?.maxAttempts,3),n=vs(e?.initialDelayMs,250),r=vs(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function ms(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function hs(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 gs(e){if(xs(e))return!1;let t=ys(e),n=bs(e),r=t?.message??n;if(js(r))return!0;if(t?.statusCode!==void 0)return Os(t.statusCode);if(t?.providerCode!==void 0)return Ds(t.providerCode);let i=ks(r);if(i!==void 0)return Os(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(ls.has(e))return!0;if(us.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;if(Ss(e))return!0;let a=As(r);return a===void 0?t?.retryable===!0:a}function _s(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function vs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function ys(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 bs(e){if(typeof e==`string`)return e;if(e instanceof Error&&typeof e.message==`string`||e&&typeof e==`object`&&typeof e.message==`string`)return e.message}function xs(e){return ys(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function Ss(e){let t=new Set;for(let n=e;n!=null&&!t.has(n);){t.add(n);let e=Cs(n);if(e!==void 0&&fs.has(e.toLowerCase()))return!0;let r=ws(n);if(r!==void 0&&Ts(r))return!0;n=Es(n)}return!1}function Cs(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`&&t.length>0?t:void 0}function ws(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return;let t=e.message;return typeof t==`string`?t:void 0}function Ts(e){return e.trim().toLowerCase()===`terminated`}function Es(e){if(!(!e||typeof e!=`object`))return e.cause}function Ds(e){return/^\d+$/.test(e)?Os(Number(e)):!1}function Os(e){return e===408||e===409||e===425||e===429||e>=500}function ks(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function As(e){if(!e)return;let t=Ms(e);for(let e of us)if(t.includes(e))return!1;for(let e of ls)if(t.includes(e))return!0}function js(e){if(!e)return!1;let t=Ms(e);return ds.some(e=>t.includes(e))}function Ms(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const Ns=Symbol(`omit-json-value`);function Ps(e,t=new WeakSet){if(e===void 0)return Ns;if(typeof e==`bigint`)return e.toString();if(typeof e==`function`)return`[Function]`;if(typeof e==`symbol`)return`[Symbol]`;if(typeof e!=`object`||!e)return e;if(t.has(e))return`[Circular]`;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=Ps(r,t);e!==Ns&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=Ps(i,t);e!==Ns&&(n[r]=e)}return n}finally{t.delete(e)}}function Fs(e,t,n){return K.join(r(e,t,n),`session-tools.json`)}function Is(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:Ps(e.parameters??{})}))}async function Ls(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:Is(n)};await L(Fs(e,t,r),`${JSON.stringify(i,null,2)}\n`,r?.encryptSessions)}async function Rs(e,t,n){let r=await o(Fs(e,t,n));if(!r?.trim())return null;try{let e=JSON.parse(r);if(e.version!==1||!Array.isArray(e.tools))return null;let t=e.tools.filter(e=>!!(e&&typeof e.name==`string`)).map(e=>({name:e.name,description:typeof e.description==`string`?e.description:``,parameters:e.parameters??{}}));return{version:1,recordedAt:typeof e.recordedAt==`string`?e.recordedAt:new Date(0).toISOString(),tools:t}}catch{return null}}async function zs(e,t,n,r){await Ls(e,t,n.tools,r)}async function Bs(e,t,n){let r=await Rs(e,t,n);return{...r&&r.tools.length>0?{tools:r.tools}:{}}}function Vs(e){return Math.ceil(e.length/4*1.2)}function Hs(e){if(e.role===`user`)return Vs(e.content);if(e.role===`assistant`){let t=Vs(e.content),n=e.thinking?.trim();n&&(t+=Vs(n)),e.errorMessage&&(t+=Vs(e.errorMessage));for(let n of e.toolCalls??[])t+=Vs(n.name)+Vs(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(`
17
+ `):e.content;return Vs(e.toolName)+Vs(t)}function J(e){return e.reduce((e,t)=>e+Hs(t),0)}function Us(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}function Ws(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}const Gs=[`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.`],Ks={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function qs(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function Js(e,t,n){return e.map(e=>Ys(e,t,n))}function Ys(e,t,n){let r=new Date(e.timestamp).getTime();if(Xs(e))return{role:`user`,content:e.content,timestamp:r};if(Zs(e)){let i=[],a=e.thinking?.trim();n?.replayThinking&&a&&i.push({type:`thinking`,thinking:a,...n.thinkingSignature?{thinkingSignature:n.thinkingSignature}:{}}),e.content&&i.push({type:`text`,text:e.content});for(let t of e.toolCalls??[])i.push({type:`toolCall`,id:t.id,name:t.name,arguments:t.arguments});return{role:`assistant`,content:i,api:t.api,provider:`openai`,model:t.model,usage:Ks,stopReason:e.stopReason??`stop`,errorMessage:e.errorMessage,timestamp:r}}let i=e;return{role:`toolResult`,toolCallId:i.toolCallId,toolName:i.toolName,content:[{type:`text`,text:Qs(i)}],isError:i.isError,timestamp:r}}function Xs(e){return e.role===`user`}function Zs(e){return e.role===`assistant`}function Qs(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:`,...Gs];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
18
+ `)}const $s=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,"- Any unfinished plan submitted through `update_task`, especially pending and in_progress tasks, current progress, and necessary constraints.",`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- A list of skill names and their locations/paths mentioned or loaded in the compressed content, especially skill_load names and paths`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
19
+ `);async function ec(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=nc(t,r,i,a),u=rc(a),d,f=ce({apiFormat:n.apiFormat,baseUrl:n.baseUrl,apiKey:n.apiKey,defaultModel:n.model,hooks:s,hookCtx:c});for(let e=1;e<=3;e++)try{let e=(await f.chat({system:$s,user:l,temperature:0,maxTokens:u,signal:o})).text.trim();if(!e)throw Error(`LLM summarisation returned empty content`);return e}catch(t){if(t instanceof Error&&t.name===`AbortError`)throw t;d=t,e<3&&await tc(500*e)}throw d}function tc(e){return new Promise(t=>setTimeout(t,e))}function nc(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${sc(t.trim(),ic(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=ac(e,t,n,r),o=oc(t,n,r);for(let[t,n]of e.entries()){if(o<=0){i.push(`[${e.length-t} entries omitted because the summarisation input budget was exhausted]`);break}let r=``;if(n.role===`user`)r=`User: ${sc(n.content,Math.min(a,o))}`;else if(n.role===`assistant`)r=`Assistant:${n.toolCalls&&n.toolCalls.length>0?` [called tools: ${n.toolCalls.map(e=>e.name).join(`, `)}]`:``} ${sc(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?cc(n):n.toolResultRef?[`[tool result persisted] ${n.toolResultRef.toolName} (${n.toolResultRef.originalChars} chars).`,`Full output: ${n.toolResultRef.storagePath}`,n.toolResultRef.preview.trim()?`Preview:\n${n.toolResultRef.preview.trimEnd()}`:``].filter(Boolean).join(`
20
+ `):n.content;r=`Tool(${n.toolName})[${e}]: ${sc(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
21
+ `)}function rc(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function ic(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function ac(e,t,n,r){let i=oc(t,n,r);if(!r||r<=0)return 2e3;let a=rc(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=$s.length+(t?.length??0)+(n?.length??0)+1e3,c=Math.max(1e3,o*4-s);return Math.max(120,Math.min(2e3,i,Math.floor(c/Math.max(1,e.length))))}function oc(e,t,n){if(!n||n<=0)return 1/0;let r=rc(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=$s.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function sc(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function cc(e){let t=lc(e),n=t.name??`<skill-name>`,r=t.path,i=r?`skill_load(name="${n}", skillPath="${r}")`:`skill_load(name="${n}")`;return[`[skill content folded] skill_load result for "${n}" is not a reliable source for future instructions.`,r?`Original path: ${r}`:``,`If this skill is needed later, call ${i} again.`,`Do not summarize, infer, or reconstruct SKILL.md instructions from this history.`].filter(Boolean).join(`
22
+ `)}function lc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=uc(t);if(e.name||e.path)return e}return{}}function uc(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,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Hs(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function fc(e){return mc((await ce({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:_c,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.segments},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}async function pc(e){return hc((await ce({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:vc,user:JSON.stringify({version:1,currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedTurns:e.maxSelectedTurns,turns:e.turns},null,2),temperature:0,timeoutMs:e.llm.timeoutMs,maxTokens:e.llm.maxTokens,signal:e.signal})).text)}function mc(e){let t=gc(e);if(t.version!==1||!Array.isArray(t.selectedSegmentIds))throw Error(`Topic segment selection decision has invalid schema.`);return{version:1,selectedSegmentIds:t.selectedSegmentIds.filter(e=>typeof e==`string`),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function hc(e){let t=gc(e);if(t.version!==1||!Array.isArray(t.selectedTurns))throw Error(`Topic turn selection decision has invalid schema.`);return{version:1,selectedTurns:t.selectedTurns.filter(e=>!!(e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:typeof e.topicLabel==`string`?e.topicLabel.trim():void 0,keywords:Array.isArray(e.keywords)?e.keywords.filter(e=>typeof e==`string`&&e.trim().length>0):void 0})),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function gc(e){let t=e.trim();if(!t)throw Error(`Topic segmentation model returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t;return JSON.parse(r)}[`You maintain SeCom-style conversation segments for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"action":"merge|split","reason":"...","topicLabel":"optional","summary":"...","compressedSummary":"...","keywords":["..."]}`,`Task: compare the active segment with the new user turn.`,`Use action=merge only when the new turn continues the same topic, task, artifact, bug, document, or refinement thread.`,`Use action=split when the new turn starts a different topic.`,`Always provide summary, compressedSummary, and concise keywords for the resulting segment after your decision.`,`Do not answer the user.`].join(`
23
+ `);const _c=[`You select relevant conversation segments for an IM assistant before final turn-level topic classification.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedSegmentIds":["..."],"reason":"...","confidence":"high|medium|low"}`,`Task: choose which prior segments are relevant to the current user message.`,`Relevant includes same task continuation, explicit topic return, reuse of prior artifact, correction, or combining multiple earlier topics.`,`Prefer recall over over-pruning when the user explicitly refers to older topics by name.`,`Do not answer the user.`].join(`
24
+ `),vc=[`You select relevant historical conversation turns for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurns":[{"turnId":"...","summary":"...","topicLabel":"optional","keywords":["..."]}],"reason":"...","confidence":"high|medium|low"}`,`Task: from the provided turns, select any turn that may be relevant to the current user message.`,`This is recall-first. It is better to include possibly relevant turns than to miss a relevant one.`,`Select turns for same task continuation, explicit old-topic return, reuse of prior artifact, corrections, or combinations of multiple earlier topics.`,`For every selected turn, provide a concise reusable summary, an optional topicLabel, and short keywords.`,`Prefer the provided summary/topicLabel fields when they exist; use raw user/assistant content only when needed.`,`Do not answer the user.`].join(`
25
+ `);async function yc(e){let t=wc(e);if(t)try{let e=await G.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(Bc);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function bc(e){let t=wc(e);t&&(await G.mkdir(K.dirname(t),{recursive:!0}),await G.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function xc(e){let t=Tc(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||Ec(t,e)){r.push(e);continue}n.push(Oc(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(Oc(r,n.length+1,!0)),n}function Sc(e,t){let n=Tc(t);if(n.length===0)return[];if(!e||e.length===0)return xc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return xc(t);if(r.length===n.length)return e;let a=e.map(e=>({...e,turnIds:[...e.turnIds],toolNames:[...e.toolNames],keywords:[...e.keywords]})),o=n.slice(r.length);for(let e of o){let t=a[a.length-1];if(t&&Dc(t,e)){a[a.length-1]=Nc(t,e);continue}t&&(t.status=`closed`),a.push(Oc([e],a.length+1,!0))}if(a.length>1){for(let e=0;e<a.length-1;e+=1)a[e]={...a[e],status:`closed`};a[a.length-1]={...a[a.length-1],status:`active`}}return a}function Cc(e,t){if(!e||e.length===0||t.length===0)return e??[];let n=new Map(t.map(e=>[e.turnId,e])),r=!1,i=e.map(e=>{let t=new Map((e.turnMemories??[]).map(e=>[e.turnId,e])),i=!1;for(let r of e.turnIds){let e=n.get(r);if(!e)continue;let a=t.get(r);(!a||a.summary!==e.summary||a.topicLabel!==e.topicLabel||a.keywords.join(`|`)!==e.keywords.join(`|`))&&(t.set(r,e),i=!0)}if(!i)return e;r=!0;let a=[...t.values()].sort((e,t)=>e.turnId.localeCompare(t.turnId)),o=a.find(t=>e.turnIds.includes(t.turnId)),s=[...new Set([...e.keywords,...a.flatMap(e=>e.keywords)])];return{...e,keywords:s,topicLabel:o?.topicLabel??e.topicLabel,turnMemories:a,updatedAt:o?.updatedAt??e.updatedAt}});return r?i:e}function wc(e){if(!(!e.dataDir||!e.sessionId))return K.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function Tc(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,user:a.content,timestamp:a.timestamp,toolNames:[]};continue}if(n){if(n.endIndex=i,a.role===`assistant`){let e=(a.content||a.errorMessage||``).trim();e&&(n.assistant=e);for(let e of a.toolCalls??[])n.toolNames.push(e.name);continue}a.role===`tool_result`&&n.toolNames.push(a.toolName)}}return r(),t.map(e=>({...e,toolNames:[...new Set(e.toolNames)].sort()}))}function Ec(e,t){return Ic(Fc(e.user,e.assistant),Fc(t.user,t.assistant))>0}function Dc(e,t){return Ic(Fc(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),Fc(t.user,t.assistant,t.toolNames.join(` `)))>0}function Oc(e,t,n){return kc(e,t,n)}function kc(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=Ac(e,o),c=zc(r?.summary||s),l=Pc(r?.keywords,c,o),u=zc(r?.compressedSummary||Mc(c,o));return{version:1,segmentId:`segment-${t}`,turnIds:e.map(e=>e.turnId),startTurnId:i.turnId,endTurnId:a.turnId,startIndex:i.startIndex,endIndex:a.endIndex,userSummary:e.map(e=>e.user).join(`
26
26
  `),assistantSummary:e.map(e=>e.assistant).filter(Boolean).join(`
27
- `)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function kc(e,t){return Ac(e.map(e=>e.user.trim()).filter(Boolean).slice(0,2).join(` / `),e.map(e=>e.assistant?.trim()).filter(Boolean).slice(-2).join(` / `)||void 0,t)}function Ac(e,t,n){let r=Lc(e,220),i=t?Lc(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return Rc(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function jc(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return Rc(`Relevant prior segment: ${Lc(e,280)}${n}`)}function Mc(e,t,n){let r=[...new Set([...e.toolNames,...t.toolNames])].sort(),i=`${e.userSummary}\n${t.user}`.trim(),a=[e.assistantSummary,t.assistant].filter(Boolean).join(`
28
- `)||void 0,o=Ac(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:Rc(n?.summary||o),compressedSummary:Rc(n?.compressedSummary||jc(n?.summary||o,r)),keywords:Nc(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Nc(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:Ic(t,n)}function Pc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||n.length>64||/^(.)\1{15,}$/u.test(n)||t.add(n)}return t}function Fc(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Ic(e,t){let n=new Set([`the`,`and`,`for`,`with`,`this`,`that`,`from`,`user`,`intents`,`outcomes`,`tools`,`prior`,`segment`,`relevant`,`继续`,`刚才`,`这个`]),r=new Map;for(let i of Pc(e,t.join(` `)))n.has(i)||r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,8).map(([e])=>e)}function Lc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Rc(e){return e.replace(/\s+/g,` `).trim()}function zc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.segmentId==`string`&&Array.isArray(t.turnIds)&&typeof t.startTurnId==`string`&&typeof t.endTurnId==`string`&&typeof t.startIndex==`number`&&typeof t.endIndex==`number`&&typeof t.userSummary==`string`&&typeof t.summary==`string`&&typeof t.compressedSummary==`string`&&Array.isArray(t.keywords)&&Array.isArray(t.toolNames)&&(t.turnMemories===void 0||Array.isArray(t.turnMemories)&&t.turnMemories.every(e=>!!e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`&&Array.isArray(e.keywords)&&typeof e.updatedAt==`string`))&&(t.status===`active`||t.status===`closed`)&&typeof t.updatedAt==`string`}function Bc(e){let t=Wc(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Gc(t,n,r,e.segments.length,e.vectorScores)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.segment.startIndex-e.segment.startIndex:t.score-e.score:e.forced?-1:1).slice(0,e.maxSegments)}function Vc(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function Hc(e){let t=new Set(e.selectedTurnIds),n=new Set(e.recentProtectedTurnIds),r=[];for(let i of e.segments){let a=i.turnIds.some(e=>t.has(e)),o=i.turnIds.some(e=>n.has(e));!a||o||i.status!==`closed`||r.push({role:`assistant`,content:Uc(i.compressedSummary),timestamp:e.timestamp})}return r}function Uc(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function Wc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Gc(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=Wc(t.summary,t.compressedSummary,t.keywords.join(` `),t.topicLabel,a),s=0;for(let t of e)o.has(t)&&(s+=1);let c=Math.max(0,i?.get(t.segmentId)??0),l=(n+1)/Math.max(r,1);return c*30+s*10+l}const Kc=`Xenova/bge-small-zh-v1.5`;let qc,Jc;const Yc=new Map;async function Xc(e,t){if(e.length===0)return W.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=tl(t),i=r.path;W.info(`topic segmentation embedding started`,{provider:`transformers`,model:Kc,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await $c({embeddingModelDir:i}),a=[],o=0,s=0;for(let n of e){let e=n.trim();if(!e){a.push([]),s+=1;continue}let r=`${i}\0${e}`,c=Yc.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Yc.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return W.info(`topic segmentation embedding completed`,{provider:`transformers`,model:Kc,textCount:e.length,embeddedCount:a.filter(e=>e.length>0).length,emptyTextCount:s,cacheHitCount:o,dims:c?.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n}),a}catch(t){throw W.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:Kc,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function Zc(e,t){let[n]=await Xc([e],t);return n??[]}function Qc(){return Kc}async function $c(e){let t=tl(e).path;return(!qc||Jc!==t)&&(Jc=t,qc=el(t)),qc}async function el(e){let t=Date.now();W.info(`topic segmentation embedding extractor load started`,{model:Kc,modelDir:e,allowRemoteModels:!1});try{let{env:n,pipeline:r}=await import(`@huggingface/transformers`);n.allowRemoteModels=!1,n.localModelPath=e;let i=await r(`feature-extraction`,Kc,{dtype:`q8`});return W.info(`topic segmentation embedding extractor load completed`,{model:Kc,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw W.warn(`topic segmentation embedding extractor load failed`,{model:Kc,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function tl(e){let t=e?.embeddingModelDir?.trim();if(t)return{path:t,source:`config`};let n=process.env.AIMAX_TOPIC_SEGMENTATION_MODEL_DIR?.trim();if(n)return{path:n,source:`env`};let r=K.dirname(en(import.meta.url)),i=K.resolve(r,`../../../../../model`);if(Wt.existsSync(i))return{path:i,source:`repo_candidate`};let a=K.resolve(process.cwd(),`model`);return Wt.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const nl=`topic_segments_vec`,rl=`topic_segments_meta`,il=`topic_segment_embedding_cache`;async function al(e){let t=Date.now(),n=sl(e);if(!n){W.info(`topic segment vector store sync skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir});return}W.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await G.mkdir(K.dirname(n),{recursive:!0});let r=qe(n,{allowExtension:!0});try{let i=await ll(r);W.info(`topic segment vector store ready`,{sessionId:e.sessionId,dbPath:n,vectorAvailable:i.vectorAvailable,vectorDims:i.vectorDims,embeddingModelDir:e.embeddingModelDir});let a=r.prepare(`SELECT segment_id, content_hash FROM ${rl}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=Qc(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=We(cl(e));return o.get(e.segmentId)!==t});W.info(`topic segment vector store embedding plan`,{sessionId:e.sessionId,dbPath:n,existingSegmentCount:a.length,segmentCount:e.segments.length,toEmbedCount:l.length,embeddingModelDir:e.embeddingModelDir,embeddingModel:s});let u=l.length>0?await Xc(l.map(e=>cl(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=cl(t),n=We(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:ml(r,t.segmentId);fl(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(pl(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(dl(r,i,o.length),r.prepare(`DELETE FROM ${nl} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${nl} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,bl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${nl} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${rl} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${il} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${nl} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),W.info(`topic segment vector store sync completed`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,toEmbedCount:l.length,embeddedCount:u.filter(e=>e.length>0).length,vectorAvailable:i.vectorAvailable,vectorDims:i.vectorDims,durationMs:Date.now()-t})}catch(e){throw r.exec(`ROLLBACK`),e}}catch(r){throw W.warn(`topic segment vector store sync failed`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)}),r}finally{r.close()}}async function ol(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:e.query.trim()?`non_positive_limit`:`empty_query`,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;let n=sl(e);if(!n)return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;try{await G.access(n)}catch{return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}W.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await _l(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return W.warn(`topic segment vector search degraded`,{sessionId:e.sessionId,reason:`empty_query_embedding`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t}),new Map;let i=qe(n,{allowExtension:!0});try{let a=await ll(i),o=Qc(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?hl(i,o,r,e.limit):gl(i,o,r,e.limit);return W.info(`topic segment vector search completed`,{sessionId:e.sessionId,dbPath:n,strategy:s,resultCount:c.length,queryDims:r.length,vectorAvailable:a.vectorAvailable,vectorDims:a.vectorDims,durationMs:Date.now()-t}),new Map(c.map(e=>[e.segment_id,Math.max(0,e.score??0)]))}catch(r){throw W.warn(`topic segment vector search failed`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)}),r}finally{i.close()}}function sl(e){if(!(!e.dataDir||!e.sessionId))return K.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function cl(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
29
- `)}async function ll(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${rl} (\n segment_id TEXT PRIMARY KEY,\n version INTEGER NOT NULL,\n content_text TEXT NOT NULL,\n content_hash TEXT NOT NULL,\n embedding_model TEXT,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE TABLE IF NOT EXISTS ${il} (\n segment_id TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n embedding_model TEXT NOT NULL,\n embedding TEXT NOT NULL,\n dims INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${rl}_hash ON ${rl}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${il}_hash ON ${il}(content_hash)`),{vectorAvailable:(await He({db:e})).ok,vectorDims:ul(e)}}function ul(e){let t=e.prepare(`SELECT dims FROM ${il} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function dl(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${nl}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${nl} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function fl(e,t){e.prepare(`INSERT INTO ${rl} (\n segment_id, version, content_text, content_hash, embedding_model, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n version = excluded.version,\n content_text = excluded.content_text,\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n updated_at = excluded.updated_at`).run(t.segment.segmentId,1,t.contentText,t.contentHash,t.embeddingModel,t.segment.updatedAt)}function pl(e,t){e.prepare(`INSERT INTO ${il} (\n segment_id, content_hash, embedding_model, embedding, dims, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n embedding = excluded.embedding,\n dims = excluded.dims,\n updated_at = excluded.updated_at`).run(t.segmentId,t.contentHash,t.embeddingModel,JSON.stringify(t.embedding),t.embedding.length,new Date().toISOString())}function ml(e,t){let n=e.prepare(`SELECT embedding FROM ${il} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function hl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${nl} v\n JOIN ${rl} m ON m.segment_id = v.segment_id\n WHERE m.embedding_model = ?\n ORDER BY vec_distance_cosine(v.embedding, ?) ASC\n LIMIT ?`).all(bl(n),t,bl(n),r)}function gl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${il} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:yl(n,vl(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function _l(e,t){try{return await Zc(e,t)}catch(e){return W.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function vl(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function yl(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a]??0,s=t[a]??0;n+=o*s,r+=o*o,i+=s*s}return r<=0||i<=0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function bl(e){return Buffer.from(new Float32Array(e).buffer)}const xl=8e3,Sl=new Map;function Cl(e){return{enabled:e?.enabled!==!1,embeddingModelDir:zl(e?.embeddingModelDir),minUserTurns:e?.minUserTurns??4,minEstimatedTokens:e?.minEstimatedTokens??4e3,recentProtectedTurnCount:e?.recentProtectedTurnCount??2,maxCandidates:e?.maxCandidates??40,maxSelectedTurns:e?.maxSelectedTurns??8,maxShortlistCandidates:e?.maxShortlistCandidates??12,maxShortlistSegments:e?.maxShortlistSegments??6,maxCandidateUserChars:e?.maxCandidateUserChars??600,maxCandidateAssistantChars:e?.maxCandidateAssistantChars??1e3,timeoutMs:e?.timeoutMs??2e4,maxTokens:e?.maxTokens??4096}}function wl(e){let t=Al(e.entries),n=new Map(e.candidates.map(e=>[e.turnId,e])),r=new Set(e.decision.selectedTurnIds),i=e.recentProtectedTurnCount>0?t.slice(-e.recentProtectedTurnCount):[],a=i.map(e=>e.turnId);for(let e of i)r.add(e.turnId);let o=new Set;if(e.useCompressedSegmentMemory!==!1&&e.segmentRecords)for(let t of e.segmentRecords){let e=t.turnIds.some(e=>r.has(e)),n=t.turnIds.some(e=>a.includes(e));if(!(!e||n||t.status!==`closed`))for(let e of t.turnIds)o.add(e)}let s=[],c=[],l=[],u=[];for(let e of t){if(!r.has(e.turnId)){l.push(e.turnId),u.push(Pl(e,n.get(e.turnId)));continue}s.push({turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex}),!o.has(e.turnId)&&c.push(...e.entries)}return{entries:[...e.useCompressedSegmentMemory!==!1&&e.segmentRecords?Hc({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function Tl(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=Bl(e.currentUserMessage),n=new Set(e.recentProtectedTurnCount>0?e.candidates.slice(-e.recentProtectedTurnCount).map(e=>e.turnId):[]);return e.candidates.map((r,i)=>({candidate:r,index:i,forced:n.has(r.turnId),score:Hl(t,r,i,e.candidates.length)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.index-e.index:t.score-e.score:e.forced?-1:1).slice(0,e.maxShortlist).map(e=>e.candidate).sort((e,t)=>e.startIndex-t.startIndex)}async function El(e){let t=Cl(e.config),n=()=>Gl({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){W.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){W.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){W.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=Al(e.entries),i=J(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){W.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>jl(e,t)),o=e.llm.flashModel||e.llm.model,s=await Dl({entries:e.entries,candidates:a,pendingUserMessage:e.pendingUserMessage,config:t,llm:{apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,model:o,timeoutMs:t.timeoutMs,maxTokens:t.maxTokens},dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:t.embeddingModelDir,signal:e.signal}),c=s.segmentRecords,l=new Set(a.map(e=>e.turnId)),u=new Date().toISOString(),d=Date.now();W.info(`topic segmentation classify started`,Gl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Nl({currentUserMessage:e.pendingUserMessage,allCandidates:a,shortlistedCandidates:s.candidates,selectedSegmentIds:s.selectedSegmentIds,supplementalTurnIds:s.supplementalTurnIds,segmentRecords:c,recentProtectedTurnCount:t.recentProtectedTurnCount,maxSelectedTurns:t.maxSelectedTurns}),p=f.selectedTurnIds.filter(e=>!l.has(e));if(p.length>0)throw Error(`Local topic segmentation returned unknown turn ids: ${p.join(`, `)}`);let m=Date.now()-d,h=wl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=Ml({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:J(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await Il(e,g),W.info(`topic segmentation classify succeeded`,{...Gl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}),durationMs:m,selectedTurnCount:f.selectedTurnIds.length,confidence:f.confidence,tokenEstimateAfter:g.tokenEstimate?.after,droppedTurnCount:h.droppedTurnIds.length,droppedTurnPreviews:h.droppedTurns.length>0?JSON.stringify(h.droppedTurns):void 0}),{entries:h.entries,audit:g}}async function Dl(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await Ol({entries:e.entries,llm:e.llm,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,signal:e.signal}),n=e.config.recentProtectedTurnCount>0?e.candidates.slice(-e.config.recentProtectedTurnCount).map(e=>e.turnId):[],r=Date.now(),i=[],a=e.candidates,o=t,s=[],c=[];if(t){let o=await ol({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,query:e.pendingUserMessage,limit:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2)}),l=Bc({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=ql(l,e.config.maxShortlistSegments),d=kl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:xl});if(d&&$l({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await nu({currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,retrieved:l,llm:{...e.llm,timeoutMs:d},maxSelectedSegments:e.config.maxShortlistSegments,signal:e.signal});t.length>0&&(u=t)}s=u,i=u.map(e=>e.segment.segmentId),a=Vc({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Jl({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:xl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),ru({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=Ql(a,l.selectedCandidates),d=Tl({currentUserMessage:e.pendingUserMessage,candidates:u.length>0?u:a,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxShortlist:Math.min(e.config.maxCandidates,e.config.maxShortlistCandidates)});return{candidates:d.length>0?d:e.candidates,selectedSegmentIds:i,supplementalTurnIds:l.selectedTurnIds,segmentRecords:o}}async function Ol(e){W.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await vc(e);if(!t){let t=bc(e.entries);if(t.length===0){W.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),ru({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),W.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}W.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=xc(t,e.entries);return n.length>0&&(await yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),ru({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),W.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function kl(e){let t=Math.max(0,(e.nowMs??Date.now())-e.budgetStartedAtMs),n=Math.max(0,e.budgetMs-t);if(!(n<=0))return Math.min(e.requestTimeoutMs,n)}function Al(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,entries:[a],user:a.content,timestamp:a.timestamp};continue}n&&(n.entries.push(a),n.endIndex=i)}return r(),t}function jl(e,t){let n=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim()),r=new Set,i=!1;for(let t of e.entries){if(t.role===`assistant`){for(let e of t.toolCalls??[])r.add(e.name);t.stopReason===`error`&&(i=!0);continue}Wl(t)&&(r.add(t.toolName),t.isError&&(i=!0))}return{turnId:e.turnId,startIndex:e.startIndex,endIndex:n?e.entries.indexOf(n)+e.startIndex:e.endIndex,user:Ll(e.user,t.maxCandidateUserChars),assistant:n?Ll((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function Ml(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:Ll(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,shortlistCount:e.shortlistedCandidates.candidates.length,selectedSegmentIds:e.selectedSegmentIds,selectedTurnIds:e.decision.selectedTurnIds,selectedRanges:e.projected.selectedRanges,forcedKeep:{recentTurnIds:e.projected.recentTurnIds},droppedTurnIds:e.projected.droppedTurnIds,droppedTurns:e.projected.droppedTurns,confidence:e.decision.confidence,reason:e.decision.reason,tokenEstimate:{before:e.tokenEstimateBefore,after:e.tokenEstimateAfter}}}function Nl(e){let t=new Set(e.allCandidates.map(e=>e.turnId)),n=new Set;if(e.segmentRecords&&e.selectedSegmentIds.length>0){let r=e.segmentRecords.filter(t=>e.selectedSegmentIds.includes(t.segmentId));for(let e of r)for(let r of e.turnIds)t.has(r)&&n.add(r)}for(let r of e.supplementalTurnIds)t.has(r)&&n.add(r);if(n.size===0){let t=Bl(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:Hl(t,n,r,e.shortlistedCandidates.length)})).sort((e,t)=>t.score-e.score),i=r[0]?.score??0,a=Math.max(8,i>=8?i*.7:1/0);for(let t of r)if(!(t.score<a)&&(n.add(t.candidate.turnId),n.size>=e.maxSelectedTurns))break}return{version:1,selectedTurnIds:[...n].slice(0,e.maxSelectedTurns),reason:e.selectedSegmentIds.length>0||e.supplementalTurnIds.length>0?`local segment retrieval matched prior segments`:`local candidate scoring matched recent turns`,confidence:`high`}}function Pl(e,t){let n=t?.assistant??Fl(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:Rl(t?.user??e.user,50),assistantPreview:n?Rl(n,50):void 0}}function Fl(e){let t=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim());return t?(t.content||t.errorMessage||``).trim():void 0}async function Il(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await G.mkdir(n,{recursive:!0}),await G.appendFile(K.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function Ll(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Rl(e,t){return[...e].slice(0,t).join(``)}function zl(e){return e?.trim()||void 0}function Bl(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Vl(e){return[...Bl(e)].slice(0,8)}function Hl(e,t,n,r){let i=Ul(e,Bl(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Ul(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Wl(e){return e.role===`tool_result`}function Gl(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Kl(e.params.llm.baseUrl),timeoutMs:e.config.timeoutMs,maxTokens:e.config.maxTokens,hasEmbeddingModelDir:!!e.config.embeddingModelDir,embeddingModelDir:e.config.embeddingModelDir,minUserTurns:e.config.minUserTurns,minEstimatedTokens:e.config.minEstimatedTokens,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxCandidates:e.config.maxCandidates,maxSelectedTurns:e.config.maxSelectedTurns,transcriptEntryCount:e.params.fullTranscript.length,workingEntryCount:e.params.entries.length,pendingUserMessageChars:e.params.pendingUserMessage?.length,candidateCount:e.candidates?.length,shortlistCount:e.shortlistedCandidates?.length,tokenEstimateBefore:e.tokenEstimateBefore,extraPromptChars:e.extraPromptChars}}function Kl(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function ql(e,t){if(e.length===0)return[];let n=e.slice().sort((e,t)=>t.score-e.score),r=n[0]?.score??0,i=Math.max(8,r>=8?r*.7:1/0);return n.filter(e=>e.forced||e.score>=i).slice(0,t)}async function Jl(e){if(!Yl(e))return{selectedCandidates:[],selectedTurnIds:[]};let t=new Set(e.segmentFilteredCandidates.map(e=>e.turnId)),n=new Set(e.recentProtectedTurnIds),r=e.allCandidates.filter(e=>!t.has(e.turnId)&&!n.has(e.turnId));if(r.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let i=Xl(Zl(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=kl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await fc({currentUserMessage:e.currentUserMessage,turns:i,maxSelectedTurns:e.config.maxSelectedTurns,recentProtectedTurnIds:e.recentProtectedTurnIds,llm:{...e.llm,timeoutMs:a},signal:e.signal}),n=[...new Set(t.selectedTurns.map(e=>e.turnId))].filter(e=>r.some(t=>t.turnId===e));if(n.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let o=r.filter(e=>n.includes(e.turnId)),s=t.selectedTurns.filter(e=>n.includes(e.turnId)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:e.topicLabel?.trim()||void 0,keywords:(e.keywords??Vl(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?Sc(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Yl(e){let t=e.selectedSegments.filter(e=>!e.forced);return eu(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:tu(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Xl(e,t){let n=new Map;for(let e of t??[])for(let t of e.turnIds)n.set(t,e);return e.map(e=>{let t=n.get(e.turnId),r=t?.turnMemories?.find(t=>t.turnId===e.turnId);return{turnId:e.turnId,user:e.user,assistant:e.assistant,toolNames:e.toolNames,hasErrors:e.hasErrors,summary:r?.summary??t?.summary,topicLabel:r?.topicLabel??t?.topicLabel,keywords:r?.keywords??t?.keywords}})}function Zl(e,t,n){let r=Math.max(n.length,1),i=Bl(t);return e.map(e=>({candidate:e,score:Hl(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function Ql(...e){let t=new Map;for(let n of e)for(let e of n)t.has(e.turnId)||t.set(e.turnId,e);return[...t.values()].sort((e,t)=>e.startIndex-t.startIndex)}function $l(e){if(e.retrieved.length<2||!eu(e.currentUserMessage))return!1;let t=new Set(e.selected.map(e=>e.segment.segmentId));if(e.selected.filter(e=>!e.forced).length>=2||e.retrieved.filter(e=>!e.forced).length<2)return!1;let n=new Set(e.selected.flatMap(e=>e.segment.turnIds));return e.recentProtectedTurnIds.length>0&&[...n].every(t=>e.recentProtectedTurnIds.includes(t))||t.size<2}function eu(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function tu(e){let t=e.toLowerCase();return/(回到|刚才|前面|之前|上次|那个|前一个|最早|继续刚才)/u.test(t)?!0:/\b(back to|earlier|previous|that earlier|the earlier)\b/i.test(t)}async function nu(e){try{let t=await dc({currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.retrieved.map(e=>({segmentId:e.segment.segmentId,turnIds:e.segment.turnIds,summary:e.segment.summary,compressedSummary:e.segment.compressedSummary,keywords:e.segment.keywords,toolNames:e.segment.toolNames,topicLabel:e.segment.topicLabel})),llm:e.llm,signal:e.signal}),n=new Set(t.selectedSegmentIds);return n.size===0?[]:e.retrieved.filter(e=>n.has(e.segment.segmentId))}catch{return[]}}function ru(e){let t=iu(e);if(!t||Sl.has(t)){W.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}W.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=al(e).catch(t=>{W.warn(`topic segment vector sync failed`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length,error:t instanceof Error?t.message:String(t)})}).finally(()=>{Sl.delete(t)});Sl.set(t,n)}function iu(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`You classify conversation topic relevance for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurnIds":["..."],"reason":"...","confidence":"high|medium|low","currentTopicLabel":"optional"}`,`Task: select historical user turns relevant to the current user message.`,`Relevant includes same task continuation, follow-up, correction, reuse of previous artifact, explicit reference, or ambiguous references like 'this', 'above', 'just now'.`,`Do not answer the user. Do not rewrite the user message.`,`Do not select unrelated old topics.`,`Compaction entries are not candidates and have no special retention rule.`].join(`
30
- `);const au=[`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 ou(e){let t=_(e.dataDir,e.sessionId,e),n=new Map,r=new Map,i=[],a=[],o=[],c,l,u=0,d,f,p=await du(t);for(let e of p.readStates)n.set(su(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 G.mkdir(K.dirname(t),{recursive:!0});let p=e.encryptSessions??!1;await L(t,JSON.stringify(s,null,2),p)};return{async findReusableRead(e,t,r){let i=su(e,t,r),a=n.get(i);if(!a)return null;let o=await lu(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:uu(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await lu(e.path)??Date.now()};return n.set(su(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())cu(i.path)===cu(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=K.join(o,c);await G.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await L(l,t.content,u);let p=K.relative(e.dataDir,l).split(K.sep).join(`/`),h=hu(t.content,a),g={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:p,preview:h,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(g.toolCallId,g),i.push({toolCallId:g.toolCallId,toolName:g.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:h.length,strategy:`persist`,createdAt:g.createdAt}),d=g.createdAt,f=`L2`,await m(),{content:mu(g),reference:g}},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 gu(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 su(e,t,n){return`${cu(e)}::${t??``}::${n??``}`}function cu(e){return K.normalize(e)}async function lu(e){try{return(await G.stat(e)).mtimeMs}catch{return null}}function uu(e){return Ft(`sha1`).update(e).digest(`hex`)}async function du(e){try{let t=await o(e);if(t===null)return fu();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?fu():{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:pu(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 fu()}}function fu(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function pu(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 mu(e){let t=e.preview.length<e.originalChars?`
31
- ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...au,`Preview:`,e.preview+t].join(`
32
- `)}function hu(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
33
- `),r=n>t*.5?n:t;return e.slice(0,r)}async function gu(e,t,n,r){let i=l(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await L(i,JSON.stringify(n,null,2),a)}const _u=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function vu(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,topicSegmentation:c,signal:l,hooks:u,hookCtx:d,contextStore:f,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g,channel:_,isSubagent:v,entriesToMessagesOptions:y}=e,b,x=Mu(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=Us(Hs(S,a)),T=[],E=(await El({entries:w,fullTranscript:t,pendingUserMessage:s,llm:i,config:c,sessionId:m,dataDir:p,sessionStoreName:h,sessionPathScope:g,channel:_,isSubagent:v,signal:l}).catch(e=>{W.warn(`topic segmentation failed; falling back to repaired history`,{sessionId:m,channel:_,isSubagent:!!v,error:e instanceof Error?e.message:String(e)})}))?.entries??w;E=await bu({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await xu({entries:E,contextStore:f,compactionEvents:T});let D=await Su({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g});if(E=D.entries,b=wu(b,D.summaries),f&&(b=await yu({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:qs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let O=f?.getSnapshot(),k=Math.max(1e3,Math.floor(r*.7)),A=Nu({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:O?.compaction.modelUsage}).projectedInputTokens>=k,j=O?.compaction.consecutiveAutocompactFailures??0;if(!A||j>=3)return{messages:qs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let{toKeep:M,toSummarise:N}=uc(E,r);if(N.length===0)return{messages:qs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let P=new Date().toISOString();try{let e=O?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await $s({entries:N,llm:i,previousSummary:b,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d}),a={role:`compaction`,content:t,keptCount:M.length,droppedCount:N.length,timestamp:P};return await f?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:P}),T.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${N.length} entries with session memory`:`Autocompact summarised ${N.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,J(N)),affectedEntries:N.length,snapshotVersion:2}),{messages:qs(Us(M),n,y),priorSummary:t,compactionEntry:a,stats:{originalCount:C,keptCount:M.length,estimatedTokens:J(M),compacted:!0},compactionEvents:T}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:P}),{messages:qs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:[...T,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function yu(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=J(t),u=i.getSnapshot().compaction.sessionMemory,d=!u&&l>=8e3,f=!!u&&l>=(u?.tokenEstimate??0)+15e3&&ju(t)>=3;if(!d&&!f)return Tu(n,u?.summary);let p=await $s({entries:t,llm:r,previousSummary:Tu(n,u?.summary),instructions:[`Produce a durable session memory for future compaction and resume.`,`If skill_load results are present, do not restate or reconstruct SKILL.md instructions.`,`Record only that the skill was loaded and that it must be reloaded with skill_load if its full content is not visible.`].join(` `),contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}),m={version:1,summary:p,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:l,trigger:d?`threshold`:`autocompact`};return await i.setSessionMemory(m),p}async function bu(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Eu).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(!Eu(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=Du(n)?Ou(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
34
- `);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}),Us(l.reverse())}async function xu(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(!Eu(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=Du(r)?Ou(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(`
35
- `);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}),bu({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Su(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{entries:t,summaries:[]};let u=l[l.length-2]??t.length,d=[],f=[],p=0,m=0,h=0;for(;p<t.length;){if(p>=u||t[p]?.role===`user`){d.push(t[p]),p+=1;continue}let e=p;for(;p<u&&t[p]?.role!==`user`;)p+=1;let r=t.slice(e,p),o=r.filter(Eu).filter(e=>_u.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=Cu(r,o),g=new Date().toISOString();f.push(l),m+=r.length,h+=Math.max(0,Math.floor(J(r)-Math.ceil(l.length/4)));let _={id:Lt(),layer:`L5`,startEntryIndex:e,endEntryIndex:p-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:h,createdAt:g};await n?.recordCollapse(_),i&&a&&await Pu(i,a,_,c)}return m>0&&r.push({type:`compaction`,reason:`Collapsed ${m} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:h,affectedEntries:m,snapshotVersion:2}),{entries:d,summaries:f}}function Cu(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(`
27
+ `)||void 0,summary:c,compressedSummary:u,keywords:l,toolNames:o,topicLabel:r?.topicLabel,turnMemories:void 0,status:n?`active`:`closed`,updatedAt:a.timestamp??new Date().toISOString()}}function Ac(e,t){return jc(e.map(e=>e.user.trim()).filter(Boolean).slice(0,2).join(` / `),e.map(e=>e.assistant?.trim()).filter(Boolean).slice(-2).join(` / `)||void 0,t)}function jc(e,t,n){let r=Rc(e,220),i=t?Rc(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return zc(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function Mc(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return zc(`Relevant prior segment: ${Rc(e,280)}${n}`)}function Nc(e,t,n){let r=[...new Set([...e.toolNames,...t.toolNames])].sort(),i=`${e.userSummary}\n${t.user}`.trim(),a=[e.assistantSummary,t.assistant].filter(Boolean).join(`
28
+ `)||void 0,o=jc(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:zc(n?.summary||o),compressedSummary:zc(n?.compressedSummary||Mc(n?.summary||o,r)),keywords:Pc(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Pc(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:Lc(t,n)}function Fc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||n.length>64||/^(.)\1{15,}$/u.test(n)||t.add(n)}return t}function Ic(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Lc(e,t){let n=new Set([`the`,`and`,`for`,`with`,`this`,`that`,`from`,`user`,`intents`,`outcomes`,`tools`,`prior`,`segment`,`relevant`,`继续`,`刚才`,`这个`]),r=new Map;for(let i of Fc(e,t.join(` `)))n.has(i)||r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,8).map(([e])=>e)}function Rc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function zc(e){return e.replace(/\s+/g,` `).trim()}function Bc(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.segmentId==`string`&&Array.isArray(t.turnIds)&&typeof t.startTurnId==`string`&&typeof t.endTurnId==`string`&&typeof t.startIndex==`number`&&typeof t.endIndex==`number`&&typeof t.userSummary==`string`&&typeof t.summary==`string`&&typeof t.compressedSummary==`string`&&Array.isArray(t.keywords)&&Array.isArray(t.toolNames)&&(t.turnMemories===void 0||Array.isArray(t.turnMemories)&&t.turnMemories.every(e=>!!e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`&&Array.isArray(e.keywords)&&typeof e.updatedAt==`string`))&&(t.status===`active`||t.status===`closed`)&&typeof t.updatedAt==`string`}function Vc(e){let t=Gc(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Kc(t,n,r,e.segments.length,e.vectorScores)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.segment.startIndex-e.segment.startIndex:t.score-e.score:e.forced?-1:1).slice(0,e.maxSegments)}function Hc(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function Uc(e){let t=new Set(e.selectedTurnIds),n=new Set(e.recentProtectedTurnIds),r=[];for(let i of e.segments){let a=i.turnIds.some(e=>t.has(e)),o=i.turnIds.some(e=>n.has(e));!a||o||i.status!==`closed`||r.push({role:`assistant`,content:Wc(i.compressedSummary),timestamp:e.timestamp})}return r}function Wc(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function Gc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Kc(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=Gc(t.summary,t.compressedSummary,t.keywords.join(` `),t.topicLabel,a),s=0;for(let t of e)o.has(t)&&(s+=1);let c=Math.max(0,i?.get(t.segmentId)??0),l=(n+1)/Math.max(r,1);return c*30+s*10+l}const qc=`Xenova/bge-small-zh-v1.5`;let Jc,Yc;const Xc=new Map;async function Zc(e,t){if(e.length===0)return W.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=nl(t),i=r.path;W.info(`topic segmentation embedding started`,{provider:`transformers`,model:qc,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await el({embeddingModelDir:i}),a=[],o=0,s=0;for(let n of e){let e=n.trim();if(!e){a.push([]),s+=1;continue}let r=`${i}\0${e}`,c=Xc.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Xc.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return W.info(`topic segmentation embedding completed`,{provider:`transformers`,model:qc,textCount:e.length,embeddedCount:a.filter(e=>e.length>0).length,emptyTextCount:s,cacheHitCount:o,dims:c?.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n}),a}catch(t){throw W.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:qc,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function Qc(e,t){let[n]=await Zc([e],t);return n??[]}function $c(){return qc}async function el(e){let t=nl(e).path;return(!Jc||Yc!==t)&&(Yc=t,Jc=tl(t)),Jc}async function tl(e){let t=Date.now();W.info(`topic segmentation embedding extractor load started`,{model:qc,modelDir:e,allowRemoteModels:!1});try{let{env:n,pipeline:r}=await import(`@huggingface/transformers`);n.allowRemoteModels=!1,n.localModelPath=e;let i=await r(`feature-extraction`,qc,{dtype:`q8`});return W.info(`topic segmentation embedding extractor load completed`,{model:qc,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw W.warn(`topic segmentation embedding extractor load failed`,{model:qc,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function nl(e){let t=e?.embeddingModelDir?.trim();if(t)return{path:t,source:`config`};let n=process.env.AIMAX_TOPIC_SEGMENTATION_MODEL_DIR?.trim();if(n)return{path:n,source:`env`};let r=K.dirname(en(import.meta.url)),i=K.resolve(r,`../../../../../model`);if(Wt.existsSync(i))return{path:i,source:`repo_candidate`};let a=K.resolve(process.cwd(),`model`);return Wt.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const rl=`topic_segments_vec`,il=`topic_segments_meta`,al=`topic_segment_embedding_cache`;async function ol(e){let t=Date.now(),n=cl(e);if(!n){W.info(`topic segment vector store sync skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir});return}W.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await G.mkdir(K.dirname(n),{recursive:!0});let r=qe(n,{allowExtension:!0});try{let i=await ul(r);W.info(`topic segment vector store ready`,{sessionId:e.sessionId,dbPath:n,vectorAvailable:i.vectorAvailable,vectorDims:i.vectorDims,embeddingModelDir:e.embeddingModelDir});let a=r.prepare(`SELECT segment_id, content_hash FROM ${il}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=$c(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=We(ll(e));return o.get(e.segmentId)!==t});W.info(`topic segment vector store embedding plan`,{sessionId:e.sessionId,dbPath:n,existingSegmentCount:a.length,segmentCount:e.segments.length,toEmbedCount:l.length,embeddingModelDir:e.embeddingModelDir,embeddingModel:s});let u=l.length>0?await Zc(l.map(e=>ll(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=ll(t),n=We(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:hl(r,t.segmentId);pl(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(ml(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(fl(r,i,o.length),r.prepare(`DELETE FROM ${rl} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${rl} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,xl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${rl} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${il} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${al} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${rl} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),W.info(`topic segment vector store sync completed`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,toEmbedCount:l.length,embeddedCount:u.filter(e=>e.length>0).length,vectorAvailable:i.vectorAvailable,vectorDims:i.vectorDims,durationMs:Date.now()-t})}catch(e){throw r.exec(`ROLLBACK`),e}}catch(r){throw W.warn(`topic segment vector store sync failed`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)}),r}finally{r.close()}}async function sl(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:e.query.trim()?`non_positive_limit`:`empty_query`,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;let n=cl(e);if(!n)return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_store_path`,hasDataDir:!!e.dataDir,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map;try{await G.access(n)}catch{return W.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}W.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await vl(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return W.warn(`topic segment vector search degraded`,{sessionId:e.sessionId,reason:`empty_query_embedding`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t}),new Map;let i=qe(n,{allowExtension:!0});try{let a=await ul(i),o=$c(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?gl(i,o,r,e.limit):_l(i,o,r,e.limit);return W.info(`topic segment vector search completed`,{sessionId:e.sessionId,dbPath:n,strategy:s,resultCount:c.length,queryDims:r.length,vectorAvailable:a.vectorAvailable,vectorDims:a.vectorDims,durationMs:Date.now()-t}),new Map(c.map(e=>[e.segment_id,Math.max(0,e.score??0)]))}catch(r){throw W.warn(`topic segment vector search failed`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir,durationMs:Date.now()-t,error:r instanceof Error?r.message:String(r)}),r}finally{i.close()}}function cl(e){if(!(!e.dataDir||!e.sessionId))return K.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function ll(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
29
+ `)}async function ul(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${il} (\n segment_id TEXT PRIMARY KEY,\n version INTEGER NOT NULL,\n content_text TEXT NOT NULL,\n content_hash TEXT NOT NULL,\n embedding_model TEXT,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE TABLE IF NOT EXISTS ${al} (\n segment_id TEXT PRIMARY KEY,\n content_hash TEXT NOT NULL,\n embedding_model TEXT NOT NULL,\n embedding TEXT NOT NULL,\n dims INTEGER NOT NULL,\n updated_at TEXT NOT NULL\n)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${il}_hash ON ${il}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${al}_hash ON ${al}(content_hash)`),{vectorAvailable:(await He({db:e})).ok,vectorDims:dl(e)}}function dl(e){let t=e.prepare(`SELECT dims FROM ${al} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function fl(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${rl}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${rl} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function pl(e,t){e.prepare(`INSERT INTO ${il} (\n segment_id, version, content_text, content_hash, embedding_model, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n version = excluded.version,\n content_text = excluded.content_text,\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n updated_at = excluded.updated_at`).run(t.segment.segmentId,1,t.contentText,t.contentHash,t.embeddingModel,t.segment.updatedAt)}function ml(e,t){e.prepare(`INSERT INTO ${al} (\n segment_id, content_hash, embedding_model, embedding, dims, updated_at\n) VALUES (?, ?, ?, ?, ?, ?)\nON CONFLICT(segment_id) DO UPDATE SET\n content_hash = excluded.content_hash,\n embedding_model = excluded.embedding_model,\n embedding = excluded.embedding,\n dims = excluded.dims,\n updated_at = excluded.updated_at`).run(t.segmentId,t.contentHash,t.embeddingModel,JSON.stringify(t.embedding),t.embedding.length,new Date().toISOString())}function hl(e,t){let n=e.prepare(`SELECT embedding FROM ${al} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function gl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${rl} v\n JOIN ${il} m ON m.segment_id = v.segment_id\n WHERE m.embedding_model = ?\n ORDER BY vec_distance_cosine(v.embedding, ?) ASC\n LIMIT ?`).all(xl(n),t,xl(n),r)}function _l(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${al} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:bl(n,yl(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function vl(e,t){try{return await Qc(e,t)}catch(e){return W.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function yl(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function bl(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a]??0,s=t[a]??0;n+=o*s,r+=o*o,i+=s*s}return r<=0||i<=0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function xl(e){return Buffer.from(new Float32Array(e).buffer)}const Sl=8e3,Cl=new Map;function wl(e){return{enabled:e?.enabled!==!1,embeddingModelDir:Bl(e?.embeddingModelDir),minUserTurns:e?.minUserTurns??4,minEstimatedTokens:e?.minEstimatedTokens??4e3,recentProtectedTurnCount:e?.recentProtectedTurnCount??2,maxCandidates:e?.maxCandidates??40,maxSelectedTurns:e?.maxSelectedTurns??8,maxShortlistCandidates:e?.maxShortlistCandidates??12,maxShortlistSegments:e?.maxShortlistSegments??6,maxCandidateUserChars:e?.maxCandidateUserChars??600,maxCandidateAssistantChars:e?.maxCandidateAssistantChars??1e3,timeoutMs:e?.timeoutMs??2e4,maxTokens:e?.maxTokens??4096}}function Tl(e){let t=jl(e.entries),n=new Map(e.candidates.map(e=>[e.turnId,e])),r=new Set(e.decision.selectedTurnIds),i=e.recentProtectedTurnCount>0?t.slice(-e.recentProtectedTurnCount):[],a=i.map(e=>e.turnId);for(let e of i)r.add(e.turnId);let o=new Set;if(e.useCompressedSegmentMemory!==!1&&e.segmentRecords)for(let t of e.segmentRecords){let e=t.turnIds.some(e=>r.has(e)),n=t.turnIds.some(e=>a.includes(e));if(!(!e||n||t.status!==`closed`))for(let e of t.turnIds)o.add(e)}let s=[],c=[],l=[],u=[];for(let e of t){if(!r.has(e.turnId)){l.push(e.turnId),u.push(Fl(e,n.get(e.turnId)));continue}s.push({turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex}),!o.has(e.turnId)&&c.push(...e.entries)}return{entries:[...e.useCompressedSegmentMemory!==!1&&e.segmentRecords?Uc({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function El(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=Vl(e.currentUserMessage),n=new Set(e.recentProtectedTurnCount>0?e.candidates.slice(-e.recentProtectedTurnCount).map(e=>e.turnId):[]);return e.candidates.map((r,i)=>({candidate:r,index:i,forced:n.has(r.turnId),score:Ul(t,r,i,e.candidates.length)})).sort((e,t)=>e.forced===t.forced?t.score===e.score?t.index-e.index:t.score-e.score:e.forced?-1:1).slice(0,e.maxShortlist).map(e=>e.candidate).sort((e,t)=>e.startIndex-t.startIndex)}async function Dl(e){let t=wl(e.config),n=()=>Kl({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){W.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){W.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){W.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=jl(e.entries),i=J(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){W.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>Ml(e,t)),o=e.llm.flashModel||e.llm.model,s=await Ol({entries:e.entries,candidates:a,pendingUserMessage:e.pendingUserMessage,config:t,llm:{apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,model:o,timeoutMs:t.timeoutMs,maxTokens:t.maxTokens},dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:t.embeddingModelDir,signal:e.signal}),c=s.segmentRecords,l=new Set(a.map(e=>e.turnId)),u=new Date().toISOString(),d=Date.now();W.info(`topic segmentation classify started`,Kl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Pl({currentUserMessage:e.pendingUserMessage,allCandidates:a,shortlistedCandidates:s.candidates,selectedSegmentIds:s.selectedSegmentIds,supplementalTurnIds:s.supplementalTurnIds,segmentRecords:c,recentProtectedTurnCount:t.recentProtectedTurnCount,maxSelectedTurns:t.maxSelectedTurns}),p=f.selectedTurnIds.filter(e=>!l.has(e));if(p.length>0)throw Error(`Local topic segmentation returned unknown turn ids: ${p.join(`, `)}`);let m=Date.now()-d,h=Tl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=Nl({timestamp:u,durationMs:m,sessionId:e.sessionId,model:o,pendingUserMessage:e.pendingUserMessage,fullTranscript:e.fullTranscript,candidates:a,shortlistedCandidates:s,decision:f,projected:h,tokenEstimateBefore:i,tokenEstimateAfter:J(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await Ll(e,g),W.info(`topic segmentation classify succeeded`,{...Kl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}),durationMs:m,selectedTurnCount:f.selectedTurnIds.length,confidence:f.confidence,tokenEstimateAfter:g.tokenEstimate?.after,droppedTurnCount:h.droppedTurnIds.length,droppedTurnPreviews:h.droppedTurns.length>0?JSON.stringify(h.droppedTurns):void 0}),{entries:h.entries,audit:g}}async function Ol(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await kl({entries:e.entries,llm:e.llm,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,signal:e.signal}),n=e.config.recentProtectedTurnCount>0?e.candidates.slice(-e.config.recentProtectedTurnCount).map(e=>e.turnId):[],r=Date.now(),i=[],a=e.candidates,o=t,s=[],c=[];if(t){let o=await sl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,query:e.pendingUserMessage,limit:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2)}),l=Vc({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=Jl(l,e.config.maxShortlistSegments),d=Al({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:Sl});if(d&&eu({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await ru({currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,retrieved:l,llm:{...e.llm,timeoutMs:d},maxSelectedSegments:e.config.maxShortlistSegments,signal:e.signal});t.length>0&&(u=t)}s=u,i=u.map(e=>e.segment.segmentId),a=Hc({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Yl({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:Sl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await bc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),iu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=$l(a,l.selectedCandidates),d=El({currentUserMessage:e.pendingUserMessage,candidates:u.length>0?u:a,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxShortlist:Math.min(e.config.maxCandidates,e.config.maxShortlistCandidates)});return{candidates:d.length>0?d:e.candidates,selectedSegmentIds:i,supplementalTurnIds:l.selectedTurnIds,segmentRecords:o}}async function kl(e){W.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await yc(e);if(!t){let t=xc(e.entries);if(t.length===0){W.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await bc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),iu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),W.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}W.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=Sc(t,e.entries);return n.length>0&&(await bc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),iu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),W.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function Al(e){let t=Math.max(0,(e.nowMs??Date.now())-e.budgetStartedAtMs),n=Math.max(0,e.budgetMs-t);if(!(n<=0))return Math.min(e.requestTimeoutMs,n)}function jl(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,entries:[a],user:a.content,timestamp:a.timestamp};continue}n&&(n.entries.push(a),n.endIndex=i)}return r(),t}function Ml(e,t){let n=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim()),r=new Set,i=!1;for(let t of e.entries){if(t.role===`assistant`){for(let e of t.toolCalls??[])r.add(e.name);t.stopReason===`error`&&(i=!0);continue}Gl(t)&&(r.add(t.toolName),t.isError&&(i=!0))}return{turnId:e.turnId,startIndex:e.startIndex,endIndex:n?e.entries.indexOf(n)+e.startIndex:e.endIndex,user:Rl(e.user,t.maxCandidateUserChars),assistant:n?Rl((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function Nl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:Rl(e.pendingUserMessage,400),transcriptEntryCount:e.fullTranscript.length,candidateCount:e.candidates.length,shortlistCount:e.shortlistedCandidates.candidates.length,selectedSegmentIds:e.selectedSegmentIds,selectedTurnIds:e.decision.selectedTurnIds,selectedRanges:e.projected.selectedRanges,forcedKeep:{recentTurnIds:e.projected.recentTurnIds},droppedTurnIds:e.projected.droppedTurnIds,droppedTurns:e.projected.droppedTurns,confidence:e.decision.confidence,reason:e.decision.reason,tokenEstimate:{before:e.tokenEstimateBefore,after:e.tokenEstimateAfter}}}function Pl(e){let t=new Set(e.allCandidates.map(e=>e.turnId)),n=new Set;if(e.segmentRecords&&e.selectedSegmentIds.length>0){let r=e.segmentRecords.filter(t=>e.selectedSegmentIds.includes(t.segmentId));for(let e of r)for(let r of e.turnIds)t.has(r)&&n.add(r)}for(let r of e.supplementalTurnIds)t.has(r)&&n.add(r);if(n.size===0){let t=Vl(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:Ul(t,n,r,e.shortlistedCandidates.length)})).sort((e,t)=>t.score-e.score),i=r[0]?.score??0,a=Math.max(8,i>=8?i*.7:1/0);for(let t of r)if(!(t.score<a)&&(n.add(t.candidate.turnId),n.size>=e.maxSelectedTurns))break}return{version:1,selectedTurnIds:[...n].slice(0,e.maxSelectedTurns),reason:e.selectedSegmentIds.length>0||e.supplementalTurnIds.length>0?`local segment retrieval matched prior segments`:`local candidate scoring matched recent turns`,confidence:`high`}}function Fl(e,t){let n=t?.assistant??Il(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:zl(t?.user??e.user,50),assistantPreview:n?zl(n,50):void 0}}function Il(e){let t=[...e.entries].reverse().find(e=>e.role===`assistant`&&!!(e.content||e.errorMessage||``).trim());return t?(t.content||t.errorMessage||``).trim():void 0}async function Ll(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await G.mkdir(n,{recursive:!0}),await G.appendFile(K.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function Rl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function zl(e,t){return[...e].slice(0,t).join(``)}function Bl(e){return e?.trim()||void 0}function Vl(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function Hl(e){return[...Vl(e)].slice(0,8)}function Ul(e,t,n,r){let i=Wl(e,Vl(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Wl(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Gl(e){return e.role===`tool_result`}function Kl(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:ql(e.params.llm.baseUrl),timeoutMs:e.config.timeoutMs,maxTokens:e.config.maxTokens,hasEmbeddingModelDir:!!e.config.embeddingModelDir,embeddingModelDir:e.config.embeddingModelDir,minUserTurns:e.config.minUserTurns,minEstimatedTokens:e.config.minEstimatedTokens,recentProtectedTurnCount:e.config.recentProtectedTurnCount,maxCandidates:e.config.maxCandidates,maxSelectedTurns:e.config.maxSelectedTurns,transcriptEntryCount:e.params.fullTranscript.length,workingEntryCount:e.params.entries.length,pendingUserMessageChars:e.params.pendingUserMessage?.length,candidateCount:e.candidates?.length,shortlistCount:e.shortlistedCandidates?.length,tokenEstimateBefore:e.tokenEstimateBefore,extraPromptChars:e.extraPromptChars}}function ql(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function Jl(e,t){if(e.length===0)return[];let n=e.slice().sort((e,t)=>t.score-e.score),r=n[0]?.score??0,i=Math.max(8,r>=8?r*.7:1/0);return n.filter(e=>e.forced||e.score>=i).slice(0,t)}async function Yl(e){if(!Xl(e))return{selectedCandidates:[],selectedTurnIds:[]};let t=new Set(e.segmentFilteredCandidates.map(e=>e.turnId)),n=new Set(e.recentProtectedTurnIds),r=e.allCandidates.filter(e=>!t.has(e.turnId)&&!n.has(e.turnId));if(r.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let i=Zl(Ql(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=Al({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await pc({currentUserMessage:e.currentUserMessage,turns:i,maxSelectedTurns:e.config.maxSelectedTurns,recentProtectedTurnIds:e.recentProtectedTurnIds,llm:{...e.llm,timeoutMs:a},signal:e.signal}),n=[...new Set(t.selectedTurns.map(e=>e.turnId))].filter(e=>r.some(t=>t.turnId===e));if(n.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let o=r.filter(e=>n.includes(e.turnId)),s=t.selectedTurns.filter(e=>n.includes(e.turnId)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:e.topicLabel?.trim()||void 0,keywords:(e.keywords??Hl(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?Cc(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Xl(e){let t=e.selectedSegments.filter(e=>!e.forced);return tu(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:nu(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Zl(e,t){let n=new Map;for(let e of t??[])for(let t of e.turnIds)n.set(t,e);return e.map(e=>{let t=n.get(e.turnId),r=t?.turnMemories?.find(t=>t.turnId===e.turnId);return{turnId:e.turnId,user:e.user,assistant:e.assistant,toolNames:e.toolNames,hasErrors:e.hasErrors,summary:r?.summary??t?.summary,topicLabel:r?.topicLabel??t?.topicLabel,keywords:r?.keywords??t?.keywords}})}function Ql(e,t,n){let r=Math.max(n.length,1),i=Vl(t);return e.map(e=>({candidate:e,score:Ul(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function $l(...e){let t=new Map;for(let n of e)for(let e of n)t.has(e.turnId)||t.set(e.turnId,e);return[...t.values()].sort((e,t)=>e.startIndex-t.startIndex)}function eu(e){if(e.retrieved.length<2||!tu(e.currentUserMessage))return!1;let t=new Set(e.selected.map(e=>e.segment.segmentId));if(e.selected.filter(e=>!e.forced).length>=2||e.retrieved.filter(e=>!e.forced).length<2)return!1;let n=new Set(e.selected.flatMap(e=>e.segment.turnIds));return e.recentProtectedTurnIds.length>0&&[...n].every(t=>e.recentProtectedTurnIds.includes(t))||t.size<2}function tu(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function nu(e){let t=e.toLowerCase();return/(回到|刚才|前面|之前|上次|那个|前一个|最早|继续刚才)/u.test(t)?!0:/\b(back to|earlier|previous|that earlier|the earlier)\b/i.test(t)}async function ru(e){try{let t=await fc({currentUserMessage:e.currentUserMessage,recentProtectedTurnIds:e.recentProtectedTurnIds,maxSelectedSegments:e.maxSelectedSegments,segments:e.retrieved.map(e=>({segmentId:e.segment.segmentId,turnIds:e.segment.turnIds,summary:e.segment.summary,compressedSummary:e.segment.compressedSummary,keywords:e.segment.keywords,toolNames:e.segment.toolNames,topicLabel:e.segment.topicLabel})),llm:e.llm,signal:e.signal}),n=new Set(t.selectedSegmentIds);return n.size===0?[]:e.retrieved.filter(e=>n.has(e.segment.segmentId))}catch{return[]}}function iu(e){let t=au(e);if(!t||Cl.has(t)){W.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}W.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=ol(e).catch(t=>{W.warn(`topic segment vector sync failed`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length,error:t instanceof Error?t.message:String(t)})}).finally(()=>{Cl.delete(t)});Cl.set(t,n)}function au(e){if(!(!e.dataDir||!e.sessionId))return`${e.dataDir}::${e.sessionStoreName??`default`}::${e.sessionPathScope?.subagent??`root`}::${e.sessionId}`}[`You classify conversation topic relevance for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"selectedTurnIds":["..."],"reason":"...","confidence":"high|medium|low","currentTopicLabel":"optional"}`,`Task: select historical user turns relevant to the current user message.`,`Relevant includes same task continuation, follow-up, correction, reuse of previous artifact, explicit reference, or ambiguous references like 'this', 'above', 'just now'.`,`Do not answer the user. Do not rewrite the user message.`,`Do not select unrelated old topics.`,`Compaction entries are not candidates and have no special retention rule.`].join(`
30
+ `);const ou=[`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 su(e){let t=_(e.dataDir,e.sessionId,e),n=new Map,r=new Map,i=[],a=[],o=[],c,l,u=0,d,f,p=await fu(t);for(let e of p.readStates)n.set(cu(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 G.mkdir(K.dirname(t),{recursive:!0});let p=e.encryptSessions??!1;await L(t,JSON.stringify(s,null,2),p)};return{async findReusableRead(e,t,r){let i=cu(e,t,r),a=n.get(i);if(!a)return null;let o=await uu(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:du(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await uu(e.path)??Date.now()};return n.set(cu(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())lu(i.path)===lu(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=K.join(o,c);await G.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await L(l,t.content,u);let p=K.relative(e.dataDir,l).split(K.sep).join(`/`),h=gu(t.content,a),g={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:p,preview:h,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(g.toolCallId,g),i.push({toolCallId:g.toolCallId,toolName:g.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:h.length,strategy:`persist`,createdAt:g.createdAt}),d=g.createdAt,f=`L2`,await m(),{content:hu(g),reference:g}},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 _u(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 cu(e,t,n){return`${lu(e)}::${t??``}::${n??``}`}function lu(e){return K.normalize(e)}async function uu(e){try{return(await G.stat(e)).mtimeMs}catch{return null}}function du(e){return Ft(`sha1`).update(e).digest(`hex`)}async function fu(e){try{let t=await o(e);if(t===null)return pu();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?pu():{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:mu(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 pu()}}function pu(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function mu(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 hu(e){let t=e.preview.length<e.originalChars?`
31
+ ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...ou,`Preview:`,e.preview+t].join(`
32
+ `)}function gu(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
33
+ `),r=n>t*.5?n:t;return e.slice(0,r)}async function _u(e,t,n,r){let i=l(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await L(i,JSON.stringify(n,null,2),a)}const vu=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function yu(e){let{entries:t,modelInfo:n,contextWindowTokens:r,llm:i,historyLimit:a,compactionEnabled:o=!0,pendingUserMessage:s,topicSegmentation:c,signal:l,hooks:u,hookCtx:d,contextStore:f,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g,channel:_,isSubagent:v,entriesToMessagesOptions:y}=e,b,x=Nu(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=Ws(Us(S,a)),T=[],E=(await Dl({entries:w,fullTranscript:t,pendingUserMessage:s,llm:i,config:c,sessionId:m,dataDir:p,sessionStoreName:h,sessionPathScope:g,channel:_,isSubagent:v,signal:l}).catch(e=>{W.warn(`topic segmentation failed; falling back to repaired history`,{sessionId:m,channel:_,isSubagent:!!v,error:e instanceof Error?e.message:String(e)})}))?.entries??w;E=await xu({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await Su({entries:E,contextStore:f,compactionEvents:T});let D=await Cu({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g});if(E=D.entries,b=Tu(b,D.summaries),f&&(b=await bu({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:Js(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let O=f?.getSnapshot(),k=Math.max(1e3,Math.floor(r*.7)),A=Pu({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:O?.compaction.modelUsage}).projectedInputTokens>=k,j=O?.compaction.consecutiveAutocompactFailures??0;if(!A||j>=3)return{messages:Js(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let{toKeep:M,toSummarise:N}=dc(E,r);if(N.length===0)return{messages:Js(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:T};let P=new Date().toISOString();try{let e=O?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await ec({entries:N,llm:i,previousSummary:b,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d}),a={role:`compaction`,content:t,keptCount:M.length,droppedCount:N.length,timestamp:P};return await f?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:P}),T.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${N.length} entries with session memory`:`Autocompact summarised ${N.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,J(N)),affectedEntries:N.length,snapshotVersion:2}),{messages:Js(Ws(M),n,y),priorSummary:t,compactionEntry:a,stats:{originalCount:C,keptCount:M.length,estimatedTokens:J(M),compacted:!0},compactionEvents:T}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:P}),{messages:Js(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:J(E),compacted:!1},compactionEvents:[...T,{type:`compaction`,reason:`Autocompact failed and was skipped for this turn`,layer:`L6`,strategy:`circuit_breaker_retry`,snapshotVersion:2}]}}}async function bu(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=J(t),u=i.getSnapshot().compaction.sessionMemory,d=!u&&l>=8e3,f=!!u&&l>=(u?.tokenEstimate??0)+15e3&&Mu(t)>=3;if(!d&&!f)return Eu(n,u?.summary);let p=await ec({entries:t,llm:r,previousSummary:Eu(n,u?.summary),instructions:[`Produce a durable session memory for future compaction and resume.`,`If skill_load results are present, do not restate or reconstruct SKILL.md instructions.`,`Record only that the skill was loaded and that it must be reloaded with skill_load if its full content is not visible.`].join(` `),contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}),m={version:1,summary:p,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:l,trigger:d?`threshold`:`autocompact`};return await i.setSessionMemory(m),p}async function xu(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Du).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(!Du(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=Ou(n)?ku(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
34
+ `);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}),Ws(l.reverse())}async function Su(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(!Du(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=Ou(r)?ku(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(`
35
+ `);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}),xu({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Cu(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{entries:t,summaries:[]};let u=l[l.length-2]??t.length,d=[],f=[],p=0,m=0,h=0;for(;p<t.length;){if(p>=u||t[p]?.role===`user`){d.push(t[p]),p+=1;continue}let e=p;for(;p<u&&t[p]?.role!==`user`;)p+=1;let r=t.slice(e,p),o=r.filter(Du).filter(e=>vu.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=wu(r,o),g=new Date().toISOString();f.push(l),m+=r.length,h+=Math.max(0,Math.floor(J(r)-Math.ceil(l.length/4)));let _={id:Lt(),layer:`L5`,startEntryIndex:e,endEntryIndex:p-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:h,createdAt:g};await n?.recordCollapse(_),i&&a&&await Fu(i,a,_,c)}return m>0&&r.push({type:`compaction`,reason:`Collapsed ${m} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:h,affectedEntries:m,snapshotVersion:2}),{entries:d,summaries:f}}function wu(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(`
36
36
  `),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
37
37
  `);return[`Historical tool activity summary: ${t.length} tool results across ${n.join(`, `)}.`,i?`Assistant notes:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
38
38
 
39
- `)}function wu(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)return e;let r=[`Historical tool activity condensed for continuity:`,...n.map(e=>`- ${e.replace(/\n/g,`
39
+ `)}function Tu(e,t){let n=t.map(e=>e.trim()).filter(Boolean);if(n.length===0)return e;let r=[`Historical tool activity condensed for continuity:`,...n.map(e=>`- ${e.replace(/\n/g,`
40
40
  `)}`)].join(`
41
41
  `);return[e?.trim(),r].filter(Boolean).join(`
42
42
 
43
- `)}function Tu(...e){return e.map(e=>e?.trim()).filter(Boolean).join(`
43
+ `)}function Eu(...e){return e.map(e=>e?.trim()).filter(Boolean).join(`
44
44
 
45
- `)||void 0}function Eu(e){return e.role===`tool_result`}function Du(e){return e.toolName===`skill_load`}function Ou(e){let t=ku(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(`
46
- `)}function ku(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Au(t);if(e.name||e.path)return e}return{}}function Au(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 ju(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Mu(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Nu(e){let t=e.pendingUserMessage?.trim()?J([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=J(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=J(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function Pu(e,t,n,r){let i=j(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0}),await G.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Fu(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await ou({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 vu({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Iu(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent,entriesToMessagesOptions:e.entriesToMessagesOptions}):vu({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent,entriesToMessagesOptions:e.entriesToMessagesOptions})}const Lu=q.Object({command:q.String({description:`Shell command to execute`}),workdir:q.Optional(q.String({description:"Working directory, must be inside the workspace root (relative path resolved against workspace, or an absolute path under it). If the desired directory cannot be located inside the workspace, do NOT set workdir — instead adjust the command itself (e.g. prefix with `cd /abs/path && ...` or pass absolute paths as arguments)."})),env:q.Optional(q.Record(q.String(),q.String())),timeout:q.Optional(q.Number({description:`Max total runtime in seconds before the process is killed (default: 1800)`})),yieldMs:q.Optional(q.Number({description:`Foreground wait window in ms before returning a running session to poll (default: 60000). Raise it to wait longer inline for a slow command.`})),background:q.Optional(q.Boolean({description:`Return immediately with a running session (poll with the process tool)`}))}),Ru=6e4;function zu(e,t,n){return Math.max(t,Math.min(n,e))}function Bu(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Vu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?Ru:zu(Math.floor(e),0,12e4)}function Hu(e,t){if(!t?.trim())return e;let n=K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t));if(!n.startsWith(e+K.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Uu(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 Wu(e){return Ku({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
47
- `)}function Gu(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Ku(e){let t=Gu(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 qu(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. Foreground commands auto-yield after ~60s (override with yieldMs), returning a running session you poll with the process tool. For a long-lived process like a dev server, set background:true to return immediately, then do NOT poll for it to finish (it never will): instead probe readiness with a separate command that exits (e.g. `until curl -sf localhost:PORT/health; do sleep 0.5; done`), do your work, then stop it with process(action="kill", sessionId). Background processes left running are killed when the run ends.',parameters:Lu,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=Hu(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Bu(n.timeout);console.log(`Executing command: ${n.command} in ${i} with timeout ${a} seconds`,{command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey});let o=e.registry.start({command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s){let t=c?Vu(n.yieldMs):Ru,r=await e.registry.wait(o.sessionId,e.scopeKey,t);r&&(l=r)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Uu(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?Ku({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[Wu(l)],p=Gu(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(`
48
- `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Ju=q.Object({action:q.String({description:`Process action: list | poll | log | kill`}),sessionId:q.Optional(q.String({description:`Session id for non-list actions`})),offset:q.Optional(q.Number({description:`Log line offset (0-based)`})),limit:q.Optional(q.Number({description:`Maximum lines to return`})),timeout:q.Optional(q.Number({description:`Poll wait time in milliseconds`}))});function Yu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Xu(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Zu(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill. poll waits for a session to FINISH — never use it on a long-lived server (it won't exit); use log to inspect a server's output and kill to stop it.`,parameters:Ju,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(`
49
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Xu(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Yu(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`}}:Xu(`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}}:Xu(`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}}:Xu(`No session found for ${i}`)}return Xu(`Unsupported action: ${n.action}`)}}}function Qu(e){return qu({workspaceDir:e,registry:Rn(),scopeKey:e})}const $u=5*1024*1024,ed=2e3;async function td(e,t){e&&await e(t).catch(()=>{})}function nd(e,t){return K.isAbsolute(e)?K.normalize(e):K.normalize(K.join(t,e))}const rd=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),offset:q.Optional(q.Number({description:`Line offset (1-based, default: 1)`})),limit:q.Optional(q.Number({description:`Maximum lines to read (default: 2000)`}))});function id(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:rd,async execute(n,r){let i;try{i=nd(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await G.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await tn(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>$u){let e=o.slice(0,$u).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${$u} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
50
- `),l=Math.max(1,r.offset??1),u=Math.min(ed,r.limit??ed),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(`
45
+ `)||void 0}function Du(e){return e.role===`tool_result`}function Ou(e){return e.toolName===`skill_load`}function ku(e){let t=Au(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(`
46
+ `)}function Au(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=ju(t);if(e.name||e.path)return e}return{}}function ju(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 Mu(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Nu(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Pu(e){let t=e.pendingUserMessage?.trim()?J([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=J(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=J(e.entries.slice(Math.max(0,e.checkpoint.coveredTranscriptEntryCount)).filter(e=>e.role!==`compaction`))+t;return{projectedInputTokens:e.checkpoint.inputTokens+n,estimatedIncrementTokens:n}}async function Fu(e,t,n,r){let i=j(e,t,r);await G.mkdir(K.dirname(i),{recursive:!0}),await G.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Iu(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await su({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 yu({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Lu(e){return e.contextManager?e.contextManager.manageHistory({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent,entriesToMessagesOptions:e.entriesToMessagesOptions}):yu({entries:e.entries,modelInfo:e.modelInfo,contextWindowTokens:e.contextWindowTokens,llm:e.llm,historyLimit:e.historyLimit,compactionEnabled:e.compactionEnabled,pendingUserMessage:e.pendingUserMessage,topicSegmentation:e.topicSegmentation,signal:e.signal,hooks:e.hooks,hookCtx:e.hookCtx,dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,channel:e.channel,isSubagent:e.isSubagent,entriesToMessagesOptions:e.entriesToMessagesOptions})}const Ru=q.Object({command:q.String({description:`Shell command to execute`}),workdir:q.Optional(q.String({description:"Working directory, must be inside the workspace root (relative path resolved against workspace, or an absolute path under it). If the desired directory cannot be located inside the workspace, do NOT set workdir — instead adjust the command itself (e.g. prefix with `cd /abs/path && ...` or pass absolute paths as arguments)."})),env:q.Optional(q.Record(q.String(),q.String())),timeout:q.Optional(q.Number({description:`Max total runtime in seconds before the process is killed (default: 1800)`})),yieldMs:q.Optional(q.Number({description:`Foreground wait window in ms before returning a running session to poll (default: 60000). Raise it to wait longer inline for a slow command.`})),background:q.Optional(q.Boolean({description:`Return immediately with a running session (poll with the process tool)`}))}),zu=6e4;function Bu(e,t,n){return Math.max(t,Math.min(n,e))}function Vu(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Hu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?zu:Bu(Math.floor(e),0,12e4)}function Uu(e,t){if(!t?.trim())return e;let n=K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t));if(!n.startsWith(e+K.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Wu(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 Gu(e){return qu({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
47
+ `)}function Ku(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function qu(e){let t=Ku(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 Ju(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. Foreground commands auto-yield after ~60s (override with yieldMs), returning a running session you poll with the process tool. For a long-lived process like a dev server, set background:true to return immediately, then do NOT poll for it to finish (it never will): instead probe readiness with a separate command that exits (e.g. `until curl -sf localhost:PORT/health; do sleep 0.5; done`), do your work, then stop it with process(action="kill", sessionId). Background processes left running are killed when the run ends.',parameters:Ru,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=Uu(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Vu(n.timeout);console.log(`Executing command: ${n.command} in ${i} with timeout ${a} seconds`,{command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey});let o=e.registry.start({command:n.command,cwd:i,env:n.env,baseEnv:e.baseEnv,timeoutSec:a,scopeKey:e.scopeKey}),s=n.background===!0,c=typeof n.yieldMs==`number`&&Number.isFinite(n.yieldMs),l=o,u;try{if(!s&&r&&(u=()=>{e.registry.terminate(o.sessionId,e.scopeKey)},r.aborted?u():r.addEventListener(`abort`,u,{once:!0})),!s){let t=c?Hu(n.yieldMs):zu,r=await e.registry.wait(o.sessionId,e.scopeKey,t);r&&(l=r)}}finally{r&&u&&r.removeEventListener(`abort`,u)}if(l.status===`running`)return{content:[{type:`text`,text:Wu(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?qu({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[Gu(l)],p=Ku(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(`
48
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Yu=q.Object({action:q.String({description:`Process action: list | poll | log | kill`}),sessionId:q.Optional(q.String({description:`Session id for non-list actions`})),offset:q.Optional(q.Number({description:`Log line offset (0-based)`})),limit:q.Optional(q.Number({description:`Maximum lines to return`})),timeout:q.Optional(q.Number({description:`Poll wait time in milliseconds`}))});function Xu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Zu(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Qu(e){return{name:`process`,label:`Process`,description:`Manage background exec sessions: list, poll, log, kill. poll waits for a session to FINISH — never use it on a long-lived server (it won't exit); use log to inspect a server's output and kill to stop it.`,parameters:Yu,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(`
49
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Zu(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Xu(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`}}:Zu(`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}}:Zu(`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}}:Zu(`No session found for ${i}`)}return Zu(`Unsupported action: ${n.action}`)}}}function $u(e){return Ju({workspaceDir:e,registry:Rn(),scopeKey:e})}const ed=5*1024*1024,td=2e3;async function nd(e,t){e&&await e(t).catch(()=>{})}function rd(e,t){return K.isAbsolute(e)?K.normalize(e):K.normalize(K.join(t,e))}const id=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),offset:q.Optional(q.Number({description:`Line offset (1-based, default: 1)`})),limit:q.Optional(q.Number({description:`Maximum lines to read (default: 2000)`}))});function ad(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:id,async execute(n,r){let i;try{i=rd(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await G.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await tn(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>ed){let e=o.slice(0,ed).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${ed} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
50
+ `),l=Math.max(1,r.offset??1),u=Math.min(td,r.limit??td),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(`
51
51
  `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
52
52
  `),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
53
- `),lines:d.length,truncated:f}}}}}const ad=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),content:q.String({description:`File content to write`})});function od(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:ad,async execute(r,i){let a;try{a=nd(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await G.mkdir(K.dirname(a),{recursive:!0}),await G.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await td(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 sd=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),old_string:q.String({description:`Exact text to replace`}),new_string:q.String({description:`Replacement text`})});function cd(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:sd,async execute(r,i){let a;try{a=nd(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await G.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await G.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await td(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 ld=q.Object({path:q.Optional(q.String({description:`Directory path (default: workspace root)`}))});function ud(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:ld,async execute(t,n){let r=n.path??`.`,i;try{i=nd(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await G.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
54
- `)||`(empty directory)`}],details:{entries:a}}}}}const dd=q.Object({input:q.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function fd(e,t){let n=K.isAbsolute(e)?K.normalize(e):K.normalize(K.join(t,e));if(!n.startsWith(t+K.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function pd(e,t){let n=K.relative(t,e);return!n||n===``?K.basename(e):n.startsWith(`..`)||K.isAbsolute(n)?e:n}async function md(e){await G.mkdir(K.dirname(e),{recursive:!0})}async function hd(e,t){e&&await e(t).catch(()=>{})}function gd(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(`
55
- `)}function _d(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:dd,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=yd(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=fd(r.path,e);await md(i),await G.writeFile(i,r.contents,`utf-8`),await hd(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),vd(o,s,`added`,pd(i,e));continue}if(r.kind===`delete`){let i=fd(r.path,e);await G.rm(i,{force:!0,recursive:!1}),await hd(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),vd(o,s,`deleted`,pd(i,e));continue}let i=fd(r.path,e),a=await Cd(i,r.chunks);if(r.movePath){let c=fd(r.movePath,e);await md(c),await G.writeFile(c,a,`utf-8`),await G.rm(i,{force:!0,recursive:!1}),await hd(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),vd(o,s,`modified`,pd(c,e))}else await G.writeFile(i,a,`utf-8`),await hd(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),vd(o,s,`modified`,pd(i,e))}return{content:[{type:`text`,text:gd(o)}],details:{summary:o}}}catch(e){if(So(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function vd(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function yd(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);bd(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=xd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function bd(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 xd(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}=Sd(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 Sd(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 Cd(e,t){let n=(await G.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
56
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Td(n,wd(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
57
- `)}function wd(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Ed(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=Ed(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=Ed(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
58
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Td(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 Ed(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(Dd(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Dd(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Dd(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Dd(e,t,n,e=>Od(e.trim())))return n;return null}function Dd(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 Od(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(``)}const Y=e=>({ok:!0,value:e}),X=e=>({ok:!1,error:e}),kd=(e,t)=>e.ok===!0?Y(t(e.value)):X(e.error),Ad=(e,t)=>e.ok===!0?t(e.value):X(e.error),Z=e=>!!e&&typeof e==`object`&&!Array.isArray(e),jd=e=>typeof e==`string`&&e.trim()?e.trim():void 0,Md=e=>e.filter(e=>e!==void 0),Nd=e=>Array.isArray(e)?`[${e.map(Nd).join(`,`)}]`:Z(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Nd(e[t])}`).join(`,`)}}`:JSON.stringify(e),Pd=e=>Ft(`sha256`).update(e).digest(`hex`),Fd=e=>Ft(`sha256`).update(e).digest(`hex`),Id=e=>Pd(Nd(e));function Ld(e,t){let n=t?.trim()?K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t)):e;if(!n.startsWith(`${e}${K.sep}`)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}const Rd=(e,t)=>t===e||t.startsWith(`${e}${K.sep}`),zd=(e,t)=>`${e}.${t}`,Bd=(e,t,n)=>t[n]===void 0?Y(void 0):jd(t[n])?Y(jd(t[n])):X(`${zd(e,n)} must be a non-empty string.`),Vd=(e,t,n)=>t[n]===void 0?Y(void 0):typeof t[n]==`number`?Y(t[n]):X(`${zd(e,n)} must be a number.`),Hd=(e,t,n)=>t[n]===void 0?Y(void 0):typeof t[n]==`boolean`?Y(t[n]):X(`${zd(e,n)} must be true or false.`),Ud=(e,t,n,r)=>t[n]===void 0?Y(void 0):r.includes(t[n])?Y(t[n]):X(`${zd(e,n)} must be one of: ${r.join(`, `)}.`),Wd=e=>e.reduce((e,[t,n])=>Ad(e,e=>kd(n,n=>n===void 0?e:{...e,[t]:n})),Y({})),Gd=e=>Array.from(e.matchAll(/{{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*}}/g)).map(e=>e[1]??``),Kd=e=>/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`,qd=(e,t)=>typeof t==`string`?Y(Kd(t)):typeof t==`number`||typeof t==`boolean`?Y(String(t)):X(`Input '${e}' cannot be inserted into a shell template. Use a string, number, or boolean.`),Jd=(e,t)=>Gd(e).reduce((e,n)=>Ad(e,e=>kd(qd(n,t[n]),t=>e.replace(RegExp(`{{\\s*${n}\\s*}}`,`g`),t))),Y(e)),Yd=e=>e.replace(/^["']|["']$/g,``),Xd=e=>Array.from(e.matchAll(/(?:^|\s)(?:bash|sh)?\s*(["']?[^"'\s]+\.sh["']?)/g)).map(e=>Yd(e[1]??``).trim()).filter(Boolean),Zd=(e,t)=>K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t)),Qd=async(e,t,n)=>{let r=Zd(t,n);return Rd(e,r)?await G.readFile(r).then(e=>({path:r,sha256:Fd(e)})).catch(()=>void 0):void 0};async function $d(e){return Md(await Promise.all(Xd(e.command).map(t=>Qd(e.workspaceDir,e.resolvedWorkdir,t))))}const ef=(e,t={})=>({content:[{type:`text`,text:e}],details:{status:`failed`,...t},isError:!0}),tf=(e,t={})=>({content:[{type:`text`,text:e}],details:{status:`skipped`,...t}}),nf=q.Object({command:q.String({description:`Shell command to execute after user approval`}),workdir:q.Optional(q.String({description:`Working directory inside the workspace`})),env:q.Optional(q.Record(q.String(),q.String())),timeout:q.Optional(q.Number({description:`Max total runtime in seconds`})),yieldMs:q.Optional(q.Number({description:`Foreground wait window in ms`})),background:q.Optional(q.Boolean({description:`Start command in background`})),title:q.String({description:`Approval card title shown to the user`}),reason:q.String({description:`Why this command requires approval`}),risk:q.Optional(q.Union([q.Literal(`low`),q.Literal(`medium`),q.Literal(`high`),q.Literal(`critical`)])),preview:q.Optional(q.String({description:`Optional markdown preview shown to the user`})),policy:q.Optional(q.Object({timeoutMs:q.Optional(q.Number()),defaultOnTimeout:q.Optional(q.Union([q.Literal(`deny`),q.Literal(`cancel`)]))})),source:q.Optional(q.Object({kind:q.Optional(q.Union([q.Literal(`skill`),q.Literal(`skill_action`),q.Literal(`manual`)])),skillName:q.Optional(q.String()),skillPath:q.Optional(q.String()),actionName:q.Optional(q.String()),actionFile:q.Optional(q.String())}))}),rf=e=>({version:1,tool:e.toolName,command:e.guardedParams.command,resolvedWorkdir:e.resolvedWorkdir,...e.guardedParams.env?{env:e.guardedParams.env}:{},...e.guardedParams.timeout===void 0?{}:{timeout:e.guardedParams.timeout},...e.guardedParams.yieldMs===void 0?{}:{yieldMs:e.guardedParams.yieldMs},...e.guardedParams.background===void 0?{}:{background:e.guardedParams.background},...e.scriptHashes.length>0?{scriptHashes:e.scriptHashes}:{},...e.guardedParams.source?{source:e.guardedParams.source}:{},...e.actionHash?{actionHash:e.actionHash}:{}}),af=e=>({tool:e.toolName,risk:e.guardedParams.risk??`medium`,operationHash:e.operationHash,commandHash:Pd(e.guardedParams.command),...e.guardedParams.env?{envHash:Id(e.guardedParams.env)}:{},...e.scriptHashes.length>0?{scriptHash:Id(e.scriptHashes),scriptPaths:e.scriptHashes.map(e=>e.path)}:{},...e.guardedParams.source?{source:e.guardedParams.source}:{},commandPreview:e.guardedParams.command,workdir:e.resolvedWorkdir,...e.actionHash?{actionHash:e.actionHash}:{}}),of=(e,t)=>[e.preview?.trim()?`${e.preview.trim()}\n`:``,`### Command`,"```bash",t.commandPreview,"```",``,`Risk: ${t.risk}`,t.scriptPaths?.length?`Script hash: ${t.scriptHash}`:``,t.actionHash?`Action hash: ${t.actionHash}`:``,`Operation hash: ${t.operationHash}`].filter(Boolean).join(`
59
- `);async function sf(e){if(!e.sessionId)throw Error(`guarded_exec requires a sessionId to create a HITL approval request.`);let t=Ld(e.workspaceDir,e.guardedParams.workdir),n=await $d({workspaceDir:e.workspaceDir,resolvedWorkdir:t,command:e.guardedParams.command}),r=Id(rf({toolName:e.toolName,guardedParams:e.guardedParams,resolvedWorkdir:t,scriptHashes:n,actionHash:e.actionHash})),i=af({toolName:e.toolName,guardedParams:e.guardedParams,resolvedWorkdir:t,scriptHashes:n,operationHash:r,actionHash:e.actionHash});return{operationHash:r,request:{requestId:Lt(),sessionId:e.hitlResume?.request.sessionId??e.sessionId,kind:`approval`,title:e.guardedParams.title,prompt:e.guardedParams.reason,details:i,preview:{mimeType:`text/markdown`,content:of(e.guardedParams,i)},input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`},{id:`deny`,label:`Deny`}]},policy:{resumable:!0,defaultOnTimeout:e.guardedParams.policy?.defaultOnTimeout??`deny`,...e.guardedParams.policy?.timeoutMs===void 0?{}:{timeoutMs:e.guardedParams.policy.timeoutMs}},createdAt:new Date().toISOString()}}}const cf=e=>typeof e?.request.details?.operationHash==`string`?e.request.details.operationHash:void 0;function lf(e){let t=e.hitlResume;return!t||t.request.kind!==`approval`||t.toolContext?.toolName!==e.toolName||t.toolContext.toolCallId!==e.toolCallId?{kind:`none`}:t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1)?cf(t)===e.operationHash?{kind:`approved`}:{kind:`hash_mismatch`,text:`Guarded command changed after approval; command was not executed.`}:{kind:`denied`,text:`HITL approval denied; guarded command skipped.`}}async function uf(e,t,n,r){return await qu(e).execute(t,{command:n.command,...n.workdir?{workdir:n.workdir}:{},...n.env?{env:n.env}:{},...n.timeout===void 0?{}:{timeout:n.timeout},...n.yieldMs===void 0?{}:{yieldMs:n.yieldMs},...n.background===void 0?{}:{background:n.background}},r)}async function df(e){try{let t=await sf({workspaceDir:e.options.workspaceDir,sessionId:e.options.sessionId,hitlResume:e.options.hitlResume,toolName:e.toolName,toolCallId:e.toolCallId,guardedParams:e.guardedParams,actionHash:e.actionHash}),n=lf({hitlResume:e.options.hitlResume,toolName:e.toolName,toolCallId:e.toolCallId,operationHash:t.operationHash});if(n.kind===`denied`)return tf(n.text);if(n.kind===`hash_mismatch`)return ef(n.text,{operationHash:t.operationHash});if(n.kind===`approved`)return await uf(e.options,e.toolCallId,e.guardedParams,e.signal);throw new xo(t.request,{turnId:e.toolCallId,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:e.toolCallId,toolName:e.toolName,toolArgs:e.guardedParams})}catch(e){if(e instanceof xo)throw e;return ef(e instanceof Error?e.message:String(e))}}function ff(e){return{name:`guarded_exec`,label:`Guarded Exec`,description:`Request HITL approval before executing a shell command. Use for skill-directed side-effectful scripts.`,parameters:nf,async execute(t,n,r){return await df({options:e,toolName:`guarded_exec`,toolCallId:t,guardedParams:n,signal:r})}}}function pf(e){return K.join(e,`.aimax`)}function mf(e){return K.join(pf(e),`MEMORY.md`)}async function hf(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function gf(e,t){let n=pf(e),r=Ke({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return{provider:r.provider,resolvedProviderId:r.providerId,source:r.providerSource}}async function _f(e){return Ye(pf(e))}async function vf(e){try{return await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function yf(e){return vf(mf(e))}async function bf(e,t,n){let{provider:r}=gf(e,n);return await r.search(t)}async function xf(e,t,n,r,i){try{let{provider:a}=gf(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Sf(e,t,n){let{provider:r,resolvedProviderId:i}=gf(e,n);await r.append(t),await hf(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 Cf(e,t,n,r){let{provider:i,resolvedProviderId:a}=gf(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 hf(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await hf(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 hf(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 hf(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await hf(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 wf(e,t,n,r){let{provider:i,resolvedProviderId:a}=gf(e,r);await i.updateFile(t,n),await hf(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Tf(e,t,n){let{provider:r,resolvedProviderId:i}=gf(e,n);await r.deleteFile(t),await hf(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const Ef=q.Object({query:q.String({description:`Search query (case-insensitive substring match)`})});function Df(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:Ef,async execute(n,r){let i=(await bf(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(`
60
- `)}],details:{matches:i}}}}}const Of=q.Object({file:q.String({description:`Memory file path (from memory_search results)`}),start_line:q.Number({description:`Start line number (1-based)`}),end_line:q.Number({description:`End line number (1-based)`})});function kf(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:Of,async execute(n,r){let i=await xf(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(`
61
- `)||`(empty)`}],details:{lines:i}}}}}const Af=q.Object({content:q.String({description:`Content to write to memory`})});function jf(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:Af,async execute(n,r){try{return await Sf(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 Mf=q.Object({section:q.Optional(q.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:q.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:q.Union([q.Literal(`append`),q.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Nf(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:Mf,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Sf(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 wf(e,`MEMORY.md`,Pf(await yf(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Sf(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 Pf(e,t,n){let r=e.split(`
53
+ `),lines:d.length,truncated:f}}}}}const od=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),content:q.String({description:`File content to write`})});function sd(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:od,async execute(r,i){let a;try{a=rd(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await G.mkdir(K.dirname(a),{recursive:!0}),await G.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await nd(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 cd=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),old_string:q.String({description:`Exact text to replace`}),new_string:q.String({description:`Replacement text`})});function ld(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:cd,async execute(r,i){let a;try{a=rd(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await G.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await G.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await nd(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 ud=q.Object({path:q.Optional(q.String({description:`Directory path (default: workspace root)`}))});function dd(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:ud,async execute(t,n){let r=n.path??`.`,i;try{i=rd(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await G.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
54
+ `)||`(empty directory)`}],details:{entries:a}}}}}const fd=q.Object({input:q.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function pd(e,t){let n=K.isAbsolute(e)?K.normalize(e):K.normalize(K.join(t,e));if(!n.startsWith(t+K.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function md(e,t){let n=K.relative(t,e);return!n||n===``?K.basename(e):n.startsWith(`..`)||K.isAbsolute(n)?e:n}async function hd(e){await G.mkdir(K.dirname(e),{recursive:!0})}async function gd(e,t){e&&await e(t).catch(()=>{})}function _d(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(`
55
+ `)}function vd(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:fd,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=bd(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=pd(r.path,e);await hd(i),await G.writeFile(i,r.contents,`utf-8`),await gd(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),yd(o,s,`added`,md(i,e));continue}if(r.kind===`delete`){let i=pd(r.path,e);await G.rm(i,{force:!0,recursive:!1}),await gd(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),yd(o,s,`deleted`,md(i,e));continue}let i=pd(r.path,e),a=await wd(i,r.chunks);if(r.movePath){let c=pd(r.movePath,e);await hd(c),await G.writeFile(c,a,`utf-8`),await G.rm(i,{force:!0,recursive:!1}),await gd(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),yd(o,s,`modified`,md(c,e))}else await G.writeFile(i,a,`utf-8`),await gd(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),yd(o,s,`modified`,md(i,e))}return{content:[{type:`text`,text:_d(o)}],details:{summary:o}}}catch(e){if(So(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function yd(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function bd(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);xd(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Sd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function xd(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 Sd(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}=Cd(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 Cd(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 wd(e,t){let n=(await G.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
56
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=Ed(n,Td(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
57
+ `)}function Td(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Dd(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=Dd(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=Dd(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
58
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function Ed(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 Dd(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(Od(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Od(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Od(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Od(e,t,n,e=>kd(e.trim())))return n;return null}function Od(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 kd(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(``)}const Y=e=>({ok:!0,value:e}),X=e=>({ok:!1,error:e}),Ad=(e,t)=>e.ok===!0?Y(t(e.value)):X(e.error),jd=(e,t)=>e.ok===!0?t(e.value):X(e.error),Z=e=>!!e&&typeof e==`object`&&!Array.isArray(e),Md=e=>typeof e==`string`&&e.trim()?e.trim():void 0,Nd=e=>e.filter(e=>e!==void 0),Pd=e=>Array.isArray(e)?`[${e.map(Pd).join(`,`)}]`:Z(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Pd(e[t])}`).join(`,`)}}`:JSON.stringify(e),Fd=e=>Ft(`sha256`).update(e).digest(`hex`),Id=e=>Ft(`sha256`).update(e).digest(`hex`),Ld=e=>Fd(Pd(e));function Rd(e,t){let n=t?.trim()?K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t)):e;if(!n.startsWith(`${e}${K.sep}`)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}const zd=(e,t)=>t===e||t.startsWith(`${e}${K.sep}`),Bd=(e,t)=>`${e}.${t}`,Vd=(e,t,n)=>t[n]===void 0?Y(void 0):Md(t[n])?Y(Md(t[n])):X(`${Bd(e,n)} must be a non-empty string.`),Hd=(e,t,n)=>t[n]===void 0?Y(void 0):typeof t[n]==`number`?Y(t[n]):X(`${Bd(e,n)} must be a number.`),Ud=(e,t,n)=>t[n]===void 0?Y(void 0):typeof t[n]==`boolean`?Y(t[n]):X(`${Bd(e,n)} must be true or false.`),Wd=(e,t,n,r)=>t[n]===void 0?Y(void 0):r.includes(t[n])?Y(t[n]):X(`${Bd(e,n)} must be one of: ${r.join(`, `)}.`),Gd=e=>e.reduce((e,[t,n])=>jd(e,e=>Ad(n,n=>n===void 0?e:{...e,[t]:n})),Y({})),Kd=e=>Array.from(e.matchAll(/{{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*}}/g)).map(e=>e[1]??``),qd=e=>/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`,Jd=(e,t)=>typeof t==`string`?Y(qd(t)):typeof t==`number`||typeof t==`boolean`?Y(String(t)):X(`Input '${e}' cannot be inserted into a shell template. Use a string, number, or boolean.`),Yd=(e,t)=>Kd(e).reduce((e,n)=>jd(e,e=>Ad(Jd(n,t[n]),t=>e.replace(RegExp(`{{\\s*${n}\\s*}}`,`g`),t))),Y(e)),Xd=e=>e.replace(/^["']|["']$/g,``),Zd=e=>Array.from(e.matchAll(/(?:^|\s)(?:bash|sh)?\s*(["']?[^"'\s]+\.sh["']?)/g)).map(e=>Xd(e[1]??``).trim()).filter(Boolean),Qd=(e,t)=>K.isAbsolute(t)?K.normalize(t):K.normalize(K.join(e,t)),$d=async(e,t,n)=>{let r=Qd(t,n);return zd(e,r)?await G.readFile(r).then(e=>({path:r,sha256:Id(e)})).catch(()=>void 0):void 0};async function ef(e){return Nd(await Promise.all(Zd(e.command).map(t=>$d(e.workspaceDir,e.resolvedWorkdir,t))))}const tf=(e,t={})=>({content:[{type:`text`,text:e}],details:{status:`failed`,...t},isError:!0}),nf=(e,t={})=>({content:[{type:`text`,text:e}],details:{status:`skipped`,...t}}),rf=q.Object({command:q.String({description:`Shell command to execute after user approval`}),workdir:q.Optional(q.String({description:`Working directory inside the workspace`})),env:q.Optional(q.Record(q.String(),q.String())),timeout:q.Optional(q.Number({description:`Max total runtime in seconds`})),yieldMs:q.Optional(q.Number({description:`Foreground wait window in ms`})),background:q.Optional(q.Boolean({description:`Start command in background`})),title:q.String({description:`Approval card title shown to the user`}),reason:q.String({description:`Why this command requires approval`}),risk:q.Optional(q.Union([q.Literal(`low`),q.Literal(`medium`),q.Literal(`high`),q.Literal(`critical`)])),preview:q.Optional(q.String({description:`Optional markdown preview shown to the user`})),policy:q.Optional(q.Object({timeoutMs:q.Optional(q.Number()),defaultOnTimeout:q.Optional(q.Union([q.Literal(`deny`),q.Literal(`cancel`)]))})),source:q.Optional(q.Object({kind:q.Optional(q.Union([q.Literal(`skill`),q.Literal(`skill_action`),q.Literal(`manual`)])),skillName:q.Optional(q.String()),skillPath:q.Optional(q.String()),actionName:q.Optional(q.String()),actionFile:q.Optional(q.String())}))}),af=e=>({version:1,tool:e.toolName,command:e.guardedParams.command,resolvedWorkdir:e.resolvedWorkdir,...e.guardedParams.env?{env:e.guardedParams.env}:{},...e.guardedParams.timeout===void 0?{}:{timeout:e.guardedParams.timeout},...e.guardedParams.yieldMs===void 0?{}:{yieldMs:e.guardedParams.yieldMs},...e.guardedParams.background===void 0?{}:{background:e.guardedParams.background},...e.scriptHashes.length>0?{scriptHashes:e.scriptHashes}:{},...e.guardedParams.source?{source:e.guardedParams.source}:{},...e.actionHash?{actionHash:e.actionHash}:{}}),of=e=>({tool:e.toolName,risk:e.guardedParams.risk??`medium`,operationHash:e.operationHash,commandHash:Fd(e.guardedParams.command),...e.guardedParams.env?{envHash:Ld(e.guardedParams.env)}:{},...e.scriptHashes.length>0?{scriptHash:Ld(e.scriptHashes),scriptPaths:e.scriptHashes.map(e=>e.path)}:{},...e.guardedParams.source?{source:e.guardedParams.source}:{},commandPreview:e.guardedParams.command,workdir:e.resolvedWorkdir,...e.actionHash?{actionHash:e.actionHash}:{}}),sf=(e,t)=>[e.preview?.trim()?`${e.preview.trim()}\n`:``,`### Command`,"```bash",t.commandPreview,"```",``,`Risk: ${t.risk}`,t.scriptPaths?.length?`Script hash: ${t.scriptHash}`:``,t.actionHash?`Action hash: ${t.actionHash}`:``,`Operation hash: ${t.operationHash}`].filter(Boolean).join(`
59
+ `);async function cf(e){if(!e.sessionId)throw Error(`guarded_exec requires a sessionId to create a HITL approval request.`);let t=Rd(e.workspaceDir,e.guardedParams.workdir),n=await ef({workspaceDir:e.workspaceDir,resolvedWorkdir:t,command:e.guardedParams.command}),r=Ld(af({toolName:e.toolName,guardedParams:e.guardedParams,resolvedWorkdir:t,scriptHashes:n,actionHash:e.actionHash})),i=of({toolName:e.toolName,guardedParams:e.guardedParams,resolvedWorkdir:t,scriptHashes:n,operationHash:r,actionHash:e.actionHash});return{operationHash:r,request:{requestId:Lt(),sessionId:e.hitlResume?.request.sessionId??e.sessionId,kind:`approval`,title:e.guardedParams.title,prompt:e.guardedParams.reason,details:i,preview:{mimeType:`text/markdown`,content:sf(e.guardedParams,i)},input:{mode:`choice`,choices:[{id:`approve`,label:`Approve`},{id:`deny`,label:`Deny`}]},policy:{resumable:!0,defaultOnTimeout:e.guardedParams.policy?.defaultOnTimeout??`deny`,...e.guardedParams.policy?.timeoutMs===void 0?{}:{timeoutMs:e.guardedParams.policy.timeoutMs}},createdAt:new Date().toISOString()}}}const lf=e=>typeof e?.request.details?.operationHash==`string`?e.request.details.operationHash:void 0;function uf(e){let t=e.hitlResume;return!t||t.request.kind!==`approval`||t.toolContext?.toolName!==e.toolName||t.toolContext.toolCallId!==e.toolCallId?{kind:`none`}:t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1)?lf(t)===e.operationHash?{kind:`approved`}:{kind:`hash_mismatch`,text:`Guarded command changed after approval; command was not executed.`}:{kind:`denied`,text:`HITL approval denied; guarded command skipped.`}}async function df(e,t,n,r){return await Ju(e).execute(t,{command:n.command,...n.workdir?{workdir:n.workdir}:{},...n.env?{env:n.env}:{},...n.timeout===void 0?{}:{timeout:n.timeout},...n.yieldMs===void 0?{}:{yieldMs:n.yieldMs},...n.background===void 0?{}:{background:n.background}},r)}async function ff(e){try{let t=await cf({workspaceDir:e.options.workspaceDir,sessionId:e.options.sessionId,hitlResume:e.options.hitlResume,toolName:e.toolName,toolCallId:e.toolCallId,guardedParams:e.guardedParams,actionHash:e.actionHash}),n=uf({hitlResume:e.options.hitlResume,toolName:e.toolName,toolCallId:e.toolCallId,operationHash:t.operationHash});if(n.kind===`denied`)return nf(n.text);if(n.kind===`hash_mismatch`)return tf(n.text,{operationHash:t.operationHash});if(n.kind===`approved`)return await df(e.options,e.toolCallId,e.guardedParams,e.signal);throw new xo(t.request,{turnId:e.toolCallId,phase:`before_tool`,resumeStrategy:`reenter_from_checkpoint`},{toolCallId:e.toolCallId,toolName:e.toolName,toolArgs:e.guardedParams})}catch(e){if(e instanceof xo)throw e;return tf(e instanceof Error?e.message:String(e))}}function pf(e){return{name:`guarded_exec`,label:`Guarded Exec`,description:`Request HITL approval before executing a shell command. Use for skill-directed side-effectful scripts.`,parameters:rf,async execute(t,n,r){return await ff({options:e,toolName:`guarded_exec`,toolCallId:t,guardedParams:n,signal:r})}}}function mf(e){return K.join(e,`.aimax`)}function hf(e){return K.join(mf(e),`MEMORY.md`)}async function gf(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function _f(e,t){let n=mf(e),r=Ke({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return{provider:r.provider,resolvedProviderId:r.providerId,source:r.providerSource}}async function vf(e){return Ye(mf(e))}async function yf(e){try{return await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function bf(e){return yf(hf(e))}async function xf(e,t,n){let{provider:r}=_f(e,n);return await r.search(t)}async function Sf(e,t,n,r,i){try{let{provider:a}=_f(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Cf(e,t,n){let{provider:r,resolvedProviderId:i}=_f(e,n);await r.append(t),await gf(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 wf(e,t,n,r){let{provider:i,resolvedProviderId:a}=_f(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 gf(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await gf(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 gf(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 gf(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await gf(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 Tf(e,t,n,r){let{provider:i,resolvedProviderId:a}=_f(e,r);await i.updateFile(t,n),await gf(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Ef(e,t,n){let{provider:r,resolvedProviderId:i}=_f(e,n);await r.deleteFile(t),await gf(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const Df=q.Object({query:q.String({description:`Search query (case-insensitive substring match)`})});function Of(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:Df,async execute(n,r){let i=(await xf(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(`
60
+ `)}],details:{matches:i}}}}}const kf=q.Object({file:q.String({description:`Memory file path (from memory_search results)`}),start_line:q.Number({description:`Start line number (1-based)`}),end_line:q.Number({description:`End line number (1-based)`})});function Af(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:kf,async execute(n,r){let i=await Sf(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(`
61
+ `)||`(empty)`}],details:{lines:i}}}}}const jf=q.Object({content:q.String({description:`Content to write to memory`})});function Mf(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:jf,async execute(n,r){try{return await Cf(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 Nf=q.Object({section:q.Optional(q.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:q.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:q.Union([q.Literal(`append`),q.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Pf(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:Nf,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Cf(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 Tf(e,`MEMORY.md`,Ff(await bf(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Cf(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 Ff(e,t,n){let r=e.split(`
62
62
  `),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(`
63
63
  `).trimEnd(),a,r.slice(s).join(`
64
64
  `).trimStart()].filter(e=>e.length>0).join(`
65
- `)}\n`}function Ff(e,t){let n=e.split(`
65
+ `)}\n`}function If(e,t){let n=e.split(`
66
66
  `),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(`
67
67
  `).trimEnd(),n.slice(a).join(`
68
68
  `).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
69
- `)}\n`:``}function If(e,t){let n=e.split(`
69
+ `)}\n`:``}function Lf(e,t){let n=e.split(`
70
70
  `);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
71
- `)}\n`:``)}function Lf(e,t,n){let r=e.split(`
71
+ `)}\n`:``)}function Rf(e,t,n){let r=e.split(`
72
72
  `);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
73
- `)}\n`)}function Rf(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 zf(e,t){let n=[],r=t.split(`
74
- `);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 Bf=q.Object({content:q.String({description:`Note to append to today's daily log`}),scope:q.Optional(q.Union([q.Literal(`daily`),q.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Vf(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:Bf,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Cf(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 Hf=q.Object({scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Uf(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:Hf,async execute(n,r){try{let n=r.scope??`all`,i=await _f(e),a=[];for(let n of i.slice(0,30)){let r=await xf(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
75
- `),t=zf(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(`
73
+ `)}\n`)}function zf(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 Bf(e,t){let n=[],r=t.split(`
74
+ `);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 Vf=q.Object({content:q.String({description:`Note to append to today's daily log`}),scope:q.Optional(q.Union([q.Literal(`daily`),q.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Hf(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:Vf,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await wf(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 Uf=q.Object({scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Wf(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:Uf,async execute(n,r){try{let n=r.scope??`all`,i=await vf(e),a=[];for(let n of i.slice(0,30)){let r=await Sf(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
75
+ `),t=Bf(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
76
76
  `):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
77
77
 
78
- `)||`(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 Wf=q.Object({id:q.Optional(q.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:q.Optional(q.String({description:`Search query used to find memories to delete`})),limit:q.Optional(q.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Gf(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:Wf,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Rf(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Ff(await yf(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 wf(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 xf(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=Ff(n.join(`
79
- `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await wf(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 xf(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=If(n.join(`
80
- `),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 wf(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 Tf(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 bf(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await Tf(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 Kf=q.Object({id:q.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:q.String({description:`New content to replace the existing memory with`})});function qf(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:Kf,async execute(n,r){try{let n=Rf(r.id);if(n.section){let i=Pf(await yf(e)??``,n.section,r.content);return await wf(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 xf(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=Lf(i.join(`
81
- `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await wf(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 wf(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 Jf=q.Object({query:q.Optional(q.String({description:`Search query; omit to browse recent sessions.`})),role_filter:q.Optional(q.Union([q.Literal(`user`),q.Literal(`assistant`),q.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:q.Optional(q.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:q.Optional(q.Union([q.Literal(`llm`),q.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Yf(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:Jf,async execute(n,r){let i=Xf(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Zf(e,i,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let c=await Qf({dataDir:e,query:o,roleFilter:s,messageLimit:50,sessionLimit:i,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(c.length===0){let e={mode:`query`,query:o,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let l=[];for(let n of c){let r=dp(o,n.snippets);if(a===`off`){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let i=await $s({entries:cp(sp(await F(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:up({query:o})});l.push({session_id:n.sessionId,summary:i.trim()||r,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let u={mode:`query`,query:o,count:l.length,results:l};return{content:[{type:`text`,text:JSON.stringify(u,null,2)}],details:u}}}}function Xf(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Zf(e,t,n){let r=await x(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await I(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function Qf(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=np(e.query),i=(await fp(n,6,async t=>$f({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(op).slice(0,t);if(i.length===0)return[];let a=new Map;for(let e of i){let t=a.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),a.set(e.sessionId,t)}let o=Array.from(a.values());for(let t of o){let n=await I(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return o.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),o.slice(0,e.sessionLimit)}async function $f(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
82
- `);for(let t of r){let r=t.trim();if(!r||!ep(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!tp(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=ip(i.content,e.terms,i.role);if(a<=0)continue;let o=ap(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(op),n.length=20)}return n.sort(op),n}function ep(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function tp(e){return e===`user`||e===`assistant`||e===`tool_result`}function np(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=>rp(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 rp(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 ip(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 ap(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function op(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function sp(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function cp(e,t,n){if(e.length===0)return e;let r=np(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 lp(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 lp(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 up(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(`
83
- `)}function dp(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(`
84
- `)}`}async function fp(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}function pp(e){return K.join(e,`.aimax`,`skills`)}function mp(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function hp(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${mp(n)}\n`)}function gp(e){let t=Vt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
85
- `);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}function _p(e){let t=Vt(e),n=t.data.metadata,r=(n&&typeof n==`object`&&!Array.isArray(n)?n.version:void 0)??t.data.version;return r==null?``:String(r).trim()}async function vp(e){return(await G.stat(e)).mtime.toISOString()}async function yp(e){return xp([pp(e)])}async function bp(e,t,n=[]){return xp([...n,...t,pp(e)])}async function xp(e){let t=new Map;for(let n of e){let e;try{e=await G.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=K.join(n,e,`SKILL.md`),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=gp(i),o=_p(i),s=await vp(r)}catch(t){hp(e,r,t);continue}t.set(e,{name:e,description:a,location:r,version:o,skillFileMtime:s})}}return Array.from(t.values()).slice(0,50)}async function Sp(e,t){let n=t.trim();if(!n)return;let r=(await xp(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:K.dirname(r.location)}}async function Cp(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=K.resolve(r),a=K.basename(i)===`SKILL.md`?i:K.join(i,`SKILL.md`);if(K.basename(a)!==`SKILL.md`)return;let o;try{o=await G.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=gp(o),c=_p(o),l=await vp(a)}catch(e){hp(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:K.dirname(a)}}async function wp(e,t,n){let r=n?.trim()?await Cp(t,n):await Sp(e,t);if(!r)return;let i=await G.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Tp(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
78
+ `)||`(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 Gf=q.Object({id:q.Optional(q.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:q.Optional(q.String({description:`Search query used to find memories to delete`})),limit:q.Optional(q.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Kf(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:Gf,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=zf(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=If(await bf(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 Tf(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 Sf(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=If(n.join(`
79
+ `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Tf(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 Sf(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=Lf(n.join(`
80
+ `),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 Tf(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 Ef(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 xf(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await Ef(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 qf=q.Object({id:q.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:q.String({description:`New content to replace the existing memory with`})});function Jf(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:qf,async execute(n,r){try{let n=zf(r.id);if(n.section){let i=Ff(await bf(e)??``,n.section,r.content);return await Tf(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 Sf(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=Rf(i.join(`
81
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Tf(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 Tf(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 Yf=q.Object({query:q.Optional(q.String({description:`Search query; omit to browse recent sessions.`})),role_filter:q.Optional(q.Union([q.Literal(`user`),q.Literal(`assistant`),q.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:q.Optional(q.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:q.Optional(q.Union([q.Literal(`llm`),q.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Xf(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:Yf,async execute(n,r){let i=Zf(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Qf(e,i,t),r={mode:`recent`,count:n.length,results:n};return{content:[{type:`text`,text:JSON.stringify(r,null,2)}],details:r}}let c=await $f({dataDir:e,query:o,roleFilter:s,messageLimit:50,sessionLimit:i,currentSessionId:t?.sessionId,sessionStoreName:t?.sessionStoreName});if(c.length===0){let e={mode:`query`,query:o,count:0,results:[]};return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}let l=[];for(let n of c){let r=fp(o,n.snippets);if(a===`off`){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}});continue}if(!t?.llm){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`extractive_short_circuit`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:`llm configuration unavailable`}});continue}try{let i=await ec({entries:lp(cp(await F(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:dp({query:o})});l.push({session_id:n.sessionId,summary:i.trim()||r,when:n.when,source:n.source,meta:{summary_source:`llm`,snippet:n.snippets[0],score:Number(n.score.toFixed(4))}})}catch(e){l.push({session_id:n.sessionId,summary:r,when:n.when,source:n.source,meta:{summary_source:`llm_fallback_extractive`,snippet:n.snippets[0],score:Number(n.score.toFixed(4)),summary_error:e instanceof Error?e.message:String(e)}})}}let u={mode:`query`,query:o,count:l.length,results:l};return{content:[{type:`text`,text:JSON.stringify(u,null,2)}],details:u}}}}function Zf(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Qf(e,t,n){let r=await x(e,{storeName:n?.sessionStoreName}),i=[];for(let t of r){if(t===n?.sessionId)continue;let r=await I(e,t,{storeName:n?.sessionStoreName});r&&i.push({id:t,when:r.updatedAt||r.createdAt||``,source:r.channel??`unknown`,title:r.title?.trim()||`Session activity summary unavailable.`})}return i.sort((e,t)=>t.when.localeCompare(e.when)),i.slice(0,t).map(e=>({session_id:e.id,summary:e.title,when:e.when,source:e.source,meta:{summary_source:`extractive`,snippet:e.title}}))}async function $f(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=rp(e.query),i=(await pp(n,6,async t=>ep({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(sp).slice(0,t);if(i.length===0)return[];let a=new Map;for(let e of i){let t=a.get(e.sessionId)??{sessionId:e.sessionId,score:0,snippets:[],matchedMessageCount:0,when:e.timestamp||``,source:`unknown`};t.score+=e.score,t.matchedMessageCount+=1,t.snippets.length<3&&!t.snippets.includes(e.snippet)&&t.snippets.push(e.snippet),e.timestamp&&e.timestamp>t.when&&(t.when=e.timestamp),a.set(e.sessionId,t)}let o=Array.from(a.values());for(let t of o){let n=await I(e.dataDir,t.sessionId,{storeName:e.sessionStoreName});n&&(t.when=n.updatedAt||n.createdAt||t.when,t.source=n.channel??`unknown`)}return o.sort((e,t)=>t.score===e.score?t.when.localeCompare(e.when):t.score-e.score),o.slice(0,e.sessionLimit)}async function ep(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
82
+ `);for(let t of r){let r=t.trim();if(!r||!tp(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!np(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=ap(i.content,e.terms,i.role);if(a<=0)continue;let o=op(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(sp),n.length=20)}return n.sort(sp),n}function tp(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function np(e){return e===`user`||e===`assistant`||e===`tool_result`}function rp(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=>ip(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 ip(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 ap(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 op(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function sp(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function cp(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function lp(e,t,n){if(e.length===0)return e;let r=rp(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 up(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 up(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 dp(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(`
83
+ `)}function fp(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(`
84
+ `)}`}async function pp(e,t,n){if(e.length===0)return[];let r=Math.max(1,Math.trunc(t)),i=Array(e.length),a=0,o=Array(Math.min(r,e.length)).fill(0).map(async()=>{for(;;){let t=a;if(a+=1,t>=e.length)break;i[t]=await n(e[t])}});return await Promise.all(o),i}function mp(e){return K.join(e,`.aimax`,`skills`)}function hp(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function gp(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${hp(n)}\n`)}function _p(e){let t=Vt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
85
+ `);for(let e of r){let t=e.trim();if(!t)continue;let n=(t.match(/^#+\s+(.+)$/)?.[1]??t).trim();if(n)return n.slice(0,500)}return``}function vp(e){let t=Vt(e),n=t.data.metadata,r=(n&&typeof n==`object`&&!Array.isArray(n)?n.version:void 0)??t.data.version;return r==null?``:String(r).trim()}async function yp(e){return(await G.stat(e)).mtime.toISOString()}async function bp(e){return Sp([mp(e)])}async function xp(e,t,n=[]){return Sp([...n,...t,mp(e)])}async function Sp(e){let t=new Map;for(let n of e){let e;try{e=await G.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=K.join(n,e,`SKILL.md`),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=_p(i),o=vp(i),s=await yp(r)}catch(t){gp(e,r,t);continue}t.set(e,{name:e,description:a,location:r,version:o,skillFileMtime:s})}}return Array.from(t.values()).slice(0,50)}async function Cp(e,t){let n=t.trim();if(!n)return;let r=(await Sp(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:K.dirname(r.location)}}async function wp(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=K.resolve(r),a=K.basename(i)===`SKILL.md`?i:K.join(i,`SKILL.md`);if(K.basename(a)!==`SKILL.md`)return;let o;try{o=await G.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=_p(o),c=vp(o),l=await yp(a)}catch(e){gp(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:K.dirname(a)}}async function Tp(e,t,n){let r=n?.trim()?await wp(t,n):await Cp(e,t);if(!r)return;let i=await G.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Ep(e){return e.length===0?``:`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
86
86
  `)).join(`
87
- `)}\n</available_skills>`}const Ep=q.Object({category:q.Optional(q.String({description:`Reserved category filter field. Not used yet.`}))}),Dp=q.Object({name:q.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:q.Optional(q.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Op(e,t,n=[]){return[...n,...t,pp(e)]}function kp(e,t,n=[]){let r=Op(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Ep,async execute(e,t){let n=await xp(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 Ap(e){let t=Op(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:Dp,async execute(r,i){let a=await wp(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``,version:``,skillFileMtime:``}}}}}const jp=q.Object({skillName:q.Optional(q.String({description:`Skill name from the available skills registry`})),skillPath:q.Optional(q.String({description:`Optional explicit path to a skill directory or SKILL.md`})),action:q.String({description:`Action name declared in actions.yml`}),inputs:q.Optional(q.Record(q.String(),q.Unknown()))}),Mp=/^[a-z][a-z0-9_-]{0,63}$/,Np=[`low`,`medium`,`high`,`critical`],Pp=[`deny`,`cancel`],Fp=(e,t,n=[])=>[...n,...t,pp(e)],Ip=e=>{let t=K.resolve(e),n=K.basename(t)===`SKILL.md`?t:K.join(t,`SKILL.md`);return{rootDir:K.dirname(n),skillFile:n}};async function Lp(e){if(!e.skillName?.trim()&&!e.skillPath?.trim())return X(`skill_action_run requires either skillName or skillPath.`);if(e.skillPath?.trim()){let t=Ip(e.skillPath),n=K.basename(t.rootDir),r=e.skillName?.trim()||n;return e.skillName?.trim()&&e.skillName.trim()!==n?X(`skillName '${e.skillName}' does not match skillPath '${e.skillPath}'.`):await G.access(t.skillFile).then(()=>Y({name:r,rootDir:t.rootDir,skillFile:t.skillFile})).catch(()=>X(`Skill '${r}' not found at '${e.skillPath}'.`))}return await Sp(Fp(e.dataDir,e.pluginDirs,e.skillsLoadPaths),e.skillName??``).then(t=>t?Y({name:t.skill.name,rootDir:t.rootDir,skillFile:t.skill.location}):X(`Skill '${e.skillName}' not found.`))}async function Rp(e){let t=K.join(e.rootDir,`actions.yml`),n=K.join(e.rootDir,`actions.yaml`),[r,i]=await Promise.all([G.access(t).then(()=>!0).catch(()=>!1),G.access(n).then(()=>!0).catch(()=>!1)]);return r&&i?X(`Skill '${e.name}' has both actions.yml and actions.yaml. Keep only actions.yml.`):r||i?await G.readFile(r?t:n,`utf-8`).then(e=>Y({path:r?t:n,content:e})).catch(t=>X(`Failed to read actions file for skill '${e.name}': ${String(t)}`)):X(`Skill '${e.name}' does not define actions.yml.`)}const zp=(e,t)=>{try{return Y(nn(t))}catch(t){return X(`Invalid actions.yml for skill '${e}': ${t instanceof Error?t.message:String(t)}`)}},Bp=e=>typeof e.shell==`string`!==Array.isArray(e.argv),Vp=(e,t)=>Z(t)?Bp(t)?typeof t.shell==`string`&&t.shell.trim()?Y({shell:t.shell}):Array.isArray(t.argv)&&t.argv.every(e=>typeof e==`string`&&e.trim())?Y({argv:t.argv}):X(`Action '${e}' has an invalid command definition.`):X(`Action '${e}' must define exactly one of command.shell or command.argv.`):X(`Action '${e}' must define command.shell or command.argv.`),Hp=(e,t)=>t===void 0?Y(void 0):Z(t)?Object.entries(t).every(([e,t])=>e.trim()&&typeof t==`string`)?Y(t):X(`Action '${e}' env values must be strings.`):X(`Action '${e}' env must be an object.`),Up=(e,t)=>t===void 0?Y(void 0):Z(t)?Y(t):X(`Action '${e}' inputSchema must be an object schema.`),Wp=(e,t)=>t===void 0?Y(void 0):Z(t)?kd(Wd([[`includeCommand`,Hd(`Action '${e}' hitl.preview`,t,`includeCommand`)],[`includeInputs`,Hd(`Action '${e}' hitl.preview`,t,`includeInputs`)],[`includeScriptHash`,Hd(`Action '${e}' hitl.preview`,t,`includeScriptHash`)],[`text`,Bd(`Action '${e}' hitl.preview`,t,`text`)]]),e=>e):X(`Action '${e}' hitl.preview must be an object.`),Gp=(e,t)=>{let n=`Action '${e}' hitl`;return t===void 0?Y(void 0):Z(t)?typeof t.required==`boolean`?kd(Wd([[`title`,Bd(n,t,`title`)],[`reason`,Bd(n,t,`reason`)],[`risk`,Ud(n,t,`risk`,Np)],[`timeoutMs`,Vd(n,t,`timeoutMs`)],[`defaultOnTimeout`,Ud(n,t,`defaultOnTimeout`,Pp)],[`preview`,Wp(e,t.preview)]]),e=>({required:t.required,...e})):X(`${n}.required must be true or false.`):X(`${n} must be an object.`)},Kp=(e,t)=>kd(Wd([[`inputSchema`,Up(e,t.inputSchema)],[`workdir`,Bd(`Action '${e}'`,t,`workdir`)],[`env`,Hp(e,t.env)],[`timeout`,Vd(`Action '${e}'`,t,`timeout`)],[`yieldMs`,Vd(`Action '${e}'`,t,`yieldMs`)],[`background`,Hd(`Action '${e}'`,t,`background`)],[`hitl`,Gp(e,t.hitl)]]),e=>e),qp=(e,t)=>Mp.test(e)?Z(t)?jd(t.description)?Ad(Vp(e,t.command),n=>kd(Kp(e,t),e=>({description:jd(t.description),command:n,...e}))):X(`Action '${e}' is missing description.`):X(`Action '${e}' must be an object.`):X(`Invalid action name '${e}'. Use lowercase letters, numbers, '_' or '-'.`),Jp=e=>Object.entries(e).reduce((e,[t,n])=>Ad(e,e=>kd(qp(t,n),n=>({...e,[t]:n}))),Y({})),Yp=(e,t)=>Z(t)?t.version===1?!Z(t.actions)||Object.keys(t.actions).length===0?X(`actions.yml for skill '${e}' must define non-empty actions.`):kd(Jp(t.actions),e=>({version:1,actions:e})):X(`actions.yml for skill '${e}' must set version: 1.`):X(`actions.yml for skill '${e}' must be an object.`),Xp=e=>e===void 0?Y({}):Z(e)?Y(e):X(`skill_action_run inputs must be an object.`),Zp=()=>new rn({allErrors:!0,strict:!1}),Qp=(e,t,n)=>{if(!t)return Object.keys(n).length===0?Y(n):X(`Action '${e}' does not accept inputs.`);if(t.type!==`object`||!Z(t.properties))return X(`Action '${e}' inputSchema must be an object schema with properties.`);let r=Zp().compile(t);return r(n)?Y(n):X(`Invalid inputs for action '${e}': ${Zp().errorsText(r.errors)}`)},$p=e=>Z(e.inputSchema?.properties)?Object.keys(e.inputSchema.properties):[],em=e=>{let t=`shell`in e.command?Gd(e.command.shell):e.command.argv.flatMap(Gd),n=new Set($p(e)),r=t.filter(e=>!n.has(e));return r.length===0?Y(e):X(`Action command references undeclared input field(s): ${r.join(`, `)}.`)},tm=(e,t)=>e.reduce((e,n)=>Ad(e,e=>kd(Jd(n,t),t=>[...e,t])),Y([])),nm=(e,t)=>`shell`in e.command?Jd(e.command.shell,t):kd(tm(e.command.argv,t),e=>e.map(Kd).join(` `));async function rm(e){let t=await Lp(e);if(t.ok===!1)return X(t.error);let n=await Rp(t.value);if(n.ok===!1)return X(n.error);let r=Ad(zp(t.value.name,n.value.content),e=>Yp(t.value.name,e));if(r.ok===!1)return X(r.error);let i=r.value.actions[e.action];return i?Ad(em(i),r=>Ad(Xp(e.inputs),i=>Ad(Qp(e.action,r.inputSchema,i),i=>kd(nm(r,i),a=>({skill:t.value,actionName:e.action,actionFile:n.value.path,definition:r,inputs:i,command:a,actionHash:Id({version:1,skillName:t.value.name,skillPath:t.value.rootDir,actionName:e.action,actionsFilePath:n.value.path,actionDefinition:r,inputs:i,renderedCommand:a})}))))):X(`Skill '${t.value.name}' does not define action '${e.action}'.`)}const im=e=>[e.definition.hitl?.preview?.text?.trim()?`${e.definition.hitl.preview.text.trim()}\n`:``,`### Skill Action`,`- Skill: ${e.skill.name}`,`- Action: ${e.actionName}`,`- Risk: ${e.definition.hitl?.risk??`medium`}`,``,`### Inputs`,"```json",JSON.stringify(e.inputs,null,2),"```",``,`### Command`,"```bash",e.command,"```",``,`Action hash: ${e.actionHash}`].filter(Boolean).join(`
88
- `),am=e=>({command:e.command,...e.definition.workdir?{workdir:e.definition.workdir}:{},...e.definition.env?{env:e.definition.env}:{},...e.definition.timeout===void 0?{}:{timeout:e.definition.timeout},...e.definition.yieldMs===void 0?{}:{yieldMs:e.definition.yieldMs},...e.definition.background===void 0?{}:{background:e.definition.background},title:e.definition.hitl?.title||e.definition.description,reason:e.definition.hitl?.reason||`该 action 会执行业务脚本,需要用户确认。`,risk:e.definition.hitl?.risk??`medium`,preview:im(e),policy:{defaultOnTimeout:e.definition.hitl?.defaultOnTimeout??`deny`,...e.definition.hitl?.timeoutMs===void 0?{}:{timeoutMs:e.definition.hitl.timeoutMs}},source:{kind:`skill_action`,skillName:e.skill.name,skillPath:e.skill.rootDir,actionName:e.actionName,actionFile:e.actionFile}});function om(e){return{name:`skill_action_run`,label:`Skill Action Run`,description:`Run an action declared in a skill's actions.yml. Fails closed on invalid config or inputs.`,parameters:jp,async execute(t,n,r){let i=await rm({dataDir:e.dataDir,pluginDirs:e.pluginDirs,skillsLoadPaths:e.skillsLoadPaths,skillName:n.skillName,skillPath:n.skillPath,action:n.action,inputs:n.inputs});if(i.ok===!1)return ef(i.error);try{Ld(e.workspaceDir,i.value.definition.workdir)}catch(e){return ef(e instanceof Error?e.message:String(e))}let a=am(i.value);return i.value.definition.hitl?.required===!0?await df({options:e,toolName:`skill_action_run`,toolCallId:t,guardedParams:a,actionHash:i.value.actionHash,signal:r}):await uf(e,t,a,r)}}}const sm=q.Object({status:q.Union([q.Literal(`complete`),q.Literal(`blocked`)],{description:`Terminal goal status to submit. Use 'complete' only when the objective is genuinely achieved; use 'blocked' when user input or external state is required.`}),summary:q.Optional(q.String({description:`Required for complete: concise final summary of what was achieved.`})),completedTasks:q.Optional(q.Array(q.Object({taskId:q.String({description:`Required task id covered by this completion report entry.`}),evidence:q.Array(q.Object({criterionId:q.String({description:`Acceptance criterion id covered by this evidence.`}),summary:q.String({description:`Manual evidence summary for this acceptance criterion.`}),source:q.String({description:`Where the evidence came from, such as a test command output, file path, or manual review note.`})}))}),{description:`Required for complete: one entry for every required task, with evidence covering every required acceptance criterion.`})),reason:q.Optional(q.String({description:`Required for blocked: concise reason the goal cannot continue.`})),neededInput:q.Optional(q.String({description:`For blocked: exact user input or external condition needed to proceed.`})),risks:q.Optional(q.Array(q.String({description:`Residual risk or follow-up note.`})))});function cm(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function lm(e,t){return cm({ok:!1,error:e,...t})}function um(e){return`warning`in e?e.warning:null}function Q(e){return{storeName:e}}function dm(e){return[...new Set(e.filter(e=>e.trim().length>0))]}async function fm(e,t,n){try{return await Qn(e,t,Q(n))}catch(e){if(e instanceof Hn)return{corrupt:!0};throw e}}function pm(e,t,n,r){let i=n?.trim()?`${t} (needed: ${n.trim()})`:t,a=e.currentTaskId;return{...e,status:`blocked`,blockedReason:i,updatedAt:r,tasks:e.tasks.map(e=>e.id===a?{...e,status:`blocked`,blockedReason:i,updatedAt:r}:e)}}function mm(e,t){let n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`blocked`).map(e=>e.id);if(r.length>0)return{ok:!1,error:`blocked_tasks_remain`,extra:{blockedTaskIds:r}};if(!t||t.length===0)return{ok:!1,error:`missing_completed_tasks`};let i=new Map(e.tasks.map(e=>[e.id,e])),a=new Map;for(let e of t){let t=e.taskId?.trim();if(!t)return{ok:!1,error:`missing_completed_task_id`};let n=i.get(t);if(!n)return{ok:!1,error:`unknown_completed_task`,extra:{taskId:t}};if(n.acceptanceCriteria.length===0)return{ok:!1,error:`missing_acceptance_criteria`,extra:{taskId:t}};let r=new Map(n.acceptanceCriteria.map(e=>[e.id,e])),o=a.get(t)??new Map;a.set(t,o);for(let n of e.evidence??[]){let e=n.criterionId?.trim();if(!e)return{ok:!1,error:`missing_criterion_id`,extra:{taskId:t}};if(!r.has(e))return{ok:!1,error:`unknown_acceptance_criterion`,extra:{taskId:t,criterionId:e}};let i=n.summary?.trim();if(!i)return{ok:!1,error:`missing_evidence_summary`,extra:{taskId:t,criterionId:e}};let a=n.source?.trim();if(!a)return{ok:!1,error:`missing_evidence_source`,extra:{taskId:t,criterionId:e}};let s=o.get(e)??[];s.push({criterionId:e,summary:i,source:a}),o.set(e,s)}}let o=n.filter(e=>!a.has(e.id)).map(e=>e.id);if(o.length>0)return{ok:!1,error:`missing_required_completed_task`,extra:{missingTaskIds:o}};for(let e of n){let t=a.get(e.id),n=e.acceptanceCriteria.filter(e=>e.required!==!1);for(let r of n)if((t.get(r.id)??[]).length===0)return{ok:!1,error:`missing_required_acceptance_evidence`,extra:{taskId:e.id,criterionId:r.id}}}return{ok:!0,report:a}}async function hm(e,t,n,r,i){let a=new Map,o=new Map,s=new Map(n.tasks.map(e=>[e.id,e])),c=[];for(let[n,l]of r.entries()){let r=s.get(n);if(!r)continue;let u=[],d=[],f=new Map(r.acceptanceCriteria.map(e=>[e.id,e]));for(let[a,o]of l.entries()){let s=f.get(a);if(s){for(let l of o){let o=await yr(e,t,{kind:`manual`,summary:`Goal completion ${n}/${a}: ${l.summary}`,content:[`Task: ${r.id} - ${r.title}`,`Acceptance criterion: ${s.id} - ${s.text}`,`Evidence: ${l.summary}`,`Source: ${l.source}`].join(`
89
- `),source:l.source},Q(i));if(`error`in o)return{ok:!1,error:o.error};u.push(o.evidenceRef),c.push(o.evidenceRef)}d.push(a)}}a.set(n,dm(u)),o.set(n,dm(d))}return{ok:!0,refsByTask:a,criteriaByTask:o,allRefs:dm(c)}}function gm(e,t,n,r,i){return{...e,status:`complete`,currentTaskId:null,blockedReason:null,finalEvidenceRefs:r,completedAt:i,updatedAt:i,tasks:e.tasks.map(e=>e.required===!1?e:{...e,status:`done`,blockedReason:null,acceptanceEvidence:dm([...e.acceptanceEvidence??[],...n.get(e.id)??[]]),evidenceRefs:dm([...e.evidenceRefs??[],...t.get(e.id)??[]]),updatedAt:i})}}function _m(e,t,n){return{name:`goal`,label:`Goal`,description:`Submit a terminal update for the current thread goal. Use only when the goal is complete or genuinely blocked; current goal context is injected by the runtime.`,parameters:sm,async execute(r,i){let a=await H(e,t,Q(n));return a?a.status===`complete`?cm({ok:!0,goalStatus:`complete`,alreadyComplete:!0}):Gn(e,t,Q(n),async()=>{let r=await fm(e,t,n);if(r===null)return lm(`workflow_not_initialized`);if(`corrupt`in r)return lm(`workflow_corrupt`);let o=new Date().toISOString();if(i.status===`blocked`){let s=i.reason?.trim();if(!s)return lm(`missing_reason`);let c=pm(r,s,i.neededInput,o);await pr(e,t,c,Q(n)),await vr(e,t,{type:`goal_task_blocked`,goalId:r.goalId,taskId:r.currentTaskId??void 0,reason:s,neededInput:i.neededInput,evidenceRefs:[]},Q(n)),await gr(e,t,{risks:[c.blockedReason??s]},Q(n));let l=await _r(e,t,c,Q(n));return cm({ok:!0,goalStatus:a.status,workflowStatus:`blocked`,warning:um(l)})}let s=i.summary?.trim();if(!s)return lm(`missing_summary`);let c=mm(r,i.completedTasks);if(c.ok===!1)return lm(c.error,c.extra);let l=await hm(e,t,r,c.report,n);if(l.ok===!1)return lm(l.error);let u=gm(r,l.refsByTask,l.criteriaByTask,l.allRefs,o);await pr(e,t,u,Q(n));try{await V(e,t,{status:`complete`},{...Q(n),eventSource:`tool`})}catch(i){throw await pr(e,t,r,Q(n)),i}await vr(e,t,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:l.allRefs,summary:s,risks:i.risks??[]},Q(n)),await gr(e,t,{finalSummary:s,evidence:l.allRefs,risks:i.risks},Q(n));let d=await _r(e,t,u,Q(n));return cm({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,evidenceRefs:l.allRefs,warning:um(d)})}):lm(`goal_not_found`)}}}q.Object({}),q.Object({status:q.String({description:`Status to set. Only 'complete' is allowed.`})});const vm=q.Union([q.Literal(`pending`),q.Literal(`in_progress`),q.Literal(`completed`)]),ym=q.Object({explanation:q.Optional(q.String({description:`Optional short explanation for why the plan is being updated.`})),tasks:q.Array(q.Object({content:q.String({description:`Short user-visible task description.`}),status:vm}),{description:`Full current task list snapshot in display order.`})}),bm=new Set([`pending`,`in_progress`,`completed`]);function xm(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}function Sm(e){if(!Array.isArray(e.tasks)||e.tasks.length===0)return{ok:!1,error:`empty_tasks`};let t=0,n=[];for(let r of e.tasks){if(!r||typeof r!=`object`)return{ok:!1,error:`invalid_task`};let e=typeof r.content==`string`?r.content.trim():``;if(!e)return{ok:!1,error:`empty_task_content`};let i=r.status;if(!bm.has(i))return{ok:!1,error:`invalid_task_status`};i===`in_progress`&&(t+=1),n.push({content:e,status:i})}if(t>1)return{ok:!1,error:`multiple_in_progress_tasks`};let r=typeof e.explanation==`string`?e.explanation.trim():``;return{ok:!0,...r?{explanation:r}:{},tasks:n}}function Cm(e={}){return{name:`update_task`,label:`Update Task`,description:`Maintain a lightweight task plan for the current coding session. The plan is shown to the user and should help them understand progress on non-trivial work.
87
+ `)}\n</available_skills>`}const Dp=q.Object({category:q.Optional(q.String({description:`Reserved category filter field. Not used yet.`}))}),Op=q.Object({name:q.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:q.Optional(q.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function kp(e,t,n=[]){return[...n,...t,mp(e)]}function Ap(e,t,n=[]){let r=kp(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Dp,async execute(e,t){let n=await Sp(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 jp(e){let t=kp(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:Op,async execute(r,i){let a=await Tp(t,i.name,i.skillPath);return a?(n.has(a.skill.name)||(n.add(a.skill.name),await e.reportSkillUsed?.({type:`skill_used`,skillName:a.skill.name,agent:`aimax:main`,taskId:`aimax[${e.sessionId}]`})),{content:[{type:`text`,text:JSON.stringify({success:!0,name:a.skill.name,description:a.skill.description,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime,content:a.content,path:a.skill.location,usage_hint:`This returns only SKILL.md. If the skill references other files, read them later with normal file tools using paths relative to the skill directory.`})}],details:{name:a.skill.name,description:a.skill.description,content:a.content,path:a.skill.location,version:a.skill.version,skillFileMtime:a.skill.skillFileMtime}}):{content:[{type:`text`,text:JSON.stringify({success:!1,error:i.skillPath?.trim()?`Skill '${i.name}' not found at '${i.skillPath}'.`:`Skill '${i.name}' not found.`})}],details:{name:i.name,description:``,content:``,path:``,version:``,skillFileMtime:``}}}}}const Mp=q.Object({skillName:q.Optional(q.String({description:`Skill name from the available skills registry`})),skillPath:q.Optional(q.String({description:`Optional explicit path to a skill directory or SKILL.md`})),action:q.String({description:`Action name declared in actions.yml`}),inputs:q.Optional(q.Record(q.String(),q.Unknown()))}),Np=/^[a-z][a-z0-9_-]{0,63}$/,Pp=[`low`,`medium`,`high`,`critical`],Fp=[`deny`,`cancel`],Ip=(e,t,n=[])=>[...n,...t,mp(e)],Lp=e=>{let t=K.resolve(e),n=K.basename(t)===`SKILL.md`?t:K.join(t,`SKILL.md`);return{rootDir:K.dirname(n),skillFile:n}};async function Rp(e){if(!e.skillName?.trim()&&!e.skillPath?.trim())return X(`skill_action_run requires either skillName or skillPath.`);if(e.skillPath?.trim()){let t=Lp(e.skillPath),n=K.basename(t.rootDir),r=e.skillName?.trim()||n;return e.skillName?.trim()&&e.skillName.trim()!==n?X(`skillName '${e.skillName}' does not match skillPath '${e.skillPath}'.`):await G.access(t.skillFile).then(()=>Y({name:r,rootDir:t.rootDir,skillFile:t.skillFile})).catch(()=>X(`Skill '${r}' not found at '${e.skillPath}'.`))}return await Cp(Ip(e.dataDir,e.pluginDirs,e.skillsLoadPaths),e.skillName??``).then(t=>t?Y({name:t.skill.name,rootDir:t.rootDir,skillFile:t.skill.location}):X(`Skill '${e.skillName}' not found.`))}async function zp(e){let t=K.join(e.rootDir,`actions.yml`),n=K.join(e.rootDir,`actions.yaml`),[r,i]=await Promise.all([G.access(t).then(()=>!0).catch(()=>!1),G.access(n).then(()=>!0).catch(()=>!1)]);return r&&i?X(`Skill '${e.name}' has both actions.yml and actions.yaml. Keep only actions.yml.`):r||i?await G.readFile(r?t:n,`utf-8`).then(e=>Y({path:r?t:n,content:e})).catch(t=>X(`Failed to read actions file for skill '${e.name}': ${String(t)}`)):X(`Skill '${e.name}' does not define actions.yml.`)}const Bp=(e,t)=>{try{return Y(nn(t))}catch(t){return X(`Invalid actions.yml for skill '${e}': ${t instanceof Error?t.message:String(t)}`)}},Vp=e=>typeof e.shell==`string`!==Array.isArray(e.argv),Hp=(e,t)=>Z(t)?Vp(t)?typeof t.shell==`string`&&t.shell.trim()?Y({shell:t.shell}):Array.isArray(t.argv)&&t.argv.every(e=>typeof e==`string`&&e.trim())?Y({argv:t.argv}):X(`Action '${e}' has an invalid command definition.`):X(`Action '${e}' must define exactly one of command.shell or command.argv.`):X(`Action '${e}' must define command.shell or command.argv.`),Up=(e,t)=>t===void 0?Y(void 0):Z(t)?Object.entries(t).every(([e,t])=>e.trim()&&typeof t==`string`)?Y(t):X(`Action '${e}' env values must be strings.`):X(`Action '${e}' env must be an object.`),Wp=(e,t)=>t===void 0?Y(void 0):Z(t)?Y(t):X(`Action '${e}' inputSchema must be an object schema.`),Gp=(e,t)=>t===void 0?Y(void 0):Z(t)?Ad(Gd([[`includeCommand`,Ud(`Action '${e}' hitl.preview`,t,`includeCommand`)],[`includeInputs`,Ud(`Action '${e}' hitl.preview`,t,`includeInputs`)],[`includeScriptHash`,Ud(`Action '${e}' hitl.preview`,t,`includeScriptHash`)],[`text`,Vd(`Action '${e}' hitl.preview`,t,`text`)]]),e=>e):X(`Action '${e}' hitl.preview must be an object.`),Kp=(e,t)=>{let n=`Action '${e}' hitl`;return t===void 0?Y(void 0):Z(t)?typeof t.required==`boolean`?Ad(Gd([[`title`,Vd(n,t,`title`)],[`reason`,Vd(n,t,`reason`)],[`risk`,Wd(n,t,`risk`,Pp)],[`timeoutMs`,Hd(n,t,`timeoutMs`)],[`defaultOnTimeout`,Wd(n,t,`defaultOnTimeout`,Fp)],[`preview`,Gp(e,t.preview)]]),e=>({required:t.required,...e})):X(`${n}.required must be true or false.`):X(`${n} must be an object.`)},qp=(e,t)=>Ad(Gd([[`inputSchema`,Wp(e,t.inputSchema)],[`workdir`,Vd(`Action '${e}'`,t,`workdir`)],[`env`,Up(e,t.env)],[`timeout`,Hd(`Action '${e}'`,t,`timeout`)],[`yieldMs`,Hd(`Action '${e}'`,t,`yieldMs`)],[`background`,Ud(`Action '${e}'`,t,`background`)],[`hitl`,Kp(e,t.hitl)]]),e=>e),Jp=(e,t)=>Np.test(e)?Z(t)?Md(t.description)?jd(Hp(e,t.command),n=>Ad(qp(e,t),e=>({description:Md(t.description),command:n,...e}))):X(`Action '${e}' is missing description.`):X(`Action '${e}' must be an object.`):X(`Invalid action name '${e}'. Use lowercase letters, numbers, '_' or '-'.`),Yp=e=>Object.entries(e).reduce((e,[t,n])=>jd(e,e=>Ad(Jp(t,n),n=>({...e,[t]:n}))),Y({})),Xp=(e,t)=>Z(t)?t.version===1?!Z(t.actions)||Object.keys(t.actions).length===0?X(`actions.yml for skill '${e}' must define non-empty actions.`):Ad(Yp(t.actions),e=>({version:1,actions:e})):X(`actions.yml for skill '${e}' must set version: 1.`):X(`actions.yml for skill '${e}' must be an object.`),Zp=e=>e===void 0?Y({}):Z(e)?Y(e):X(`skill_action_run inputs must be an object.`),Qp=()=>new rn({allErrors:!0,strict:!1}),$p=(e,t,n)=>{if(!t)return Object.keys(n).length===0?Y(n):X(`Action '${e}' does not accept inputs.`);if(t.type!==`object`||!Z(t.properties))return X(`Action '${e}' inputSchema must be an object schema with properties.`);let r=Qp().compile(t);return r(n)?Y(n):X(`Invalid inputs for action '${e}': ${Qp().errorsText(r.errors)}`)},em=e=>Z(e.inputSchema?.properties)?Object.keys(e.inputSchema.properties):[],tm=e=>{let t=`shell`in e.command?Kd(e.command.shell):e.command.argv.flatMap(Kd),n=new Set(em(e)),r=t.filter(e=>!n.has(e));return r.length===0?Y(e):X(`Action command references undeclared input field(s): ${r.join(`, `)}.`)},nm=(e,t)=>e.reduce((e,n)=>jd(e,e=>Ad(Yd(n,t),t=>[...e,t])),Y([])),rm=(e,t)=>`shell`in e.command?Yd(e.command.shell,t):Ad(nm(e.command.argv,t),e=>e.map(qd).join(` `));async function im(e){let t=await Rp(e);if(t.ok===!1)return X(t.error);let n=await zp(t.value);if(n.ok===!1)return X(n.error);let r=jd(Bp(t.value.name,n.value.content),e=>Xp(t.value.name,e));if(r.ok===!1)return X(r.error);let i=r.value.actions[e.action];return i?jd(tm(i),r=>jd(Zp(e.inputs),i=>jd($p(e.action,r.inputSchema,i),i=>Ad(rm(r,i),a=>({skill:t.value,actionName:e.action,actionFile:n.value.path,definition:r,inputs:i,command:a,actionHash:Ld({version:1,skillName:t.value.name,skillPath:t.value.rootDir,actionName:e.action,actionsFilePath:n.value.path,actionDefinition:r,inputs:i,renderedCommand:a})}))))):X(`Skill '${t.value.name}' does not define action '${e.action}'.`)}const am=e=>[e.definition.hitl?.preview?.text?.trim()?`${e.definition.hitl.preview.text.trim()}\n`:``,`### Skill Action`,`- Skill: ${e.skill.name}`,`- Action: ${e.actionName}`,`- Risk: ${e.definition.hitl?.risk??`medium`}`,``,`### Inputs`,"```json",JSON.stringify(e.inputs,null,2),"```",``,`### Command`,"```bash",e.command,"```",``,`Action hash: ${e.actionHash}`].filter(Boolean).join(`
88
+ `),om=e=>({command:e.command,...e.definition.workdir?{workdir:e.definition.workdir}:{},...e.definition.env?{env:e.definition.env}:{},...e.definition.timeout===void 0?{}:{timeout:e.definition.timeout},...e.definition.yieldMs===void 0?{}:{yieldMs:e.definition.yieldMs},...e.definition.background===void 0?{}:{background:e.definition.background},title:e.definition.hitl?.title||e.definition.description,reason:e.definition.hitl?.reason||`该 action 会执行业务脚本,需要用户确认。`,risk:e.definition.hitl?.risk??`medium`,preview:am(e),policy:{defaultOnTimeout:e.definition.hitl?.defaultOnTimeout??`deny`,...e.definition.hitl?.timeoutMs===void 0?{}:{timeoutMs:e.definition.hitl.timeoutMs}},source:{kind:`skill_action`,skillName:e.skill.name,skillPath:e.skill.rootDir,actionName:e.actionName,actionFile:e.actionFile}});function sm(e){return{name:`skill_action_run`,label:`Skill Action Run`,description:`Run an action declared in a skill's actions.yml. Fails closed on invalid config or inputs.`,parameters:Mp,async execute(t,n,r){let i=await im({dataDir:e.dataDir,pluginDirs:e.pluginDirs,skillsLoadPaths:e.skillsLoadPaths,skillName:n.skillName,skillPath:n.skillPath,action:n.action,inputs:n.inputs});if(i.ok===!1)return tf(i.error);try{Rd(e.workspaceDir,i.value.definition.workdir)}catch(e){return tf(e instanceof Error?e.message:String(e))}let a=om(i.value);return i.value.definition.hitl?.required===!0?await ff({options:e,toolName:`skill_action_run`,toolCallId:t,guardedParams:a,actionHash:i.value.actionHash,signal:r}):await df(e,t,a,r)}}}const cm=q.Object({status:q.Union([q.Literal(`complete`),q.Literal(`blocked`)],{description:`Terminal goal status to submit. Use 'complete' only when the objective is genuinely achieved; use 'blocked' when user input or external state is required.`}),summary:q.Optional(q.String({description:`Required for complete: concise final summary of what was achieved.`})),completedTasks:q.Optional(q.Array(q.Object({taskId:q.String({description:`Required task id covered by this completion report entry.`}),evidence:q.Array(q.Object({criterionId:q.String({description:`Acceptance criterion id covered by this evidence.`}),summary:q.String({description:`Manual evidence summary for this acceptance criterion.`}),source:q.String({description:`Where the evidence came from, such as a test command output, file path, or manual review note.`})}))}),{description:`Required for complete: one entry for every required task, with evidence covering every required acceptance criterion.`})),reason:q.Optional(q.String({description:`Required for blocked: concise reason the goal cannot continue.`})),neededInput:q.Optional(q.String({description:`For blocked: exact user input or external condition needed to proceed.`})),risks:q.Optional(q.Array(q.String({description:`Residual risk or follow-up note.`})))});function lm(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function um(e,t){return lm({ok:!1,error:e,...t})}function dm(e){return`warning`in e?e.warning:null}function Q(e){return{storeName:e}}function fm(e){return[...new Set(e.filter(e=>e.trim().length>0))]}async function pm(e,t,n){try{return await Qn(e,t,Q(n))}catch(e){if(e instanceof Hn)return{corrupt:!0};throw e}}function mm(e,t,n,r){let i=n?.trim()?`${t} (needed: ${n.trim()})`:t,a=e.currentTaskId;return{...e,status:`blocked`,blockedReason:i,updatedAt:r,tasks:e.tasks.map(e=>e.id===a?{...e,status:`blocked`,blockedReason:i,updatedAt:r}:e)}}function hm(e,t){let n=e.tasks.filter(e=>e.required!==!1),r=n.filter(e=>e.status===`blocked`).map(e=>e.id);if(r.length>0)return{ok:!1,error:`blocked_tasks_remain`,extra:{blockedTaskIds:r}};if(!t||t.length===0)return{ok:!1,error:`missing_completed_tasks`};let i=new Map(e.tasks.map(e=>[e.id,e])),a=new Map;for(let e of t){let t=e.taskId?.trim();if(!t)return{ok:!1,error:`missing_completed_task_id`};let n=i.get(t);if(!n)return{ok:!1,error:`unknown_completed_task`,extra:{taskId:t}};if(n.acceptanceCriteria.length===0)return{ok:!1,error:`missing_acceptance_criteria`,extra:{taskId:t}};let r=new Map(n.acceptanceCriteria.map(e=>[e.id,e])),o=a.get(t)??new Map;a.set(t,o);for(let n of e.evidence??[]){let e=n.criterionId?.trim();if(!e)return{ok:!1,error:`missing_criterion_id`,extra:{taskId:t}};if(!r.has(e))return{ok:!1,error:`unknown_acceptance_criterion`,extra:{taskId:t,criterionId:e}};let i=n.summary?.trim();if(!i)return{ok:!1,error:`missing_evidence_summary`,extra:{taskId:t,criterionId:e}};let a=n.source?.trim();if(!a)return{ok:!1,error:`missing_evidence_source`,extra:{taskId:t,criterionId:e}};let s=o.get(e)??[];s.push({criterionId:e,summary:i,source:a}),o.set(e,s)}}let o=n.filter(e=>!a.has(e.id)).map(e=>e.id);if(o.length>0)return{ok:!1,error:`missing_required_completed_task`,extra:{missingTaskIds:o}};for(let e of n){let t=a.get(e.id),n=e.acceptanceCriteria.filter(e=>e.required!==!1);for(let r of n)if((t.get(r.id)??[]).length===0)return{ok:!1,error:`missing_required_acceptance_evidence`,extra:{taskId:e.id,criterionId:r.id}}}return{ok:!0,report:a}}async function gm(e,t,n,r,i){let a=new Map,o=new Map,s=new Map(n.tasks.map(e=>[e.id,e])),c=[];for(let[n,l]of r.entries()){let r=s.get(n);if(!r)continue;let u=[],d=[],f=new Map(r.acceptanceCriteria.map(e=>[e.id,e]));for(let[a,o]of l.entries()){let s=f.get(a);if(s){for(let l of o){let o=await yr(e,t,{kind:`manual`,summary:`Goal completion ${n}/${a}: ${l.summary}`,content:[`Task: ${r.id} - ${r.title}`,`Acceptance criterion: ${s.id} - ${s.text}`,`Evidence: ${l.summary}`,`Source: ${l.source}`].join(`
89
+ `),source:l.source},Q(i));if(`error`in o)return{ok:!1,error:o.error};u.push(o.evidenceRef),c.push(o.evidenceRef)}d.push(a)}}a.set(n,fm(u)),o.set(n,fm(d))}return{ok:!0,refsByTask:a,criteriaByTask:o,allRefs:fm(c)}}function _m(e,t,n,r,i){return{...e,status:`complete`,currentTaskId:null,blockedReason:null,finalEvidenceRefs:r,completedAt:i,updatedAt:i,tasks:e.tasks.map(e=>e.required===!1?e:{...e,status:`done`,blockedReason:null,acceptanceEvidence:fm([...e.acceptanceEvidence??[],...n.get(e.id)??[]]),evidenceRefs:fm([...e.evidenceRefs??[],...t.get(e.id)??[]]),updatedAt:i})}}function vm(e,t,n){return{name:`goal`,label:`Goal`,description:`Submit a terminal update for the current thread goal. Use only when the goal is complete or genuinely blocked; current goal context is injected by the runtime.`,parameters:cm,async execute(r,i){let a=await H(e,t,Q(n));return a?a.status===`complete`?lm({ok:!0,goalStatus:`complete`,alreadyComplete:!0}):Gn(e,t,Q(n),async()=>{let r=await pm(e,t,n);if(r===null)return um(`workflow_not_initialized`);if(`corrupt`in r)return um(`workflow_corrupt`);let o=new Date().toISOString();if(i.status===`blocked`){let s=i.reason?.trim();if(!s)return um(`missing_reason`);let c=mm(r,s,i.neededInput,o);await pr(e,t,c,Q(n)),await vr(e,t,{type:`goal_task_blocked`,goalId:r.goalId,taskId:r.currentTaskId??void 0,reason:s,neededInput:i.neededInput,evidenceRefs:[]},Q(n)),await gr(e,t,{risks:[c.blockedReason??s]},Q(n));let l=await _r(e,t,c,Q(n));return lm({ok:!0,goalStatus:a.status,workflowStatus:`blocked`,warning:dm(l)})}let s=i.summary?.trim();if(!s)return um(`missing_summary`);let c=hm(r,i.completedTasks);if(c.ok===!1)return um(c.error,c.extra);let l=await gm(e,t,r,c.report,n);if(l.ok===!1)return um(l.error);let u=_m(r,l.refsByTask,l.criteriaByTask,l.allRefs,o);await pr(e,t,u,Q(n));try{await V(e,t,{status:`complete`},{...Q(n),eventSource:`tool`})}catch(i){throw await pr(e,t,r,Q(n)),i}await vr(e,t,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:l.allRefs,summary:s,risks:i.risks??[]},Q(n)),await gr(e,t,{finalSummary:s,evidence:l.allRefs,risks:i.risks},Q(n));let d=await _r(e,t,u,Q(n));return lm({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,evidenceRefs:l.allRefs,warning:dm(d)})}):um(`goal_not_found`)}}}q.Object({}),q.Object({status:q.String({description:`Status to set. Only 'complete' is allowed.`})});const ym=q.Union([q.Literal(`pending`),q.Literal(`in_progress`),q.Literal(`completed`)]),bm=q.Object({explanation:q.Optional(q.String({description:`Optional short explanation for why the plan is being updated.`})),tasks:q.Array(q.Object({content:q.String({description:`Short user-visible task description.`}),status:ym}),{description:`Full current task list snapshot in display order.`})}),xm=new Set([`pending`,`in_progress`,`completed`]);function Sm(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}function Cm(e){if(!Array.isArray(e.tasks)||e.tasks.length===0)return{ok:!1,error:`empty_tasks`};let t=0,n=[];for(let r of e.tasks){if(!r||typeof r!=`object`)return{ok:!1,error:`invalid_task`};let e=typeof r.content==`string`?r.content.trim():``;if(!e)return{ok:!1,error:`empty_task_content`};let i=r.status;if(!xm.has(i))return{ok:!1,error:`invalid_task_status`};i===`in_progress`&&(t+=1),n.push({content:e,status:i})}if(t>1)return{ok:!1,error:`multiple_in_progress_tasks`};let r=typeof e.explanation==`string`?e.explanation.trim():``;return{ok:!0,...r?{explanation:r}:{},tasks:n}}function wm(e={}){return{name:`update_task`,label:`Update Task`,description:`Maintain a lightweight task plan for the current coding session. The plan is shown to the user and should help them understand progress on non-trivial work.
90
90
 
91
91
  Use this tool when:
92
92
  - The user request has multiple meaningful steps or phases.
@@ -119,80 +119,80 @@ Numbered/Listed Step Protocol:
119
119
  - The initial \`update_task\` call must include the ordered list with the first task \`in_progress\` and later tasks \`pending\`.
120
120
  - After completing task N, and before any tool call that starts task N+1, call \`update_task\` with task N \`completed\` and task N+1 \`in_progress\`.
121
121
  - Never start work for task N+1 while task N is still \`in_progress\`.
122
- - Do not mark multiple newly completed listed tasks in one update unless they were completed by the same single tool result.`,parameters:ym,async execute(t,n){let r=Sm(n);return r.ok===!1?xm({ok:!1,error:r.error}):(await e.reportTaskUpdated?.({type:`task_updated`,toolCallId:t,...r.explanation?{explanation:r.explanation}:{},tasks:r.tasks,updatedAt:new Date().toISOString()}),xm({ok:!0,updated:!0,taskCount:r.tasks.length}))}}}var wm=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Ai(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=Fi(e.path),n=Am(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 Yi(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:ji(this.rootDir)}}async createSkill(e){let t=Ii(e.name),n=Fi(e.categoryPath),r=Am(e.description,`auto-skill description`),i=jm(e.body);await this.assertCategoryExists(n);let a=Li(n,t),o=Bi(this.rootDir,n,t);if(await Om(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=K.join(o,`SKILL.md`),l=K.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:Mm(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:Nm(e.evidence,s)};return await G.mkdir(o,{recursive:!0}),await G.writeFile(c,Tm(t,r,i),`utf-8`),await km(l,u),await Yi(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=Ri(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Bi(this.rootDir,t.categoryPath,t.skillName),r=K.join(n,`SKILL.md`),i=K.join(n,`metadata.json`),a=await Em(r),o=await Dm(i),s=e.description===void 0?a.description:Am(e.description,`auto-skill description`),c=e.body===void 0?a.body:jm(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?Mm(o.tags):Mm(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:{},...Nm(e.evidence,l)}};return await G.writeFile(r,Tm(t.skillName,s,c),`utf-8`),await km(i,u),await Yi(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=Ri(e.skillId),n=Bi(this.rootDir,t.categoryPath,t.skillName),r=K.join(n,`metadata.json`),i=K.join(n,`SKILL.md`);await G.access(i);let a=await Dm(r),o=this.now().toISOString();return await km(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...Nm(e.evidence,o)}}),await Yi(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=ji(this.rootDir),t;try{t=await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=Fi(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await G.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await km(ji(this.rootDir),t)}};function Tm(e,t,n){return[`---`,`name: ${Pm(e)}`,`description: ${Pm(t)}`,`---`,``,n.trim(),``].join(`
123
- `)}async function Em(e){let t=Vt(await G.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Dm(e){let t;try{t=await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}async function Om(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function km(e,t){await G.mkdir(K.dirname(e),{recursive:!0}),await G.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Am(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function jm(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 Mm(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Nm(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Pm(e){return JSON.stringify(e)}const Fm=[`create`,`update`,`archive`,`create_category`],Im=q.Object({}),Lm=q.Object({categoryPath:q.Optional(q.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:q.Optional(q.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),Rm=q.Object({query:q.String({description:`Search query for learned auto-skills.`}),limit:q.Optional(q.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),zm=q.Object({skillId:q.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:q.Optional(q.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),Bm=q.Object({action:q.Union(Fm.map(e=>q.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:q.Optional(q.String({description:`Exact auto-skill id for update/archive.`})),name:q.Optional(q.String({description:`Auto-skill slug for create.`})),categoryPath:q.Optional(q.String({description:`Existing single-level category slug for create.`})),newCategory:q.Optional(q.Object({path:q.String({description:`New single-level category slug to create.`}),description:q.String({description:`New category description.`})})),description:q.Optional(q.String({description:`Auto-skill description for create/update.`})),tags:q.Optional(q.Array(q.String({description:`Auto-skill tag.`}))),confidence:q.Optional(q.Number({description:`Optional confidence score from 0 to 1.`})),body:q.Optional(q.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:q.Optional(q.Object({sessionId:q.String({description:`Source session id.`}),reason:q.String({description:`Why this auto-skill write is justified.`}),toolCallCount:q.Optional(q.Number({description:`Tool calls observed in source run.`})),loadedSkills:q.Optional(q.Array(q.String({description:`Skill loaded during source run.`})))}))});function Vm(e){let t=new Xi({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:Im,async execute(){try{let e=await t.autoSkillCategories();return qm({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return qm({categories:[],count:0,error:Jm(e)})}}}}function Hm(e){let t=new Xi({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:Lm,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return qm({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return qm({skills:[],count:0,error:Jm(e)})}}}}function Um(e){let t=new Xi({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:Rm,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return qm({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return qm({skills:[],count:0,error:Jm(e)})}}}}function Wm(e){let t=new Xi({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:zm,async execute(e,n){try{return qm({...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 qm({skillId:n.skillId,error:Jm(e)})}}}}function Gm(e){let t=new wm({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:Bm,async execute(e,n){try{return qm(await Km(t,n))}catch(e){return qm({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:Jm(e)})}}}}async function Km(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 qm(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Jm(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const Ym=2,Xm=5;var Zm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),W.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:oe(e.task),startedAt:e.startedAt})}complete(e,t,n){let r=this.entries.get(e);!r||r.record.status!==`running`||(r.record.status=`done`,r.record.result=t,n&&n.length>0&&(r.record.artifacts=n),r.record.endedAt=Date.now(),this.logTerminalStatus(r.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&W.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){W.info(`subagent status changed`,t);return}if(e.status===`killed`){W.warn(`subagent status changed`,t);return}W.error(`subagent status changed`,t)}};const Qm=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),$m=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),eh=q.Object({tasks:q.Array(Qm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function th(e){let t=e.label?`"${e.label}"`:`task: ${At(e.task)}`;return e.status===`done`?`${t}\n\n${nh(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function nh(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 rh(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(W.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:oe(p)}),!p){let e={status:`error`,error:`task must not be empty`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Lt(),v=new AbortController,y=t,b=Ea(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await T(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return W.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}W.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let C=f({dataDir:s,sessionId:y,message:b?Ma(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)`,e.artifacts)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,C),W.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,W.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let w=th({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??``,...S.artifacts&&S.artifacts.length>0?{artifacts:S.artifacts}:{}};return W.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:w}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return W.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:w}],isError:!0,details:E}}function ih(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:$m,async execute(e,t){return rh(u,e,t)}}}function ah(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:eh,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}W.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await rh(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`Batch subagents: ${o.length-d.length}/${o.length} completed.`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${nh(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
122
+ - Do not mark multiple newly completed listed tasks in one update unless they were completed by the same single tool result.`,parameters:bm,async execute(t,n){let r=Cm(n);return r.ok===!1?Sm({ok:!1,error:r.error}):(await e.reportTaskUpdated?.({type:`task_updated`,toolCallId:t,...r.explanation?{explanation:r.explanation}:{},tasks:r.tasks,updatedAt:new Date().toISOString()}),Sm({ok:!0,updated:!0,taskCount:r.tasks.length}))}}}var Tm=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=K.resolve(e.rootDir??Ai(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=Fi(e.path),n=jm(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 Yi(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:ji(this.rootDir)}}async createSkill(e){let t=Ii(e.name),n=Fi(e.categoryPath),r=jm(e.description,`auto-skill description`),i=Mm(e.body);await this.assertCategoryExists(n);let a=Li(n,t),o=Bi(this.rootDir,n,t);if(await km(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=K.join(o,`SKILL.md`),l=K.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:Nm(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:Pm(e.evidence,s)};return await G.mkdir(o,{recursive:!0}),await G.writeFile(c,Em(t,r,i),`utf-8`),await Am(l,u),await Yi(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=Ri(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Bi(this.rootDir,t.categoryPath,t.skillName),r=K.join(n,`SKILL.md`),i=K.join(n,`metadata.json`),a=await Dm(r),o=await Om(i),s=e.description===void 0?a.description:jm(e.description,`auto-skill description`),c=e.body===void 0?a.body:Mm(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?Nm(o.tags):Nm(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:{},...Pm(e.evidence,l)}};return await G.writeFile(r,Em(t.skillName,s,c),`utf-8`),await Am(i,u),await Yi(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=Ri(e.skillId),n=Bi(this.rootDir,t.categoryPath,t.skillName),r=K.join(n,`metadata.json`),i=K.join(n,`SKILL.md`);await G.access(i);let a=await Om(r),o=this.now().toISOString();return await Am(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...Pm(e.evidence,o)}}),await Yi(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=ji(this.rootDir),t;try{t=await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=Fi(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await G.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await Am(ji(this.rootDir),t)}};function Em(e,t,n){return[`---`,`name: ${Fm(e)}`,`description: ${Fm(t)}`,`---`,``,n.trim(),``].join(`
123
+ `)}async function Dm(e){let t=Vt(await G.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Om(e){let t;try{t=await G.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}async function km(e){try{return await G.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Am(e,t){await G.mkdir(K.dirname(e),{recursive:!0}),await G.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function jm(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function Mm(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 Nm(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Pm(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Fm(e){return JSON.stringify(e)}const Im=[`create`,`update`,`archive`,`create_category`],Lm=q.Object({}),Rm=q.Object({categoryPath:q.Optional(q.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:q.Optional(q.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),zm=q.Object({query:q.String({description:`Search query for learned auto-skills.`}),limit:q.Optional(q.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),Bm=q.Object({skillId:q.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:q.Optional(q.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),Vm=q.Object({action:q.Union(Im.map(e=>q.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:q.Optional(q.String({description:`Exact auto-skill id for update/archive.`})),name:q.Optional(q.String({description:`Auto-skill slug for create.`})),categoryPath:q.Optional(q.String({description:`Existing single-level category slug for create.`})),newCategory:q.Optional(q.Object({path:q.String({description:`New single-level category slug to create.`}),description:q.String({description:`New category description.`})})),description:q.Optional(q.String({description:`Auto-skill description for create/update.`})),tags:q.Optional(q.Array(q.String({description:`Auto-skill tag.`}))),confidence:q.Optional(q.Number({description:`Optional confidence score from 0 to 1.`})),body:q.Optional(q.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:q.Optional(q.Object({sessionId:q.String({description:`Source session id.`}),reason:q.String({description:`Why this auto-skill write is justified.`}),toolCallCount:q.Optional(q.Number({description:`Tool calls observed in source run.`})),loadedSkills:q.Optional(q.Array(q.String({description:`Skill loaded during source run.`})))}))});function Hm(e){let t=new Xi({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:Lm,async execute(){try{let e=await t.autoSkillCategories();return Jm({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return Jm({categories:[],count:0,error:Ym(e)})}}}}function Um(e){let t=new Xi({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:Rm,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return Jm({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Jm({skills:[],count:0,error:Ym(e)})}}}}function Wm(e){let t=new Xi({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:zm,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return Jm({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Jm({skills:[],count:0,error:Ym(e)})}}}}function Gm(e){let t=new Xi({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:Bm,async execute(e,n){try{return Jm({...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 Jm({skillId:n.skillId,error:Ym(e)})}}}}function Km(e){let t=new Tm({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:Vm,async execute(e,n){try{return Jm(await qm(t,n))}catch(e){return Jm({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:Ym(e)})}}}}async function qm(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 Jm(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Ym(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const Xm=2,Zm=5;var Qm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),W.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:oe(e.task),startedAt:e.startedAt})}complete(e,t,n){let r=this.entries.get(e);!r||r.record.status!==`running`||(r.record.status=`done`,r.record.result=t,n&&n.length>0&&(r.record.artifacts=n),r.record.endedAt=Date.now(),this.logTerminalStatus(r.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&W.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){W.info(`subagent status changed`,t);return}if(e.status===`killed`){W.warn(`subagent status changed`,t);return}W.error(`subagent status changed`,t)}};const $m=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),eh=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),th=q.Object({tasks:q.Array($m,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function nh(e){let t=e.label?`"${e.label}"`:`task: ${At(e.task)}`;return e.status===`done`?`${t}\n\n${rh(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function rh(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 ih(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(W.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:oe(p)}),!p){let e={status:`error`,error:`task must not be empty`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Lt(),v=new AbortController,y=t,b=Ea(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return W.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await T(s,c,{storeName:d.sessionStoreName,subagent:x,sessionId:y})}catch(e){let t={status:`error`,error:`Failed to create session: ${e instanceof Error?e.message:String(e)}`};return W.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}W.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let C=f({dataDir:s,sessionId:y,message:b?Ma(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)`,e.artifacts)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,C),W.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,W.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let w=nh({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??``,...S.artifacts&&S.artifacts.length>0?{artifacts:S.artifacts}:{}};return W.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:w}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return W.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:w}],isError:!0,details:E}}function ah(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:eh,async execute(e,t){return ih(u,e,t)}}}function oh(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:th,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}W.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await ih(u,`${n}-${e+1}`,t)).details,index:e,task:t.task.trim(),label:t.label?.trim()}}};await Promise.all(Array.from({length:l},()=>e()))}let d=o.filter(e=>e.status!==`done`),f=d.length===0?`done`:d.length===o.length?`error`:`partial_error`,p={status:f,results:o},m=[`Batch subagents: ${o.length-d.length}/${o.length} completed.`,...o.map(e=>{let t=e.label?`"${e.label}"`:`#${e.index+1}`;return e.status===`done`?`- ${t}: done\n${rh(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
124
124
 
125
- `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const oh=q.Object({action:q.Union([`list`,`kill`].map(e=>q.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:q.Optional(q.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function sh(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 ch(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 lh(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:oh,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} (${sh(e.runtimeMs)})${n}`})).join(`
126
- `)};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=ch(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}function uh(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 dh(e){let t=uh(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=K.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function fh(e){let t=e.watchFactory??((e,t,n)=>Wt.watch(e,t,n)),n=K.join(e.dataDir,`.aimax`),r=[{target:K.join(n,`MEMORY.md`),kind:`memory-file`},{target:K.join(n,`memory.md`),kind:`memory-file-lower`},{target:K.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=dh({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}function $(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}function ph(e){return e.projectDir?.trim()||K.join(e.dataDir,`workspace`)}async function mh(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=ph(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=vh(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??_.id})`:`memory_log routed to ${t} (provider=${p.providerId??_.id})`,details:{providerId:p.providerId??_.id,resolvedProviderId:g?.registration.id??_.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof _.appendRecent==`function`}}).catch(()=>{})}p.source===`sessions`?await n.dispatchDiagnostic(e.sessionId??i,{level:`info`,scope:`memory`,phase:p.reason,message:`session transcript changed`,details:{reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}}).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=K.join(t.dataDir,`.aimax`),m,g=(()=>{try{return Ke({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName,includeSessions:!0})}catch(e){if(!Ge(e))throw e;m=e instanceof Error?e.message:String(e);let t=hh(p,m);return{provider:t,providerId:t.id,providerSource:`builtin`,fallbackToBuiltin:!0}}})(),_=g.provider,v=g.providerId,y=g.pluginId;m&&await n.dispatchDiagnostic(i,{level:`warn`,scope:`memory`,phase:`memory_provider_degraded`,message:`builtin memory provider degraded after sqlite index failure`,details:{providerId:v,requestedProviderId:o,requestedPluginId:s,error:m}}).catch(()=>{}),await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:v,pluginId:y,providerSource:g.providerSource,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:g.fallbackToBuiltin}}).catch(()=>{});let b=fh({dataDir:t.dataDir,sessionId:i,providerId:o??s??v,provider:_,onMemoryChanged:f});_.sync&&_.sync(`session-start`).catch(()=>{});let x=async e=>{await h(t.dataDir,i,e,_h({sessionOptions:$(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,memoryProvider:_,memoryProviderSource:g.providerSource,memoryFallbackToBuiltin:g.fallbackToBuiltin,recallState:{recallProvided:!1},compactionRecallState:{recallProvided:!1},appendTranscriptEntry:x,persistInitialUserEntry:async e=>d?!1:(await x({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{b()}}}function hh(e,t){return{id:`builtin-memory`,name:`Builtin Memory Provider (degraded)`,status:()=>({backend:`builtin`,provider:`builtin-memory`,workspaceDir:e,dbPath:K.join(e,`.index.sqlite`),dirty:!0,fts:{enabled:!1,available:!1,error:t},vector:{enabled:!1,available:!1,loadError:t},custom:{searchMode:`unavailable`,fallbackActive:!0,fallbackReason:t}}),search:async()=>[],getLines:async()=>[],listFiles:async()=>[],append:async()=>{},updateFile:async()=>{},deleteFile:async()=>{},sync:async()=>{},noteSessionUpdate:()=>{}}}function gh(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function _h(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 vh(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}const yh=q.Object({image:q.String({description:`Image path or URL`}),prompt:q.Optional(q.String({description:`Prompt for image analysis`})),model:q.Optional(q.String({description:`Optional model override`})),maxBytesMb:q.Optional(q.Number({description:`Optional size cap in MB`}))});function bh(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:yh,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}}}}[`Use only the returned evidenceRef values from goal_record_evidence.`,`Natural-language descriptions, file paths, and strings such as 'goal/state.json ...' are not evidence refs unless they are registered in goal/artifacts/registry.jsonl.`,`If command output should prove an acceptance criterion, run it with goal_record_evidence(kind='exec'); regular exec output is not registered goal evidence.`].join(` `);function xh(e,t){let n=ph({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??Rn(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await A(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[qu({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),ff({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),Zu({registry:i,scopeKey:n}),id(n,t?.contextManager),od(n,t?.contextManager,s),cd(n,t?.contextManager,s),ud(n),_d(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),Cm({reportTaskUpdated:t?.reportTaskUpdated}),...t?.sessionId?[_m(e,t.sessionId,t.inheritedRunParams?.sessionStoreName)]:[],Df(e,r),Yf(e,r),kf(e,r),Nf(e,r),Vf(e,r),Uf(e,r),Gf(e,r),qf(e,r),kp(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Ap({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed}),om({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,sessionId:t?.sessionId,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv})];return a&&c.push(Vm(e),Hm(e),Um(e),Wm(e)),t&&c.push(ih(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),ah(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),lh(t.registry,t.parentSessionId)),c}function Sh(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(`
125
+ `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const sh=q.Object({action:q.Union([`list`,`kill`].map(e=>q.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:q.Optional(q.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function ch(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 lh(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 uh(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:sh,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} (${ch(e.runtimeMs)})${n}`})).join(`
126
+ `)};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=lh(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}function dh(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 fh(e){let t=dh(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=K.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function ph(e){let t=e.watchFactory??((e,t,n)=>Wt.watch(e,t,n)),n=K.join(e.dataDir,`.aimax`),r=[{target:K.join(n,`MEMORY.md`),kind:`memory-file`},{target:K.join(n,`memory.md`),kind:`memory-file-lower`},{target:K.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=fh({kind:e.kind,filename:n});if(r.length!==0){for(let e of r)a.add(e);l()}});n.on?.(`error`,()=>{try{n.close()}catch{}}),i.push(n)}catch{}return()=>{o&&=(clearTimeout(o),null);for(let e of i)try{e.close()}catch{}}}function $(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}function mh(e){return e.projectDir?.trim()||K.join(e.dataDir,`workspace`)}async function hh(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=mh(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=yh(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??_.id})`:`memory_log routed to ${t} (provider=${p.providerId??_.id})`,details:{providerId:p.providerId??_.id,resolvedProviderId:g?.registration.id??_.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof _.appendRecent==`function`}}).catch(()=>{})}p.source===`sessions`?await n.dispatchDiagnostic(e.sessionId??i,{level:`info`,scope:`memory`,phase:p.reason,message:`session transcript changed`,details:{reason:p.reason,files:p.files,source:p.source,providerId:p.providerId,timestamp:p.timestamp}}).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=K.join(t.dataDir,`.aimax`),m,g=(()=>{try{return Ke({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName,includeSessions:!0})}catch(e){if(!Ge(e))throw e;m=e instanceof Error?e.message:String(e);let t=gh(p,m);return{provider:t,providerId:t.id,providerSource:`builtin`,fallbackToBuiltin:!0}}})(),_=g.provider,v=g.providerId,y=g.pluginId;m&&await n.dispatchDiagnostic(i,{level:`warn`,scope:`memory`,phase:`memory_provider_degraded`,message:`builtin memory provider degraded after sqlite index failure`,details:{providerId:v,requestedProviderId:o,requestedPluginId:s,error:m}}).catch(()=>{}),await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:v,pluginId:y,providerSource:g.providerSource,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:g.fallbackToBuiltin}}).catch(()=>{});let b=ph({dataDir:t.dataDir,sessionId:i,providerId:o??s??v,provider:_,onMemoryChanged:f});_.sync&&_.sync(`session-start`).catch(()=>{});let x=async e=>{await h(t.dataDir,i,e,vh({sessionOptions:$(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,memoryProvider:_,memoryProviderSource:g.providerSource,memoryFallbackToBuiltin:g.fallbackToBuiltin,recallState:{recallProvided:!1},compactionRecallState:{recallProvided:!1},appendTranscriptEntry:x,persistInitialUserEntry:async e=>d?!1:(await x({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{b()}}}function gh(e,t){return{id:`builtin-memory`,name:`Builtin Memory Provider (degraded)`,status:()=>({backend:`builtin`,provider:`builtin-memory`,workspaceDir:e,dbPath:K.join(e,`.index.sqlite`),dirty:!0,fts:{enabled:!1,available:!1,error:t},vector:{enabled:!1,available:!1,loadError:t},custom:{searchMode:`unavailable`,fallbackActive:!0,fallbackReason:t}}),search:async()=>[],getLines:async()=>[],listFiles:async()=>[],append:async()=>{},updateFile:async()=>{},deleteFile:async()=>{},sync:async()=>{},noteSessionUpdate:()=>{}}}function _h(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function vh(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 yh(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}const bh=q.Object({image:q.String({description:`Image path or URL`}),prompt:q.Optional(q.String({description:`Prompt for image analysis`})),model:q.Optional(q.String({description:`Optional model override`})),maxBytesMb:q.Optional(q.Number({description:`Optional size cap in MB`}))});function xh(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:bh,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}}}}[`Use only the returned evidenceRef values from goal_record_evidence.`,`Natural-language descriptions, file paths, and strings such as 'goal/state.json ...' are not evidence refs unless they are registered in goal/artifacts/registry.jsonl.`,`If command output should prove an acceptance criterion, run it with goal_record_evidence(kind='exec'); regular exec output is not registered goal evidence.`].join(` `);function Sh(e,t){let n=mh({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??Rn(),a=t?.autoSkillsLoadEnabled??!1,o=t?.sessionId,s=t?.channel!==`CRON`&&o?async n=>{await A(e,o,{...n,source:(t.depth??0)>0?`subagent`:`agent`,sessionId:t.runtimeSessionId??t.sessionId},{storeName:t.inheritedRunParams?.sessionStoreName})}:void 0,c=[Ju({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),pf({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),Qu({registry:i,scopeKey:n}),ad(n,t?.contextManager),sd(n,t?.contextManager,s),ld(n,t?.contextManager,s),dd(n),vd(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),wm({reportTaskUpdated:t?.reportTaskUpdated}),...t?.sessionId?[vm(e,t.sessionId,t.inheritedRunParams?.sessionStoreName)]:[],Of(e,r),Xf(e,r),Af(e,r),Pf(e,r),Hf(e,r),Wf(e,r),Kf(e,r),Jf(e,r),Ap(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),jp({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed}),sm({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,sessionId:t?.sessionId,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv})];return a&&c.push(Hm(e),Um(e),Wm(e),Gm(e)),t&&c.push(ah(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),oh(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),uh(t.registry,t.parentSessionId)),c}function Ch(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(`
127
127
  `),`</auto_skill_categories>`,``].join(`
128
- `)}const Ch={goal:`Submit a terminal update for the current thread goal: complete or blocked`,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`,guarded_exec:`Request user approval before running a side-effectful command; use when a loaded skill requires HITL before executing a script`,process:`Manage background exec sessions`,update_task:`Update the current task plan for non-trivial multi-step work; initialize before work and advance before starting the next listed step`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,skill_action_run:`Run an action declared in a loaded skill's actions.yml; validates inputs and triggers HITL when required`,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`},wh=`read_file.write_file.edit_file.list_dir.apply_patch.exec.guarded_exec.process.update_task.skill_list.skill_load.skill_action_run.goal.auto_skill_categories.auto_skill_list.auto_skill_search.auto_skill_view.memory_search.memory_get.memory_write.memory_log.memory_list.memory_forget.memory_update.session_search.subagent_spawn.subagents`.split(`.`);function Th(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:[...wh.filter(e=>t.has(e)),...n.filter(e=>!wh.includes(e)).sort()],displayName:t}}function Eh(e){let{ordered:t,displayName:n}=Th(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)??Ch[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
128
+ `)}const wh={goal:`Submit a terminal update for the current thread goal: complete or blocked`,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`,guarded_exec:`Request user approval before running a side-effectful command; use when a loaded skill requires HITL before executing a script`,process:`Manage background exec sessions`,update_task:`Update the current task plan for non-trivial multi-step work; initialize before work and advance before starting the next listed step`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,skill_action_run:`Run an action declared in a loaded skill's actions.yml; validates inputs and triggers HITL when required`,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`},Th=`read_file.write_file.edit_file.list_dir.apply_patch.exec.guarded_exec.process.update_task.skill_list.skill_load.skill_action_run.goal.auto_skill_categories.auto_skill_list.auto_skill_search.auto_skill_view.memory_search.memory_get.memory_write.memory_log.memory_list.memory_forget.memory_update.session_search.subagent_spawn.subagents`.split(`.`);function Eh(e){let t=new Map;for(let n of e){let e=n.trim();if(!e)continue;let r=e.toLowerCase();t.has(r)||t.set(r,e)}let n=Array.from(t.keys());return{ordered:[...Th.filter(e=>t.has(e)),...n.filter(e=>!Th.includes(e)).sort()],displayName:t}}function Dh(e){let{ordered:t,displayName:n}=Eh(e.toolNames),r=new Map;for(let[t,n]of Object.entries(e.toolSummaries??{})){let e=t.trim().toLowerCase();!e||!n?.trim()||r.set(e,n.trim())}return[`## Tooling`,`Tool availability (filtered by runtime policy):`,`Tool names are case-sensitive. Call tools exactly as listed.`,t.map(e=>{let t=n.get(e)??e,i=r.get(e)??wh[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
129
129
  `),``].join(`
130
- `)}function Dh(e,t){let n=t.toLowerCase();return e.some(e=>e.trim().toLowerCase()===n)}function Oh(e){return Dh(e,`update_task`)?[`## Task Progress`,"When `update_task` is available, use it as the user-visible progress surface for non-trivial multi-step work.","- For multi-step requests, publish an initial plan before the first substantive read, command, or edit, with the first task `in_progress` and later tasks `pending`.","- Keep at most one task `in_progress`, move the next task to `in_progress` when continuing, and publish a final completed snapshot before the final answer when the plan is done.",`- Do not update for tiny internal actions inside one planned step.`,``,`Numbered/Listed Step Protocol:`,`- For explicit numbered or bulleted steps from the user, treat each listed item as a user-visible task.`,"- After completing task N, and before any tool call that starts task N+1, call `update_task` with task N `completed` and task N+1 `in_progress`.","- Never start work for task N+1 while task N is still `in_progress`.",`- Do not mark multiple newly completed listed tasks in one update unless they were completed by the same single tool result.`,`- If you skipped an earlier update, publish the current honest state and continue with per-step updates instead of retroactively pretending progress was tracked.`,``].join(`
131
- `):``}function kh(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Current goal state is injected through `<goal_context>` when a goal is active.",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,'- Use `goal({ status: "complete", summary, completedTasks })` only when the objective is genuinely achieved and every required task plus required acceptance criterion has evidence summaries and sources.','- Use `goal({ status: "blocked", reason, neededInput })` when user input or external state is required before continuing.',`- Do NOT submit a complete status merely because the budget is nearly exhausted or work is paused.`,`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, the `goal` tool reports an error.",``].join(`
132
- `)}function Ah(){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(`
133
- `)}function jh(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
134
- `)}function Mh(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(`
135
- `)}function Nh(){return[`## Artifact Declaration`,"Before your final answer, always run an internal artifact audit for the current turn. If the turn produced, modified, returned, exported, downloaded, or made available any user-relevant persistent artifact, declare it at the very end of the assistant message using exactly one `<aimax_artifacts>` block.",`A user-relevant artifact is a deliverable the user or backend may want to open, inspect, download, or display, including files and user-openable URLs.`,`Maintain a private artifact list while working: after every successful tool result, add produced or modified file/URL candidates; before the final answer, serialize the distinct list into the block.`,`Normal answer text does not count as artifact reporting: mentioning a file path or URL in prose is not enough. Every reportable artifact must appear in the block.`,``,`Mandatory artifact sources to audit:`,"- `write_file`: every file written after success.","- `edit_file`: every successfully edited file when the tool says `File edited` or reports occurrences greater than 0. If you changed file contents, declare the edited file even if the final answer only says it was modified.","- `apply_patch`: every added, updated, or moved resulting file; include all files touched by a multi-file patch.","- `exec` / bash / `process`: files generated, exported, downloaded, converted, overwritten, or modified by commands and scripts. Use command arguments, stdout/stderr, path parameters, and follow-up confirmations. If a bash command creates a user deliverable, declare it even when no file-writing tool was used or the result is `(no output)`.",`- Skills, plugin tools, and UI tools: files or URLs produced or returned by tool execution. If a skill returns a user-openable URL as the deliverable, declare that URL even if the visible final answer is only the URL.`,"- `subagent_spawn` / `batch_subagent_spawn`: artifacts returned from child agents; include all child artifacts in the parent block.",`- Assistant-only output: durable URLs or newly created file paths mentioned without a tool call when they are user deliverables.`,``,`Bash/exec detection checklist:`,"- Treat command arguments as evidence; successful `(no output)` does not cancel reporting when the command names a write/edit target.","- Declare files named by redirection or output patterns such as `> file`, `>> file`, `cat > file`, heredoc writers, `tee`, `cp`, `mv`, `curl -o`, `wget -O`, `--output`, `saved to`, `generated file`, `file created`, `file written`, or `文件已生成:<path>`.","- Declare files mutated by commands such as `sed -i`, `perl -pi`, append redirections, `tee -a`, scripts that open/write files, or temp-file replacement patterns like `command > file.tmp && mv file.tmp file`.",`- For heredocs that write a script template, declare the outer script file. Do not declare paths inside the heredoc body until that generated script runs or a later result confirms creation.`,"- Ignore metadata-only lines such as `Generated at:`, file size, byte counts, timestamps, row counts, and column counts; they are not artifact paths.",``,`Do not declare deleted files, failed or rolled-back outputs, files that were only read/listed/searched, temporary/cache files unless explicitly presented as user deliverables, or internal AIMax files such as transcript.jsonl, artifacts.json, session metadata, logs, memory files, context snapshots, and tool-result spill files.`,``,`The block format is a JSON array. Each item must include:`,'- `kind`: `"file"` or `"url"`.','- `file`: file path, required when kind is `"file"`; prefer absolute paths, but use a workspace-relative path if that is what the tool reported.','- `url`: URL value, required when kind is `"url"`.',"- `timestamp`: ISO 8601 timestamp.","- `label`: short human-readable description in the user's language.",``,`Example:`,`<aimax_artifacts>`,`[{"kind":"file","file":"/data/user/workspace/report.md","timestamp":"2026-06-15T10:30:00.000Z","label":"分析报告"},{"kind":"url","url":"https://artifact.example.test/report","timestamp":"2026-06-15T10:31:00.000Z","label":"在线报告"}]`,`</aimax_artifacts>`,``,`Common cases:`,'- After a successful `edit_file` on `src/app.ts`: `[{"kind":"file","file":"src/app.ts","timestamp":"2026-06-15T10:30:00.000Z","label":"已编辑的应用源码"}]`.','- After a bash command writes `dist/report.html`: `[{"kind":"file","file":"dist/report.html","timestamp":"2026-06-15T10:30:00.000Z","label":"生成的 HTML 报告"}]`.','- After a skill returns `https://artifact.example.test/share/abc`: `[{"kind":"url","url":"https://artifact.example.test/share/abc","timestamp":"2026-06-15T10:30:00.000Z","label":"技能生成的在线结果"}]`.',``,`High-risk scenarios:`,"- After `cat > hello.py << 'EOF' ... EOF`, declare `hello.py` even if the command returns `(no output)`.","- After `sed -i '' 's/old/new/' test123.md`, declare `test123.md` even if a later read merely verifies the contents.","- After one turn edits `hello.md` and a subagent returns `test.md`, include both items in the same block. Reporting only one artifact violates the protocol.",`- If a child result text or child task explicitly names a user deliverable path/URL that was created or modified, include it in the parent block even when the child did not emit its own block.`,'- If a skill or command returns a single user-openable URL such as `https://artifact.example.test/result`, declare it as `kind: "url"`; do not return only the visible URL.',``,`Bad outputs that violate the protocol:`,"- Saying `已编辑 test123.md` after `edit_file` or `sed -i` without an `<aimax_artifacts>` block.","- Saying `已创建 hello.py` after `cat > hello.py` without an `<aimax_artifacts>` block.",`- Reporting only one artifact after multiple successful tool calls changed multiple user files.`,``,`Rules:`,`- If no artifacts were produced this turn, do not include the block.`,`- The block must be the last thing in the assistant message.`,"- There must be no text after `</aimax_artifacts>`.",`- The block is for the runtime parser, not for the user.`,`- Do not duplicate the same file or URL inside the block.`,``].join(`
136
- `)}function Ph(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
130
+ `)}function Oh(e,t){let n=t.toLowerCase();return e.some(e=>e.trim().toLowerCase()===n)}function kh(e){return Oh(e,`update_task`)?[`## Task Progress`,"When `update_task` is available, use it as the user-visible progress surface for non-trivial multi-step work.","- For multi-step requests, publish an initial plan before the first substantive read, command, or edit, with the first task `in_progress` and later tasks `pending`.","- Keep at most one task `in_progress`, move the next task to `in_progress` when continuing, and publish a final completed snapshot before the final answer when the plan is done.",`- Do not update for tiny internal actions inside one planned step.`,``,`Numbered/Listed Step Protocol:`,`- For explicit numbered or bulleted steps from the user, treat each listed item as a user-visible task.`,"- After completing task N, and before any tool call that starts task N+1, call `update_task` with task N `completed` and task N+1 `in_progress`.","- Never start work for task N+1 while task N is still `in_progress`.",`- Do not mark multiple newly completed listed tasks in one update unless they were completed by the same single tool result.`,`- If you skipped an earlier update, publish the current honest state and continue with per-step updates instead of retroactively pretending progress was tracked.`,``].join(`
131
+ `):``}function Ah(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Current goal state is injected through `<goal_context>` when a goal is active.",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,'- Use `goal({ status: "complete", summary, completedTasks })` only when the objective is genuinely achieved and every required task plus required acceptance criterion has evidence summaries and sources.','- Use `goal({ status: "blocked", reason, neededInput })` when user input or external state is required before continuing.',`- Do NOT submit a complete status merely because the budget is nearly exhausted or work is paused.`,`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, the `goal` tool reports an error.",``].join(`
132
+ `)}function jh(){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(`
133
+ `)}function Mh(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
134
+ `)}function Nh(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(`
135
+ `)}function Ph(){return[`## Artifact Declaration`,"Before your final answer, always run an internal artifact audit for the current turn. If the turn produced, modified, returned, exported, downloaded, or made available any user-relevant persistent artifact, declare it at the very end of the assistant message using exactly one `<aimax_artifacts>` block.",`A user-relevant artifact is a deliverable the user or backend may want to open, inspect, download, or display, including files and user-openable URLs.`,`Maintain a private artifact list while working: after every successful tool result, add produced or modified file/URL candidates; before the final answer, serialize the distinct list into the block.`,`Normal answer text does not count as artifact reporting: mentioning a file path or URL in prose is not enough. Every reportable artifact must appear in the block.`,``,`Mandatory artifact sources to audit:`,"- `write_file`: every file written after success.","- `edit_file`: every successfully edited file when the tool says `File edited` or reports occurrences greater than 0. If you changed file contents, declare the edited file even if the final answer only says it was modified.","- `apply_patch`: every added, updated, or moved resulting file; include all files touched by a multi-file patch.","- `exec` / bash / `process`: files generated, exported, downloaded, converted, overwritten, or modified by commands and scripts. Use command arguments, stdout/stderr, path parameters, and follow-up confirmations. If a bash command creates a user deliverable, declare it even when no file-writing tool was used or the result is `(no output)`.",`- Skills, plugin tools, and UI tools: files or URLs produced or returned by tool execution. If a skill returns a user-openable URL as the deliverable, declare that URL even if the visible final answer is only the URL.`,"- `subagent_spawn` / `batch_subagent_spawn`: artifacts returned from child agents; include all child artifacts in the parent block.",`- Assistant-only output: durable URLs or newly created file paths mentioned without a tool call when they are user deliverables.`,``,`Bash/exec detection checklist:`,"- Treat command arguments as evidence; successful `(no output)` does not cancel reporting when the command names a write/edit target.","- Declare files named by redirection or output patterns such as `> file`, `>> file`, `cat > file`, heredoc writers, `tee`, `cp`, `mv`, `curl -o`, `wget -O`, `--output`, `saved to`, `generated file`, `file created`, `file written`, or `文件已生成:<path>`.","- Declare files mutated by commands such as `sed -i`, `perl -pi`, append redirections, `tee -a`, scripts that open/write files, or temp-file replacement patterns like `command > file.tmp && mv file.tmp file`.",`- For heredocs that write a script template, declare the outer script file. Do not declare paths inside the heredoc body until that generated script runs or a later result confirms creation.`,"- Ignore metadata-only lines such as `Generated at:`, file size, byte counts, timestamps, row counts, and column counts; they are not artifact paths.",``,`Do not declare deleted files, failed or rolled-back outputs, files that were only read/listed/searched, temporary/cache files unless explicitly presented as user deliverables, or internal AIMax files such as transcript.jsonl, artifacts.json, session metadata, logs, memory files, context snapshots, and tool-result spill files.`,``,`The block format is a JSON array. Each item must include:`,'- `kind`: `"file"` or `"url"`.','- `file`: file path, required when kind is `"file"`; prefer absolute paths, but use a workspace-relative path if that is what the tool reported.','- `url`: URL value, required when kind is `"url"`.',"- `timestamp`: ISO 8601 timestamp.","- `label`: short human-readable description in the user's language.",``,`Example:`,`<aimax_artifacts>`,`[{"kind":"file","file":"/data/user/workspace/report.md","timestamp":"2026-06-15T10:30:00.000Z","label":"分析报告"},{"kind":"url","url":"https://artifact.example.test/report","timestamp":"2026-06-15T10:31:00.000Z","label":"在线报告"}]`,`</aimax_artifacts>`,``,`Common cases:`,'- After a successful `edit_file` on `src/app.ts`: `[{"kind":"file","file":"src/app.ts","timestamp":"2026-06-15T10:30:00.000Z","label":"已编辑的应用源码"}]`.','- After a bash command writes `dist/report.html`: `[{"kind":"file","file":"dist/report.html","timestamp":"2026-06-15T10:30:00.000Z","label":"生成的 HTML 报告"}]`.','- After a skill returns `https://artifact.example.test/share/abc`: `[{"kind":"url","url":"https://artifact.example.test/share/abc","timestamp":"2026-06-15T10:30:00.000Z","label":"技能生成的在线结果"}]`.',``,`High-risk scenarios:`,"- After `cat > hello.py << 'EOF' ... EOF`, declare `hello.py` even if the command returns `(no output)`.","- After `sed -i '' 's/old/new/' test123.md`, declare `test123.md` even if a later read merely verifies the contents.","- After one turn edits `hello.md` and a subagent returns `test.md`, include both items in the same block. Reporting only one artifact violates the protocol.",`- If a child result text or child task explicitly names a user deliverable path/URL that was created or modified, include it in the parent block even when the child did not emit its own block.`,'- If a skill or command returns a single user-openable URL such as `https://artifact.example.test/result`, declare it as `kind: "url"`; do not return only the visible URL.',``,`Bad outputs that violate the protocol:`,"- Saying `已编辑 test123.md` after `edit_file` or `sed -i` without an `<aimax_artifacts>` block.","- Saying `已创建 hello.py` after `cat > hello.py` without an `<aimax_artifacts>` block.",`- Reporting only one artifact after multiple successful tool calls changed multiple user files.`,``,`Rules:`,`- If no artifacts were produced this turn, do not include the block.`,`- The block must be the last thing in the assistant message.`,"- There must be no text after `</aimax_artifacts>`.",`- The block is for the runtime parser, not for the user.`,`- Do not duplicate the same file or URL inside the block.`,``].join(`
136
+ `)}function Fh(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
137
137
  `)).join(`
138
138
  `)}\n</available_skills>`,``].join(`
139
- `)}function Fh(e=[]){let t=Sh(e).trim();return t?`${t}\n`:``}function Ih(){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(`
140
- `)}function Lh(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: write durable long-term memory to MEMORY.md (facts, preferences, rules, decisions).`,`- memory_log: append short-lived daily/session notes to memory/YYYY-MM-DD.md or session logs.`,`- Choose exactly one write surface per fact by default: long-term -> memory_write; daily/session log -> memory_log.`,`- Do not write the same fact to both memory_write and memory_log unless the user explicitly requests dual-write.`,`- Before memory_update or memory_forget, first run memory_list or memory_search to get the exact id/path.`,`- If the user explicitly names a listed memory tool, prefer calling that exact tool.`,`- Pattern: write/log for new memory; list/search -> update/forget for existing memory.`,``].join(`
141
- `)}function Rh(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(`
142
- `)}function zh(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.`,`Use the workspace temp directories for temporary or intermediate files:`,`- ${r}/temp/daily/ for short-lived files that can be cleaned daily.`,`- ${r}/temp/weekly/ for files that should remain available for about a week.`,`- ${r}/temp/monthly/ for files that should remain available for about a month.`,`Do not pre-initialize these directories; create them only when you actually need to write temporary files.`,``].join(`
143
- `)}function Bh(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(`
144
- `)}function Vh(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Hh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
145
- `)}function Hh(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 Uh(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(`
146
- `)}function Wh(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(`
147
- `)}function Gh(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(`
148
- `)}function Kh(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(`
149
- `)}function qh(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(`
150
- `)}function Jh(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(`
151
- `):``}function Yh(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:[...wh],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,qh(e.subagentDepth??0),Eh({toolNames:i,toolSummaries:e.toolSummaries}),Oh(i),Nh(),Mh(n),kh(),Ah(),ja(e.availableAgents??[]),Ph(a),Fh(e.autoSkillCategories),Ih(),Lh(),Rh(e.memoryCitationsMode??`off`),zh({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Bh(e.sandboxInfo),Vh({currentDate:e.currentDate,timezone:e.timezone}),jh(),Uh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Gh({isMinimal:n}),Wh(e.runtimeInfo),Kh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Jh(e.priorConversationSummary)].filter(Boolean).join(`
152
- `)}function Xh(e,t,n){return e.map(e=>{let r=e,i=Le(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await me({pluginId:i,hookContext:t,eventDispatcher:n.eventDispatcher},e):await e();try{return await l(async()=>await r.execute(e,c,o,s))}catch(e){if(So(e))return Eo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function Zh(e){let t=!1,n,r;for(let i of e)i&&(i.params&&(r={...r,...i.params}),i.block&&(t=!0,n=i.blockReason));return{blocked:t,blockReason:n,mergedParams:r}}function Qh(e,t){let n=e.content,r=ng(e.details),i=e.isError;for(let e of t)if(e){if(e.content!==void 0&&(n=$h(n,e.content)),e.details!==void 0){let t=ng(e.details);r={...r,...t}}e.isError===!0&&(i=!0)}return{content:n,details:r,isError:i}}function $h(e,t){return t===void 0?e:e===void 0?t:Array.isArray(e)&&Array.isArray(t)?eg(e,t)?t:[...e,...t]:t}function eg(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!tg(e[n],t[n]))return!1;return!0}function tg(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ng(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function rg(e){let{agent:t,hookRegistry:n,hookContext:r,pluginRuntime:i,overrideStore:a}=e,o=new Map;t.beforeToolCall=async({toolCall:e,args:t},s)=>{let c=Date.now();o.set(e.id,c);let l;try{l=await n.dispatch(`before_tool_call`,{toolCallId:e.id,toolName:e.name,params:t},r,i)}catch(t){if(o.delete(e.id),So(t))return Eo(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=Zh(l);if(u){let a=d??`blocked by plugin`;return o.delete(e.id),await n.dispatch(`after_tool_call`,{toolCallId:e.id,toolName:e.name,params:f??t,error:a,durationMs:Math.max(0,Date.now()-c)},r,i),{block:!0,reason:a}}f&&f!==t&&a.set(e.id,f)},t.afterToolCall=async({toolCall:e,args:t,result:a,isError:s},c)=>{let l=o.get(e.id)??Date.now();o.delete(e.id);let u=a.details&&typeof a.details==`object`?a.details:{},d;try{d=await n.dispatch(`tool_result`,{type:`tool_result`,toolCallId:e.id,toolName:e.name,input:t,content:a.content,details:u,isError:s},r,i)}catch(e){if(So(e))return Eo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}let f=Qh({content:a.content,details:u,isError:s},d),p=Math.max(0,Date.now()-l),m=f.isError?ig(f.content)??`tool call failed`:void 0;return await n.dispatch(`after_tool_call`,{toolCallId:e.id,toolName:e.name,params:t,result:{content:f.content,details:f.details,isError:f.isError},...m?{error:m}:{},durationMs:p},r,i),{content:f.content,details:f.details,isError:f.isError}}}function ig(e){if(typeof e==`string`&&e.trim())return e;if(!Array.isArray(e))return;let t=e.map(e=>e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`?e.text.trim():``).filter(Boolean);return t.length>0?t.join(`
153
- `):void 0}var ag=class e{overrides=new Map;static MAX_SIZE=1e3;set(t,n){this.overrides.size>=e.MAX_SIZE&&this.overrides.clear(),this.overrides.set(t,n)}consume(e,t){let n=this.overrides.get(e);return n?(this.overrides.delete(e),n):t}clear(){this.overrides.clear()}get size(){return this.overrides.size}};const og={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function sg(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function cg(e){let t=sg(e?.warningThreshold,og.warningThreshold),n=sg(e?.criticalThreshold,og.criticalThreshold),r=sg(e?.globalCircuitBreakerThreshold,og.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??og.enabled,historySize:sg(e?.historySize,og.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??og.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??og.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??og.detectors.pingPong}}}function lg(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function ug(e,t){return`${e}:${pg(t)}`}function dg(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(dg).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${dg(t[e])}`).join(`,`)}}`}function fg(e){try{return dg(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 pg(e){let t=fg(e);return Ft(`sha256`).update(t).digest(`hex`)}function mg(e,t){if(e===`command_status`)return!0;if(e!==`process`||!lg(t))return!1;let n=t.action;return n===`poll`||n===`log`}function hg(e){return!lg(e)||!Array.isArray(e.content)?``:e.content.filter(e=>lg(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
154
- `).trim()}function gg(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:dg(e)}function _g(e,t,n,r){if(r!==void 0)return`error:${pg(gg(r))}`;if(!lg(n))return n===void 0?void 0:pg(n);let i=lg(n.details)?n.details:{},a=hg(n);if(mg(e,t)&&e===`process`&&lg(t)){let e=t.action;if(e===`poll`)return pg({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return pg({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 pg({details:i,text:a})}function vg(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 yg(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 bg(e,t){return[e,t].toSorted().join(`|`)}function xg(e,t,n,r){let i=cg(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=ug(t,n),s=vg(a,t,o),c=s.count,l=mg(t,n),u=yg(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:${bg(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 Sg(e,t,n,r,i){let a=cg(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:ug(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Cg(e,t){let n=cg(t.config),r=_g(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=ug(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 wg(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 Tg(e){return e&&e.trim()||`tool`}function Eg(e,t,n){if(!e.execute)return e;let r=Tg(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=xg(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);wg(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Sg(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Cg(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Cg(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Dg(e,t,n){return e.map(e=>Eg(e,t,n))}const Og=new Map;function kg(e){let t=Og.get(e);return t||(t={},Og.set(e,t)),t}function Ag(e){Og.delete(e)}function jg(e){let t=e.streamFn??$t;return(e,n,r)=>(e.api===`anthropic-messages`&&Mg(e),t(e,n,{...r,...zg(e,r)}))}function Mg(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Fg(Rg(e),n)?(globalThis.fetch=t,Ng(await t(e,Ig(e,r)))):t(e,r))}function Ng(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
155
-
156
- `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Pg))),a.enqueue(r.encode(e+`
157
-
158
- `))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Pg=`event: message_start
139
+ `)}function Ih(e=[]){let t=Ch(e).trim();return t?`${t}\n`:``}function Lh(){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(`
140
+ `)}function Rh(){return[`## Memory Write`,`Use memory tools, not write_file/edit_file, for memory operations.`,`- memory_write: write durable long-term memory to MEMORY.md (facts, preferences, rules, decisions).`,`- memory_log: append short-lived daily/session notes to memory/YYYY-MM-DD.md or session logs.`,`- Choose exactly one write surface per fact by default: long-term -> memory_write; daily/session log -> memory_log.`,`- Do not write the same fact to both memory_write and memory_log unless the user explicitly requests dual-write.`,`- Before memory_update or memory_forget, first run memory_list or memory_search to get the exact id/path.`,`- If the user explicitly names a listed memory tool, prefer calling that exact tool.`,`- Pattern: write/log for new memory; list/search -> update/forget for existing memory.`,``].join(`
141
+ `)}function zh(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(`
142
+ `)}function Bh(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.`,`Use the workspace temp directories for temporary or intermediate files:`,`- ${r}/temp/daily/ for short-lived files that can be cleaned daily.`,`- ${r}/temp/weekly/ for files that should remain available for about a week.`,`- ${r}/temp/monthly/ for files that should remain available for about a month.`,`Do not pre-initialize these directories; create them only when you actually need to write temporary files.`,``].join(`
143
+ `)}function Vh(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(`
144
+ `)}function Hh(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Uh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
145
+ `)}function Uh(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 Wh(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(`
146
+ `)}function Gh(e){if(!e)return``;let t=[e.os?`os=${e.os}`:``,e.node?`node=${e.node}`:``,e.model?`model=${e.model}`:``].filter(Boolean);return t.length===0?``:[`## Runtime`,`Runtime: ${t.join(` | `)}`,``].join(`
147
+ `)}function Kh(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(`
148
+ `)}function qh(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(`
149
+ `)}function Jh(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(`
150
+ `)}function Yh(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(`
151
+ `):``}function Xh(e){let t=e.promptMode??`full`,n=t===`minimal`,r=e.activeAgentSystemPrompt?.trim()||e.presetSystemPrompt||`You are a personal assistant running inside AiMax.`;if(t===`none`)return r;let i=e.toolNames&&e.toolNames.length>0?e.toolNames:[...Th],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Jh(e.subagentDepth??0),Dh({toolNames:i,toolSummaries:e.toolSummaries}),kh(i),Ph(),Nh(n),Ah(),jh(),ja(e.availableAgents??[]),Fh(a),Ih(e.autoSkillCategories),Lh(),Rh(),zh(e.memoryCitationsMode??`off`),Bh({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Vh(e.sandboxInfo),Hh({currentDate:e.currentDate,timezone:e.timezone}),Mh(),Wh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Kh({isMinimal:n}),Gh(e.runtimeInfo),qh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Yh(e.priorConversationSummary)].filter(Boolean).join(`
152
+ `)}function Zh(e,t,n){return e.map(e=>{let r=e,i=Le(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await me({pluginId:i,hookContext:t,eventDispatcher:n.eventDispatcher},e):await e();try{return await l(async()=>await r.execute(e,c,o,s))}catch(e){if(So(e))return Eo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function Qh(e){let t=!1,n,r;for(let i of e)i&&(i.params&&(r={...r,...i.params}),i.block&&(t=!0,n=i.blockReason));return{blocked:t,blockReason:n,mergedParams:r}}function $h(e,t){let n=e.content,r=rg(e.details),i=e.isError;for(let e of t)if(e){if(e.content!==void 0&&(n=eg(n,e.content)),e.details!==void 0){let t=rg(e.details);r={...r,...t}}e.isError===!0&&(i=!0)}return{content:n,details:r,isError:i}}function eg(e,t){return t===void 0?e:e===void 0?t:Array.isArray(e)&&Array.isArray(t)?tg(e,t)?t:[...e,...t]:t}function tg(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!ng(e[n],t[n]))return!1;return!0}function ng(e,t){return JSON.stringify(e)===JSON.stringify(t)}function rg(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function ig(e){let{agent:t,hookRegistry:n,hookContext:r,pluginRuntime:i,overrideStore:a}=e,o=new Map;t.beforeToolCall=async({toolCall:e,args:t},s)=>{let c=Date.now();o.set(e.id,c);let l;try{l=await n.dispatch(`before_tool_call`,{toolCallId:e.id,toolName:e.name,params:t},r,i)}catch(t){if(o.delete(e.id),So(t))return Eo(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=Qh(l);if(u){let a=d??`blocked by plugin`;return o.delete(e.id),await n.dispatch(`after_tool_call`,{toolCallId:e.id,toolName:e.name,params:f??t,error:a,durationMs:Math.max(0,Date.now()-c)},r,i),{block:!0,reason:a}}f&&f!==t&&a.set(e.id,f)},t.afterToolCall=async({toolCall:e,args:t,result:a,isError:s},c)=>{let l=o.get(e.id)??Date.now();o.delete(e.id);let u=a.details&&typeof a.details==`object`?a.details:{},d;try{d=await n.dispatch(`tool_result`,{type:`tool_result`,toolCallId:e.id,toolName:e.name,input:t,content:a.content,details:u,isError:s},r,i)}catch(e){if(So(e))return Eo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}let f=$h({content:a.content,details:u,isError:s},d),p=Math.max(0,Date.now()-l),m=f.isError?ag(f.content)??`tool call failed`:void 0;return await n.dispatch(`after_tool_call`,{toolCallId:e.id,toolName:e.name,params:t,result:{content:f.content,details:f.details,isError:f.isError},...m?{error:m}:{},durationMs:p},r,i),{content:f.content,details:f.details,isError:f.isError}}}function ag(e){if(typeof e==`string`&&e.trim())return e;if(!Array.isArray(e))return;let t=e.map(e=>e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`?e.text.trim():``).filter(Boolean);return t.length>0?t.join(`
153
+ `):void 0}var og=class e{overrides=new Map;static MAX_SIZE=1e3;set(t,n){this.overrides.size>=e.MAX_SIZE&&this.overrides.clear(),this.overrides.set(t,n)}consume(e,t){let n=this.overrides.get(e);return n?(this.overrides.delete(e),n):t}clear(){this.overrides.clear()}get size(){return this.overrides.size}};const sg={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function cg(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function lg(e){let t=cg(e?.warningThreshold,sg.warningThreshold),n=cg(e?.criticalThreshold,sg.criticalThreshold),r=cg(e?.globalCircuitBreakerThreshold,sg.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??sg.enabled,historySize:cg(e?.historySize,sg.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??sg.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??sg.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??sg.detectors.pingPong}}}function ug(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function dg(e,t){return`${e}:${mg(t)}`}function fg(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(fg).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${fg(t[e])}`).join(`,`)}}`}function pg(e){try{return fg(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 mg(e){let t=pg(e);return Ft(`sha256`).update(t).digest(`hex`)}function hg(e,t){if(e===`command_status`)return!0;if(e!==`process`||!ug(t))return!1;let n=t.action;return n===`poll`||n===`log`}function gg(e){return!ug(e)||!Array.isArray(e.content)?``:e.content.filter(e=>ug(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
154
+ `).trim()}function _g(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:fg(e)}function vg(e,t,n,r){if(r!==void 0)return`error:${mg(_g(r))}`;if(!ug(n))return n===void 0?void 0:mg(n);let i=ug(n.details)?n.details:{},a=gg(n);if(hg(e,t)&&e===`process`&&ug(t)){let e=t.action;if(e===`poll`)return mg({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return mg({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 mg({details:i,text:a})}function yg(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 bg(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 xg(e,t){return[e,t].toSorted().join(`|`)}function Sg(e,t,n,r){let i=lg(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=dg(t,n),s=yg(a,t,o),c=s.count,l=hg(t,n),u=bg(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:${xg(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 Cg(e,t,n,r,i){let a=lg(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:dg(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function wg(e,t){let n=lg(t.config),r=vg(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=dg(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 Tg(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 Eg(e){return e&&e.trim()||`tool`}function Dg(e,t,n){if(!e.execute)return e;let r=Eg(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Sg(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Tg(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Cg(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return wg(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw wg(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Og(e,t,n){return e.map(e=>Dg(e,t,n))}const kg=new Map;function Ag(e){let t=kg.get(e);return t||(t={},kg.set(e,t)),t}function jg(e){kg.delete(e)}function Mg(e){let t=e.streamFn??$t;return(e,n,r)=>(e.api===`anthropic-messages`&&Ng(e),t(e,n,{...r,...Bg(e,r)}))}function Ng(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Ig(zg(e),n)?(globalThis.fetch=t,Pg(await t(e,Lg(e,r)))):t(e,r))}function Pg(e){if(!e.body)return e;let t=!1,n=``,r=new TextEncoder,i=new TextDecoder,a=new TransformStream({transform(e,a){n+=i.decode(e,{stream:!0});let o;for(;(o=n.indexOf(`
155
+
156
+ `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Fg))),a.enqueue(r.encode(e+`
157
+
158
+ `))}},flush(e){n.length>0&&e.enqueue(r.encode(n))}}),o=e.body.pipeThrough(a);return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}const Fg=`event: message_start
159
159
  data: {"type":"message_start","message":{"id":"","type":"message","role":"assistant","content":[],"model":"","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}}
160
160
 
161
- `;function Fg(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Ig(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Lg(e)&&n.delete(e);return{...t,headers:n}}function Lg(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function Rg(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function zg(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}function Bg(e,t=.3){return e.length===0?!0:e.every(e=>e.score<t)}function Vg(e){return Math.ceil(e.length/4)}function Hg(e,t){if(Vg(e)<=t)return e;let n=t*4;return`${e.slice(0,Math.max(0,n-3)).trimEnd()}...`}async function Ug(e){let t=e.query.trim();if(!t)return{};let n=await e.provider.search(t),r=e.coreConfig?.knowledgeController?.scoreThreshold,i=Bg(n,r);if(n.length===0)return{isWeakLocalRecall:!0};let a=e.coreConfig?.recall?.tokenBudget??1500,o=[`<!-- AIMax persistent memory recall -->`,``,`## Recalled Memory`,``];for(let e of n){let t=e.path.includes(`#`)?e.path:`${e.path} (L${e.startLine})`;o.push(`- **${t}**: ${e.snippet.trim()}`)}return{block:Hg(o.join(`
162
- `),a),blockId:`core-recall-${Date.now()}`,isWeakLocalRecall:i}}function Wg(e,t){return`${t.trim()}\n\n${e}`}function Gg(e,t){let n=`${t.trim()}\n\n`;return e.startsWith(n)?e.slice(n.length):e}const Kg=`<!-- AIMax compaction memory recall -->`;async function qg(e){if(e.coreConfig?.compactionRecall?.enabled!==!0)return;let t=e.query.trim();if(t)try{let n=await Ug({provider:e.provider,query:t,coreConfig:{...e.coreConfig,recall:{...e.coreConfig.recall,enabled:!0,tokenBudget:e.coreConfig.compactionRecall?.tokenBudget??e.coreConfig.recall?.tokenBudget}}});return n.block?`${Kg}\n\n${n.block.replace(`${Kg}\n\n`,``).trim()}`:void 0}catch{return}}async function Jg(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:f,pluginTools:p,pluginSkillDirs:m,skillsLoadPaths:h,presetSystemPrompt:g},dependencies:{registry:_,spawnFn:v,createModel:y,abortSignal:b}}=e,x=t.autoSkills?.load?.enabled===!0,S=t.agentPolicy?.activeAgent,C=t.channel===`CRON`,w=C?[]:await F(t.dataDir,n,$(t)),T={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},E=Ks(t.llm),D=await Fu({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=C?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Iu({entries:w,modelInfo:T,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:b,hooks:i,hookCtx:a,contextManager:D,dataDir:t.dataDir,sessionId:n,entriesToMessagesOptions:E});await Zg({runParams:t,sessionId:n,historyResult:O,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a,effectivePromptText:f});let k=t.subagentContext?.depth??0,A=r(t.dataDir,n,$(t)),j=Rn(),M=Aa([...xh(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:A,registry:_,processRegistry:j,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:h,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,onLog:t.onLog,messageId:t.messageId,agentPolicy:t.agentPolicy,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:x,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:m,skillsLoadPaths:h,reportSkillUsed:async e=>{await s.dispatchProgress(n,e)},reportTaskUpdated:async e=>{await s.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:s,spawnFn:v,baseEnv:t.env}),...p],S),N=M.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),P={};for(let e of M){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||P[t]||(P[t]=n)}let ee=t.messaging?.enabled??t.channel!==`CRON`,I=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],L=Yh({dataDir:t.dataDir,projectDir:t.projectDir,skills:ka(u,S),autoSkillCategories:x?d:[],contextFiles:c,toolNames:N,toolSummaries:P,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:ee,channels:I},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Rt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});L=await Xg({systemPrompt:L,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let R,te=t.memory?.core,z=te?.recall?.enabled===!0,B=!!t.subagentContext,V=o.memoryProviderSource===`plugin`&&te?.recall?.forceWithPluginProvider!==!0;if(z&&!B&&!V&&!o.recallState.recallProvided)try{let e=await Ug({provider:o.memoryProvider,query:f,coreConfig:te}),t=te?.knowledgeController;if(t?.enabled===!0&&t?.searchMode===`fallback`&&(e.isWeakLocalRecall===!0||!e.block))try{let e=await(await import(`./kc-Omw-bmtO.js`)).runKcFallbackSearch({config:t,query:f});e.block&&(R&&(L=Gg(L,R)),R=e.block,L=Wg(L,R),o.recallState={recallProvided:!0,source:`core`,blockId:e.blockId})}catch(e){await s.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_kc_recall_failed`,message:`KC fallback recall failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}!o.recallState.recallProvided&&e.block&&(R=e.block,L=Wg(L,R),o.recallState={recallProvided:!0,source:`core`,blockId:e.blockId})}catch(e){await s.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_recall_failed`,message:`core recall step failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}let ne={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},re=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:L,systemPromptOptions:ne,recallState:o.recallState},a,{eventDispatcher:s}),ie=await i.dispatchWithMetadata(`before_prompt_build`,{prompt:f,recallState:o.recallState},a,{eventDispatcher:s});ie.length>0&&console.warn(`[AgentRuntime] before_prompt_build hook(s) fired; this hook is deprecated in favor of before_agent_start. Migrate plugins to before_agent_start.`);let H=[];for(let e of re){if(!e)continue;let t=e;if(t.recall?.block?.trim()){R&&=(L=Gg(L,R),void 0),L=Wg(L,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}t.systemPrompt&&(L=t.systemPrompt),t.prependContext&&(L=`${t.prependContext}\n\n${L}`),t.message&&H.push(t.message)}for(let e of ie){if(!e.result)continue;let t=e.result;if(t.recall?.block?.trim()){R&&=(L=Gg(L,R),void 0),L=Wg(L,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}if(t.systemPrompt&&(L=t.systemPrompt),t.prependContext){if((e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&o.recallState.recallProvided)continue;L=`${t.prependContext}\n\n${L}`,(e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&(o.recallState={recallProvided:!0,source:`plugin`})}}await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:L},a,{eventDispatcher:s});let ae=Dg(Xh(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},kg),U=S?.model??t.llm.model,oe=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of oe)e&&e.modelOverride&&(U=e.modelOverride);let se=y({...t.llm,model:U},n,t.messageId,t.channel);try{await Rs(t.dataDir,n,{systemPrompt:L,tools:ae},$(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let W=new Ht({initialState:{systemPrompt:L,model:se,tools:ae,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:jg({})}),ce={eventDispatcher:s};a.signal=b;let le=new ag;return a.toolParamOverrides=le,rg({agent:W,hookRegistry:i,hookContext:a,pluginRuntime:ce,overrideStore:le}),O.messages.length>0&&(W.state.messages=O.messages),H.length>0&&(W.state.messages=[...H,...W.state.messages]),{agent:W,resolvedModelId:U,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function Yg(e){let t=await e.hookRegistry.dispatch(`context`,{messages:e.agent.state.messages},e.hookContext,e.pluginRuntime),n=e.agent.state.messages;for(let e of t)!e||!(`messages`in e)||!e.messages||(n=e.messages);n!==e.agent.state.messages&&(e.agent.state.messages=n)}async function Xg(e){if((await m(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 ${N(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 Zg(e){let{runParams:t,sessionId:n,historyResult:r,runContext:i,eventDispatcher:a,hookRegistry:o,hookContext:s,effectivePromptText:c}=e;for(let e of r.compactionEvents??[])e.type===`compaction`&&await a.dispatchDiagnostic(n,{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(r.compactionEntry){let e=r.stats.originalCount-r.stats.keptCount,l=Qg(await o.dispatch(`before_compaction`,{messageCount:r.stats.originalCount,compactingCount:e},s,{eventDispatcher:a})),u=l.injectRecall,d=!!l.pluginRecallProvided;if(t.memory?.core?.compactionRecall?.enabled===!0&&!d&&!i.compactionRecallState.recallProvided)try{let e=await qg({provider:i.memoryProvider,query:c,coreConfig:t.memory.core});e&&(u=e,i.compactionRecallState={recallProvided:!0,source:`core`})}catch(e){await a.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_compaction_recall_failed`,message:`core compaction recall failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}let f=u?{...r.compactionEntry,content:`${u.trim()}\n\n${r.compactionEntry.content}`}:r.compactionEntry;if(l.skipPersist){await a.dispatchDiagnostic(n,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!l.injectRecall}});return}await i.appendTranscriptEntry(f),(r.compactionEvents?.length??0)===0&&await a.dispatchDiagnostic(n,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await o.dispatch(`after_compaction`,{messageCount:r.stats.originalCount,compactedCount:e},s,{eventDispatcher:a})}}function Qg(e){let t=!1,n=[],r=!1;for(let i of e)if(i){if(i.skipPersist&&(t=!0),i.recall?.block?.trim()){n.push(i.recall.block.trim()),r=!0;continue}typeof i.injectRecall==`string`&&i.injectRecall.trim().length>0&&(n.push(i.injectRecall.trim()),r=!0)}return{skipPersist:t,injectRecall:n.length>0?n.join(`
161
+ `;function Ig(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Lg(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Rg(e)&&n.delete(e);return{...t,headers:n}}function Rg(e){let t=e.toLowerCase();return t===`anthropic-beta`||t===`anthropic-dangerous-direct-browser-access`||t===`x-stainless-helper-method`||t.startsWith(`x-stainless-`)||t===`user-agent`}function zg(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function Bg(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}function Vg(e,t=.3){return e.length===0?!0:e.every(e=>e.score<t)}function Hg(e){return Math.ceil(e.length/4)}function Ug(e,t){if(Hg(e)<=t)return e;let n=t*4;return`${e.slice(0,Math.max(0,n-3)).trimEnd()}...`}async function Wg(e){let t=e.query.trim();if(!t)return{};let n=await e.provider.search(t),r=e.coreConfig?.knowledgeController?.scoreThreshold,i=Vg(n,r);if(n.length===0)return{isWeakLocalRecall:!0};let a=e.coreConfig?.recall?.tokenBudget??1500,o=[`<!-- AIMax persistent memory recall -->`,``,`## Recalled Memory`,``];for(let e of n){let t=e.path.includes(`#`)?e.path:`${e.path} (L${e.startLine})`;o.push(`- **${t}**: ${e.snippet.trim()}`)}return{block:Ug(o.join(`
162
+ `),a),blockId:`core-recall-${Date.now()}`,isWeakLocalRecall:i}}function Gg(e,t){return`${t.trim()}\n\n${e}`}function Kg(e,t){let n=`${t.trim()}\n\n`;return e.startsWith(n)?e.slice(n.length):e}const qg=`<!-- AIMax compaction memory recall -->`;async function Jg(e){if(e.coreConfig?.compactionRecall?.enabled!==!0)return;let t=e.query.trim();if(t)try{let n=await Wg({provider:e.provider,query:t,coreConfig:{...e.coreConfig,recall:{...e.coreConfig.recall,enabled:!0,tokenBudget:e.coreConfig.compactionRecall?.tokenBudget??e.coreConfig.recall?.tokenBudget}}});return n.block?`${qg}\n\n${n.block.replace(`${qg}\n\n`,``).trim()}`:void 0}catch{return}}async function Yg(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:f,pluginTools:p,pluginSkillDirs:m,skillsLoadPaths:h,presetSystemPrompt:g},dependencies:{registry:_,spawnFn:v,createModel:y,abortSignal:b}}=e,x=t.autoSkills?.load?.enabled===!0,S=t.agentPolicy?.activeAgent,C=t.channel===`CRON`,w=C?[]:await F(t.dataDir,n,$(t)),T={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},E=qs(t.llm),D=await Iu({dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName,sessionPathScope:t.sessionPathScope}),O=C?{messages:[],priorSummary:void 0,compactionEntry:void 0,stats:{originalCount:0,keptCount:0,estimatedTokens:0,compacted:!1},compactionEvents:[]}:await Lu({entries:w,modelInfo:T,contextWindowTokens:t.llm.contextWindow??2e5,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model,flashModel:t.llm.flashModel},historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,channel:t.channel,isSubagent:!!t.subagentContext,compactionEnabled:!0,pendingUserMessage:f,signal:b,hooks:i,hookCtx:a,contextManager:D,dataDir:t.dataDir,sessionId:n,entriesToMessagesOptions:E});await Qg({runParams:t,sessionId:n,historyResult:O,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a,effectivePromptText:f});let k=t.subagentContext?.depth??0,A=r(t.dataDir,n,$(t)),j=Rn(),M=Aa([...Sh(t.dataDir,{sessionId:t.subagentContext?.parentSessionId??n,runtimeSessionId:n,currentSessionDir:A,registry:_,processRegistry:j,parentSessionId:n,depth:k,channel:t.channel,llm:t.llm,inheritedRunParams:{sessionStoreName:t.sessionStoreName,plugins:t.plugins,skillsLoadPaths:h,memory:t.memory,messaging:t.messaging,historyLimit:t.historyLimit,topicSegmentation:t.topicSegmentation,autoSkills:t.autoSkills,onProgress:t.onProgress,onLog:t.onLog,messageId:t.messageId,agentPolicy:t.agentPolicy,projectDir:t.projectDir,env:t.env},loopDetection:t.loopDetection,autoSkillsLoadEnabled:x,memoryOptions:{providerId:o.memoryProviderId,pluginId:o.memoryPluginId,sessionId:n,sessionStoreName:t.sessionStoreName,llm:{apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,model:t.llm.model},onMemoryChanged:async()=>{}},pluginSkillDirs:m,skillsLoadPaths:h,reportSkillUsed:async e=>{await s.dispatchProgress(n,e)},reportTaskUpdated:async e=>{await s.dispatchProgress(n,e)},contextManager:D,hitlResume:t.hitlResume,eventDispatcher:s,spawnFn:v,baseEnv:t.env}),...p],S),N=M.map(e=>typeof e.name==`string`?e.name.trim():``).filter(Boolean),P={};for(let e of M){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||P[t]||(P[t]=n)}let ee=t.messaging?.enabled??t.channel!==`CRON`,I=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],L=Xh({dataDir:t.dataDir,projectDir:t.projectDir,skills:ka(u,S),autoSkillCategories:x?d:[],contextFiles:c,toolNames:N,toolSummaries:P,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:ee,channels:I},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:Rt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});L=await Zg({systemPrompt:L,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let R,te=t.memory?.core,z=te?.recall?.enabled===!0,B=!!t.subagentContext,V=o.memoryProviderSource===`plugin`&&te?.recall?.forceWithPluginProvider!==!0;if(z&&!B&&!V&&!o.recallState.recallProvided)try{let e=await Wg({provider:o.memoryProvider,query:f,coreConfig:te}),t=te?.knowledgeController;if(t?.enabled===!0&&t?.searchMode===`fallback`&&(e.isWeakLocalRecall===!0||!e.block))try{let e=await(await import(`./kc-Omw-bmtO.js`)).runKcFallbackSearch({config:t,query:f});e.block&&(R&&(L=Kg(L,R)),R=e.block,L=Gg(L,R),o.recallState={recallProvided:!0,source:`core`,blockId:e.blockId})}catch(e){await s.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_kc_recall_failed`,message:`KC fallback recall failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}!o.recallState.recallProvided&&e.block&&(R=e.block,L=Gg(L,R),o.recallState={recallProvided:!0,source:`core`,blockId:e.blockId})}catch(e){await s.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_recall_failed`,message:`core recall step failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}let ne={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},re=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:L,systemPromptOptions:ne,recallState:o.recallState},a,{eventDispatcher:s}),ie=await i.dispatchWithMetadata(`before_prompt_build`,{prompt:f,recallState:o.recallState},a,{eventDispatcher:s});ie.length>0&&console.warn(`[AgentRuntime] before_prompt_build hook(s) fired; this hook is deprecated in favor of before_agent_start. Migrate plugins to before_agent_start.`);let H=[];for(let e of re){if(!e)continue;let t=e;if(t.recall?.block?.trim()){R&&=(L=Kg(L,R),void 0),L=Gg(L,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}t.systemPrompt&&(L=t.systemPrompt),t.prependContext&&(L=`${t.prependContext}\n\n${L}`),t.message&&H.push(t.message)}for(let e of ie){if(!e.result)continue;let t=e.result;if(t.recall?.block?.trim()){R&&=(L=Kg(L,R),void 0),L=Gg(L,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}if(t.systemPrompt&&(L=t.systemPrompt),t.prependContext){if((e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&o.recallState.recallProvided)continue;L=`${t.prependContext}\n\n${L}`,(e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&(o.recallState={recallProvided:!0,source:`plugin`})}}await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:L},a,{eventDispatcher:s});let ae=Og(Zh(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},Ag),U=S?.model??t.llm.model,oe=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of oe)e&&e.modelOverride&&(U=e.modelOverride);let se=y({...t.llm,model:U},n,t.messageId,t.channel);try{await Ls(t.dataDir,n,ae,$(t))}catch(e){console.warn(`[AgentRuntime] failed to persist tools snapshot for session ${n}:`,e.message)}let W=new Ht({initialState:{systemPrompt:L,model:se,tools:ae,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:Mg({})}),ce={eventDispatcher:s};a.signal=b;let le=new og;return a.toolParamOverrides=le,ig({agent:W,hookRegistry:i,hookContext:a,pluginRuntime:ce,overrideStore:le}),O.messages.length>0&&(W.state.messages=O.messages),H.length>0&&(W.state.messages=[...H,...W.state.messages]),{agent:W,resolvedModelId:U,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function Xg(e){let t=await e.hookRegistry.dispatch(`context`,{messages:e.agent.state.messages},e.hookContext,e.pluginRuntime),n=e.agent.state.messages;for(let e of t)!e||!(`messages`in e)||!e.messages||(n=e.messages);n!==e.agent.state.messages&&(e.agent.state.messages=n)}async function Zg(e){if((await m(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 ${N(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 Qg(e){let{runParams:t,sessionId:n,historyResult:r,runContext:i,eventDispatcher:a,hookRegistry:o,hookContext:s,effectivePromptText:c}=e;for(let e of r.compactionEvents??[])e.type===`compaction`&&await a.dispatchDiagnostic(n,{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(r.compactionEntry){let e=r.stats.originalCount-r.stats.keptCount,l=$g(await o.dispatch(`before_compaction`,{messageCount:r.stats.originalCount,compactingCount:e},s,{eventDispatcher:a})),u=l.injectRecall,d=!!l.pluginRecallProvided;if(t.memory?.core?.compactionRecall?.enabled===!0&&!d&&!i.compactionRecallState.recallProvided)try{let e=await Jg({provider:i.memoryProvider,query:c,coreConfig:t.memory.core});e&&(u=e,i.compactionRecallState={recallProvided:!0,source:`core`})}catch(e){await a.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_compaction_recall_failed`,message:`core compaction recall failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}let f=u?{...r.compactionEntry,content:`${u.trim()}\n\n${r.compactionEntry.content}`}:r.compactionEntry;if(l.skipPersist){await a.dispatchDiagnostic(n,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!l.injectRecall}});return}await i.appendTranscriptEntry(f),(r.compactionEvents?.length??0)===0&&await a.dispatchDiagnostic(n,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await o.dispatch(`after_compaction`,{messageCount:r.stats.originalCount,compactedCount:e},s,{eventDispatcher:a})}}function $g(e){let t=!1,n=[],r=!1;for(let i of e)if(i){if(i.skipPersist&&(t=!0),i.recall?.block?.trim()){n.push(i.recall.block.trim()),r=!0;continue}typeof i.injectRecall==`string`&&i.injectRecall.trim().length>0&&(n.push(i.injectRecall.trim()),r=!0)}return{skipPersist:t,injectRecall:n.length>0?n.join(`
163
163
 
164
- `):void 0,pluginRecallProvided:r}}function $g(e){return e.some(e=>n_(e.message)!==null||e.toolResults.length>0)}function e_(e,t){return{role:`assistant`,content:e,stopReason:(t&&typeof t==`object`?t.code:void 0)===`aborted`||e===`aborted`?`aborted`:`error`,errorMessage:e,timestamp:new Date().toISOString()}}function t_(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 n_(e){let t=c_(e),n=r_(e),r=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&r.length===0)return null;let i={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.trim().length>0&&(i.thinking=n),r.length>0&&(i.toolCalls=r),i}function r_(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function i_(e){return e.map(e=>r_(e.message)).filter(e=>e.trim().length>0).join(`
164
+ `):void 0,pluginRecallProvided:r}}function e_(e){return e.some(e=>r_(e.message)!==null||e.toolResults.length>0)}function t_(e,t){return{role:`assistant`,content:e,stopReason:(t&&typeof t==`object`?t.code:void 0)===`aborted`||e===`aborted`?`aborted`:`error`,errorMessage:e,timestamp:new Date().toISOString()}}function n_(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 r_(e){let t=l_(e),n=i_(e),r=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&r.length===0)return null;let i={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.trim().length>0&&(i.thinking=n),r.length>0&&(i.toolCalls=r),i}function i_(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function a_(e){return e.map(e=>i_(e.message)).filter(e=>e.trim().length>0).join(`
165
165
 
166
- `)}function a_(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function o_(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 s_(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:l_(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function c_(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function l_(e){let t=e.indexOf(`
166
+ `)}function o_(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function s_(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 c_(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:u_(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function l_(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function u_(e){let t=e.indexOf(`
167
167
  Preview:
168
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function u_(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,artifactAccumulator:p}=e,m=``,h=``,g=``,_=0,v=0,y,b,x=0,S=0,C=[],w=new Map,T=new Map,E=new Set,D=wo(),O=ze(),k=new Ja,A={workspaceDir:l.workspaceDir},j=new Set,M=Promise.resolve(),N,P=0,ee=0,F={eventDispatcher:s},I=e=>{j.add(e),e.catch(e=>{N??=e}).finally(()=>{j.delete(e)})},L=async()=>{for(;j.size>0;)await Promise.allSettled([...j]);if(N)throw N},R=t.subscribe(e=>{let t=M.then(()=>te(e));M=t.catch(()=>{}),I(t)});async function te(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`agent_start`){c.dispatch(`agent_start`,{turnIndex:P},l,F).catch(()=>{});return}if(e.type===`turn_start`){ee=P,P+=1,c.dispatch(`turn_start`,{turnIndex:ee,timestamp:Date.now()},l,F).catch(()=>{});return}if(e.type===`message_update`){let t=e.assistantMessageEvent;if(S===0&&(t.type===`text_delta`||t.type===`done`)&&(S=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=T_(`partial`in t?t.partial:void 0)??T_(`message`in t?t.message:void 0)??T_(`message`in e?e.message:void 0),a=E_(t.delta,r,h);r?(h=r,g=r):a&&(g+=a);let o=k.push(a);o&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:o})}if(t.type===`done`){let e=t.message;if(n()){m=``,h=``,g=``,k.reset(),e.usage&&(_=e.usage.input,v=e.usage.output);return}m=c_(e);let r=E_(``,m,g||h);h=m,g=m;let a=`${k.push(r)}${k.finish()}`;a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a}),e.usage&&(_=e.usage.input,v=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(_=t.usage.input,v=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=c_(e);!m&&n&&(m=n);let r=k.finish();r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:t.usage?{input:_,output:v,total:_+v}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(b=g_(t));let r=Va(c_(t),A);n||(r.artifacts.length>0&&p?.addOwn(r.artifacts),await oe(r.warnings));let a=(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:s_(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),o=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),s=new Set(a.map(e=>e.toolCallId));for(let e of T.values())!s.has(e.toolCallId)&&o.has(e.toolCallId)&&a.push(e);for(let e of a)T.delete(e.toolCallId);if(C.push({message:t,toolResults:a}),f&&!n){let e=!!D.signal,n=!!O.signal;if(!(e&&D.signal.transparentPause)){let i=a_(n_(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText);let o=n?[]:a.map(o_);(i||o.length>0)&&await f(i,o)}if(e||n)return}await c.dispatch(`turn_end`,{turnIndex:ee,message:t,toolResults:a},l,F);return}if(e.type===`tool_execution_start`){let t=k.finish();t&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:t}),k.reset(),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_planned`,message:`tool call planned`,details:{toolCallId:e.toolCallId,toolName:e.toolName,args:e.args}}),g=``,w.set(e.toolCallId,e.args),D.signal?.transparentPause!==!0&&!E.has(e.toolCallId)&&(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args}));return}if(e.type===`tool_execution_end`){let n=w_(e.result),r=C_(e.result);p?.addChild(d_(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:s_(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(Xa({toolName:e.toolName,input:c,result:e.result,isError:!!e.isError,workspaceDir:l.workspaceDir})),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_completed`,message:`tool call completed`,details:{toolCallId:e.toolCallId,toolName:e.toolName,input:c,output:n,isError:e.isError,...o?{toolResultRef:o}:{}}}),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let z=ps(d),B=z.enabled?z.maxAttempts:1;try{f_({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=B;e++){let d=C.length;b=void 0,y=void 0,P=0,ee=0;try{await Yg({agent:t,hookRegistry:c,hookContext:l,pluginRuntime:F});let f=await c.dispatch(`before_provider_request`,{model:a,messages:t.state.messages,tools:t.state.tools},l,F);for(let e of f)if(e){if(e.abort)return await L(),{text:m,inputTokens:_,outputTokens:v,error:y,turnRecords:C};e.messages&&(t.state.messages=e.messages),e.tools&&(t.state.tools=e.tools)}if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);W.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),x=Date.now(),await To(D,async()=>{await he(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await L();let p=D.signal;if(p)throw p;let h=O.signal;if(h)throw h;let g=C.some(e=>e.message.content.some(e=>e.type===`toolCall`||e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0));!b&&C.length>0&&!g&&m.trim().length===0&&(W.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,turnRecordCount:C.length}),b={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let S=t.state,w=typeof S.error==`string`?S.error:typeof S.errorMessage==`string`?S.errorMessage:void 0,T=b??w;if(T){let t=b?`sdk`:`agent_state`;if(y=D_(T),W.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:C.length-d,...zo(T,`providerError`)}),await ne(T,y,e,d))continue;await re(y,T),await s.dispatchProgress(i,{type:`error`,message:y})}y||W.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await L(),So(t)||Re(t))throw t;if(y=D_(t),W.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y}),await ne(t,y,e,d))continue;await re(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{R()}function V(){m=``,h=``,g=``}async function ne(e,n,r,a){let o=h_({error:e,attempt:r,maxAttempts:B,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g});if(!o.retry)return W.warn(`llm turn retry skipped`,{sessionId:i,attempt:r,maxAttempts:B,error:n,reason:o.reason,retryableError:o.retryableError,attemptRecordCount:o.attemptRecordCount,recordsWithToolResults:o.recordsWithToolResults,recordsWithAssistantText:o.recordsWithAssistantText,hasFinalAssistantText:o.hasFinalAssistantText,hasStreamedAssistantSnapshot:o.hasStreamedAssistantSnapshot,hasStreamedTextSinceBoundary:o.hasStreamedTextSinceBoundary}),!1;let c=ms(r,z);return W.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:B,delayMs:c,error:n}),await y_({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:B,message:n,delayMs:c}),C.length=a,V(),b_(t),await hs(c,u),!0}async function re(e,t){f&&await f(e_(e,t),[])}let ie=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:ie,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let H=O.signal?``:C.length>0?Va(c_(C[C.length-1].message),A).cleanedText:``,ae=Va(m,A).cleanedText,U=H||ae||t_(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;if(f&&!$g(C)&&!y&&m.trim().length>0){let e=Va(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await oe(e.warnings);let t=i_(C);await f({role:`assistant`,content:e.cleanedText,...t?{thinking:t}:{},timestamp:new Date().toISOString()},[])}return{text:U,inputTokens:_,outputTokens:v,error:y,turnRecords:C};async function oe(e){for(let t of e)await s.dispatchDiagnostic(i,{level:`warn`,scope:`runner`,phase:`artifact_parse`,message:t})}}function d_(e,t){if(e!==`subagent_spawn`&&e!==`batch_subagent_spawn`)return[];let n=t&&typeof t==`object`?t.details:void 0;if(!n||typeof n!=`object`)return[];if(e===`subagent_spawn`){let e=n.artifacts;return Array.isArray(e)?e:[]}let r=n.results;return Array.isArray(r)?r.flatMap(e=>{let t=e&&typeof e==`object`?e.artifacts:void 0;return Array.isArray(t)?t:[]}):[]}function f_(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model,r=e.agent.state?.thinkingLevel;if(!n||typeof n.id!=`string`)return;let i=typeof t?.systemPrompt==`string`?t.systemPrompt:``,a=Array.isArray(t?.messages)?[...t.messages]:[],o=e.continueFromHistory?a:p_(a,e.message),s=m_(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=Yo(n,{systemPrompt:i,messages:o,tools:s.length>0?s.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},t),c=typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`;e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`runner`,phase:`model_request_preview`,message:`model request preview`,details:{model:n.id,provider:c,systemPrompt:i,tools:s,requestJson:a}})}catch{}}function p_(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function m_(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e).flatMap(e=>{let t=typeof e.name==`string`?e.name:``;return t?[{name:t,description:typeof e.description==`string`?e.description:void 0,parameters:e.parameters}]:[]}):[]}function h_(e){let t=e.turnRecords.slice(e.attemptTurnRecordStart),n=t.filter(e=>e.toolResults.length>0).length,r=t.filter(e=>c_(e.message).trim().length>0).length,i=e.finalAssistantText.trim().length>0,a=e.streamedAssistantSnapshot.trim().length>0,o=e.streamedTextSinceBoundary.trim().length>0,s=gs(e.error),c={retryableError:s,attemptRecordCount:t.length,recordsWithToolResults:n,recordsWithAssistantText:r,hasFinalAssistantText:i,hasStreamedAssistantSnapshot:a,hasStreamedTextSinceBoundary:o};return e.attempt>=e.maxAttempts?{retry:!1,reason:`max_attempts_exhausted`,...c}:s?i||a||o?{retry:!1,reason:`assistant_text_already_streamed`,...c}:n>0?{retry:!1,reason:`tool_results_already_produced`,...c}:r>0?{retry:!1,reason:`assistant_text_already_recorded`,...c}:{retry:!0,...c}:{retry:!1,reason:`error_not_retryable`,...c}}function g_(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:__(t.errorCode),statusCode:v_(t.statusCode),providerCode:__(t.providerCode),providerType:__(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function __(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function v_(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function y_(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 b_(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&x_(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function x_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`?t.stopReason===`error`||t.stopReason===`aborted`?!0:S_(t.content):!1}function S_(e){return e==null?!0:typeof e==`string`?e.trim().length===0:Array.isArray(e)?e.every(e=>{if(!e||typeof e!=`object`)return!0;let t=e;return t.type===`toolCall`?!1:t.type===`text`?typeof t.text!=`string`||t.text.trim().length===0:!0}):!1}function C_(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return w_(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):w_(e)}function w_(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function T_(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 E_(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function D_(e){let t=O_(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 O_(e){if(e instanceof ge)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:__(t.code),statusCode:v_(t.statusCode),statusText:__(t.statusText),providerMessage:__(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 k_(e){let t=F_(e.toolResultPreviewChars),n=I_(e.systemPrompt,e.agentDefinition),r=R_(e.model,e.agentDefinition),i=Aa(e.tools??[],e.agentDefinition),a=L_(e.message,e.agentDefinition),o=await u_({agent:new Ht({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:A_({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new de,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:M_(o.turnRecords),toolResults:N_(o.turnRecords,t)}}function A_(e){let t=e.phasePrefix??`silent_agent`;return new Ra({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await j_(e.diagnosticDispatcher,t,n)}})}async function j_(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 M_(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 N_(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:P_(e.content,t)})))}function P_(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function F_(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 I_(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
168
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function d_(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,artifactAccumulator:p}=e,m=``,h=``,g=``,_=0,v=0,y,b,x=0,S=0,C=[],w=new Map,T=new Map,E=new Set,D=wo(),O=ze(),k=new Ja,A={workspaceDir:l.workspaceDir},j=new Set,M=Promise.resolve(),N,P=0,ee=0,F={eventDispatcher:s},I=e=>{j.add(e),e.catch(e=>{N??=e}).finally(()=>{j.delete(e)})},L=async()=>{for(;j.size>0;)await Promise.allSettled([...j]);if(N)throw N},R=t.subscribe(e=>{let t=M.then(()=>te(e));M=t.catch(()=>{}),I(t)});async function te(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`agent_start`){c.dispatch(`agent_start`,{turnIndex:P},l,F).catch(()=>{});return}if(e.type===`turn_start`){ee=P,P+=1,c.dispatch(`turn_start`,{turnIndex:ee,timestamp:Date.now()},l,F).catch(()=>{});return}if(e.type===`message_update`){let t=e.assistantMessageEvent;if(S===0&&(t.type===`text_delta`||t.type===`done`)&&(S=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=E_(`partial`in t?t.partial:void 0)??E_(`message`in t?t.message:void 0)??E_(`message`in e?e.message:void 0),a=D_(t.delta,r,h);r?(h=r,g=r):a&&(g+=a);let o=k.push(a);o&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:o})}if(t.type===`done`){let e=t.message;if(n()){m=``,h=``,g=``,k.reset(),e.usage&&(_=e.usage.input,v=e.usage.output);return}m=l_(e);let r=D_(``,m,g||h);h=m,g=m;let a=`${k.push(r)}${k.finish()}`;a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a}),e.usage&&(_=e.usage.input,v=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(_=t.usage.input,v=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=l_(e);!m&&n&&(m=n);let r=k.finish();r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:t.usage?{input:_,output:v,total:_+v}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(b=__(t));let r=Va(l_(t),A);n||(r.artifacts.length>0&&p?.addOwn(r.artifacts),await oe(r.warnings));let a=(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:c_(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),o=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),s=new Set(a.map(e=>e.toolCallId));for(let e of T.values())!s.has(e.toolCallId)&&o.has(e.toolCallId)&&a.push(e);for(let e of a)T.delete(e.toolCallId);if(C.push({message:t,toolResults:a}),f&&!n){let e=!!D.signal,n=!!O.signal;if(!(e&&D.signal.transparentPause)){let i=o_(r_(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText);let o=n?[]:a.map(s_);(i||o.length>0)&&await f(i,o)}if(e||n)return}await c.dispatch(`turn_end`,{turnIndex:ee,message:t,toolResults:a},l,F);return}if(e.type===`tool_execution_start`){let t=k.finish();t&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:t}),k.reset(),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_planned`,message:`tool call planned`,details:{toolCallId:e.toolCallId,toolName:e.toolName,args:e.args}}),g=``,w.set(e.toolCallId,e.args),D.signal?.transparentPause!==!0&&!E.has(e.toolCallId)&&(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:e.args}));return}if(e.type===`tool_execution_end`){let n=T_(e.result),r=w_(e.result);p?.addChild(f_(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:c_(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(Xa({toolName:e.toolName,input:c,result:e.result,isError:!!e.isError,workspaceDir:l.workspaceDir})),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_completed`,message:`tool call completed`,details:{toolCallId:e.toolCallId,toolName:e.toolName,input:c,output:n,isError:e.isError,...o?{toolResultRef:o}:{}}}),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let z=ps(d),B=z.enabled?z.maxAttempts:1;try{p_({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=B;e++){let d=C.length;b=void 0,y=void 0,P=0,ee=0;try{await Xg({agent:t,hookRegistry:c,hookContext:l,pluginRuntime:F});let f=await c.dispatch(`before_provider_request`,{model:a,messages:t.state.messages,tools:t.state.tools},l,F);for(let e of f)if(e){if(e.abort)return await L(),{text:m,inputTokens:_,outputTokens:v,error:y,turnRecords:C};e.messages&&(t.state.messages=e.messages),e.tools&&(t.state.tools=e.tools)}if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);W.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),x=Date.now(),await To(D,async()=>{await he(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await L();let p=D.signal;if(p)throw p;let h=O.signal;if(h)throw h;let g=C.some(e=>e.message.content.some(e=>e.type===`toolCall`||e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0));!b&&C.length>0&&!g&&m.trim().length===0&&(W.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,turnRecordCount:C.length}),b={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let S=t.state,w=typeof S.error==`string`?S.error:typeof S.errorMessage==`string`?S.errorMessage:void 0,T=b??w;if(T){let t=b?`sdk`:`agent_state`;if(y=O_(T),W.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:C.length-d,...zo(T,`providerError`)}),await ne(T,y,e,d))continue;await re(y,T),await s.dispatchProgress(i,{type:`error`,message:y})}y||W.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await L(),So(t)||Re(t))throw t;if(y=O_(t),W.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y}),await ne(t,y,e,d))continue;await re(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{R()}function V(){m=``,h=``,g=``}async function ne(e,n,r,a){let o=g_({error:e,attempt:r,maxAttempts:B,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g});if(!o.retry)return W.warn(`llm turn retry skipped`,{sessionId:i,attempt:r,maxAttempts:B,error:n,reason:o.reason,retryableError:o.retryableError,attemptRecordCount:o.attemptRecordCount,recordsWithToolResults:o.recordsWithToolResults,recordsWithAssistantText:o.recordsWithAssistantText,hasFinalAssistantText:o.hasFinalAssistantText,hasStreamedAssistantSnapshot:o.hasStreamedAssistantSnapshot,hasStreamedTextSinceBoundary:o.hasStreamedTextSinceBoundary}),!1;let c=ms(r,z);return W.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:B,delayMs:c,error:n}),await b_({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:B,message:n,delayMs:c}),C.length=a,V(),x_(t),await hs(c,u),!0}async function re(e,t){f&&await f(t_(e,t),[])}let ie=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:ie,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let H=O.signal?``:C.length>0?Va(l_(C[C.length-1].message),A).cleanedText:``,ae=Va(m,A).cleanedText,U=H||ae||n_(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;if(f&&!e_(C)&&!y&&m.trim().length>0){let e=Va(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await oe(e.warnings);let t=a_(C);await f({role:`assistant`,content:e.cleanedText,...t?{thinking:t}:{},timestamp:new Date().toISOString()},[])}return{text:U,inputTokens:_,outputTokens:v,error:y,turnRecords:C};async function oe(e){for(let t of e)await s.dispatchDiagnostic(i,{level:`warn`,scope:`runner`,phase:`artifact_parse`,message:t})}}function f_(e,t){if(e!==`subagent_spawn`&&e!==`batch_subagent_spawn`)return[];let n=t&&typeof t==`object`?t.details:void 0;if(!n||typeof n!=`object`)return[];if(e===`subagent_spawn`){let e=n.artifacts;return Array.isArray(e)?e:[]}let r=n.results;return Array.isArray(r)?r.flatMap(e=>{let t=e&&typeof e==`object`?e.artifacts:void 0;return Array.isArray(t)?t:[]}):[]}function p_(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model,r=e.agent.state?.thinkingLevel;if(!n||typeof n.id!=`string`)return;let i=typeof t?.systemPrompt==`string`?t.systemPrompt:``,a=Array.isArray(t?.messages)?[...t.messages]:[],o=e.continueFromHistory?a:m_(a,e.message),s=h_(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=Yo(n,{systemPrompt:i,messages:o,tools:s.length>0?s.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},t),c=typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`;e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`runner`,phase:`model_request_preview`,message:`model request preview`,details:{model:n.id,provider:c,systemPrompt:i,tools:s,requestJson:a}})}catch{}}function m_(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function h_(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e).flatMap(e=>{let t=typeof e.name==`string`?e.name:``;return t?[{name:t,description:typeof e.description==`string`?e.description:void 0,parameters:e.parameters}]:[]}):[]}function g_(e){let t=e.turnRecords.slice(e.attemptTurnRecordStart),n=t.filter(e=>e.toolResults.length>0).length,r=t.filter(e=>l_(e.message).trim().length>0).length,i=e.finalAssistantText.trim().length>0,a=e.streamedAssistantSnapshot.trim().length>0,o=e.streamedTextSinceBoundary.trim().length>0,s=gs(e.error),c={retryableError:s,attemptRecordCount:t.length,recordsWithToolResults:n,recordsWithAssistantText:r,hasFinalAssistantText:i,hasStreamedAssistantSnapshot:a,hasStreamedTextSinceBoundary:o};return e.attempt>=e.maxAttempts?{retry:!1,reason:`max_attempts_exhausted`,...c}:s?i||a||o?{retry:!1,reason:`assistant_text_already_streamed`,...c}:n>0?{retry:!1,reason:`tool_results_already_produced`,...c}:r>0?{retry:!1,reason:`assistant_text_already_recorded`,...c}:{retry:!0,...c}:{retry:!1,reason:`error_not_retryable`,...c}}function __(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:v_(t.errorCode),statusCode:y_(t.statusCode),providerCode:v_(t.providerCode),providerType:v_(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function v_(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function y_(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function b_(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 x_(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&S_(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function S_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`?t.stopReason===`error`||t.stopReason===`aborted`?!0:C_(t.content):!1}function C_(e){return e==null?!0:typeof e==`string`?e.trim().length===0:Array.isArray(e)?e.every(e=>{if(!e||typeof e!=`object`)return!0;let t=e;return t.type===`toolCall`?!1:t.type===`text`?typeof t.text!=`string`||t.text.trim().length===0:!0}):!1}function w_(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return T_(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):T_(e)}function T_(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function E_(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 D_(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function O_(e){let t=k_(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 k_(e){if(e instanceof ge)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:v_(t.code),statusCode:y_(t.statusCode),statusText:v_(t.statusText),providerMessage:v_(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 A_(e){let t=I_(e.toolResultPreviewChars),n=L_(e.systemPrompt,e.agentDefinition),r=z_(e.model,e.agentDefinition),i=Aa(e.tools??[],e.agentDefinition),a=R_(e.message,e.agentDefinition),o=await d_({agent:new Ht({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:j_({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new de,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:N_(o.turnRecords),toolResults:P_(o.turnRecords,t)}}function j_(e){let t=e.phasePrefix??`silent_agent`;return new Ra({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await M_(e.diagnosticDispatcher,t,n)}})}async function M_(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 N_(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 P_(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:F_(e.content,t)})))}function F_(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function I_(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 L_(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
169
169
 
170
- `)}function L_(e,t){return!t?.initPrompt||typeof e!=`string`?e:Ma(t,e)}function R_(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const z_=q.Object({kind:q.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>q.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:q.Optional(q.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:q.Optional(q.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:q.Optional(q.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:q.Optional(q.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function B_(e){let t=ui({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??ai}),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:z_,async execute(r,i){try{return i.kind===`tool_result`?H_(await li({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?H_(await oi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?H_(await si({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?H_({...await ci({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):H_(await ci({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:V_(i),limits:t}))}catch(r){return H_({kind:i.kind,error:U_(r),limits:t,contextFiles:fi(e.dataDir,e.sessionId,n)})}}}}function V_(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 H_(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function U_(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function W_(e){let t=[Hm(e.dataDir),Um(e.dataDir),Wm(e.dataDir),B_({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(Gm(e.dataDir)),t}const G_=`auto-skill-reviewer`;async function K_(e){let t=e.createModel??ga,n=e.tools??W_({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 k_({sessionId:e.sessionId,systemPrompt:q_(e.mode),message:J_(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=Y_(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 q_(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(`
171
- `)}function J_(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(`
172
- `)}function Y_(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=X_(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 X_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const Z_=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Q_=Z_,$_={session:{tool_call_volume:5,state_changing_tools:2},currentRun:{tool_call_volume:5,tool_diversity:3,state_changing_tools:3},reviewWindow:{tool_call_volume:5,state_changing_tools:1}},ev=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function tv(e){let t=rv(e.gates),n={session:av(`session`,e.sessionTranscript,t.session),currentRun:av(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:av(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=lv(e.reviewState?.reviewCount,0),i=lv(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return dv(n,a,r,i,o,`run_error`);if(e.result?.paused)return dv(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return dv(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return dv(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 nv(e,t={}){let n=Yr(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??Z_),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(fv(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}pv(t)&&mv(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 rv(e){return{session:iv(e?e.session:$_.session),currentRun:iv(e?e.currentRun:$_.currentRun),reviewWindow:iv(e?e.reviewWindow:$_.reviewWindow)}}function iv(e){let t={};for(let n of ev){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Q_:void 0;if(typeof r==`number`){let e=cv(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=cv(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:uv(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:uv(r.toolNames,i)})}return t}function av(e,t,n){let r=nv(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=ev.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];ov(t,o,r)?i.push({code:t,description:sv(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 ov(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 sv(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 cv(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function lv(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function uv(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function dv(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 fv(e){return e.role===`assistant`}function pv(e){return e.role===`tool_result`}function mv(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:hv(e.content)?.success===!1}function hv(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function gv(e){let t=Zr(e.transcript.length,e.transcriptStartIndex),n=Qr(e.transcript.length,e.recentEntryLimit),r=Zr(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Zr(e.transcript.length,0),a=$r(e.transcript,t),o=$r(e.transcript,r),s=nv(e.transcript),c=nv(a),l=nv(o),u=Jr(e.transcript),d=Jr(a),f=Jr(o),p=a.filter(vv),m=a.filter(yv);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:_v(p[0]?.content??``,800),finalResponse:_v(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:Xr(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 _v(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function vv(e){return e.role===`user`}function yv(e){return e.role===`assistant`}function bv(e,t,n){return K.join(r(e,t,n),`auto-skill-review-state.json`)}function xv(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function Sv(e,t,n){let r=bv(e,t,n),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return xv(t);throw e}return Dv(JSON.parse(i),t)}async function Cv(e,t,n){let r=bv(e,t.sessionId,n);await G.mkdir(K.dirname(r),{recursive:!0}),await G.writeFile(r,`${JSON.stringify(Dv(t,t.sessionId),null,2)}\n`,`utf-8`)}async function wv(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await Cv(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Tv(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 Cv(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Ev(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await Cv(e.dataDir,t,{storeName:e.sessionStoreName}),t}function Dv(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:Av(n.reviewCount,0),lastAttemptedReviewAt:Ov(n.lastAttemptedReviewAt),lastCompletedReviewAt:Ov(n.lastCompletedReviewAt),lastFailedReviewAt:Ov(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:kv(n.lastReviewedTranscriptEndIndex)}}function Ov(e){return typeof e==`string`&&e.trim()?e:null}function kv(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function Av(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function jv(e){return K.join(Ai(e),`.reviews`,`run-log.jsonl`)}async function Mv(e,t){let n=jv(e);await G.mkdir(K.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await G.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const Nv=`write`,Pv=new Set([`off`,`gate`,`dry_run`,`write`]);async function Fv(e){let t=Iv(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=Rv(e);if(n){await Hv(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=zv(n,e.transcriptStartIndex),o=await Sv(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=Bv(o.lastReviewedTranscriptEndIndex,n.length),c=zv(n,s);await Uv(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=tv({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await Uv(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:l.worthReview,selectedGateScope:l.selectedGateScope,skipReason:l.skipReason}),!l.worthReview){await Wv(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await Uv(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new Xi({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=gv({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:fi(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await Uv(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await Wv(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(G_);if(!p){W.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:G_}),await Hv(e,t,`reviewer_agent_missing`,{reviewerAgentName:G_});return}i={mode:f,decision:l,packet:d},r=await wv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:o,sessionStoreName:e.runParams.sessionStoreName}),await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_started`,message:`auto-skill review agent started`,details:{mode:t.mode,selectedGateScope:l.selectedGateScope,reviewCount:l.reviewCount,maxReviewsPerSession:l.maxReviewsPerSession}});let m=e.curator??K_,h=W_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:t.mode,currentRunRange:d.currentRunRange,recentRange:d.recentRange,reviewWindowRange:d.reviewWindowRange}),g=await m({sessionId:e.sessionId,runParams:e.runParams,packet:d,mode:t.mode,tools:h,reviewerAgent:p,diagnosticDispatcher:e.eventDispatcher});if(g.error){r=await Ev({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await Gv(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await Vv(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:Kv(g.toolCalls),toolResults:$v(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await Tv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await Gv(e.runParams.dataDir,i,{status:`completed`,curatorResult:g,reviewState:r});await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_completed`,message:`auto-skill review agent completed`,details:{mode:t.mode,usage:g.usage,text:Qv(g.text,2e3),toolCalls:Kv(g.toolCalls),toolResults:$v(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewState:r,reviewRunLogPath:_}})}catch(t){let n=t instanceof Error?t.message:String(t),a;r&&(r=await Ev({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await Gv(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await Vv(e,n,a?{reviewRunLogPath:a}:void 0)}}function Iv(e){return{mode:Lv(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function Lv(e){if(e==null)return Nv;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?Pv.has(t)?t:`off`:Nv}function Rv(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 zv(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function Bv(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function Vv(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 Hv(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 Uv(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function Wv(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:Zv(n),...i.packet?{packet:i.packet}:{}}})}async function Gv(e,t,n){return Mv(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?Jv(n.curatorResult.text):void 0,conclusionText:n.curatorResult?Yv(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?Kv(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?$v(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 Kv(e){return e.map(e=>({...e,arguments:qv(e.name,e.arguments)}))}function qv(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 Jv(e){let t=Xv(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function Yv(e){return Jv(e)?void 0:Qv(e,8e3)}function Xv(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 Zv(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 Qv(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function $v(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let ey=!1;function ty(){ey||=(Qt(),Zt({api:`openai-completions`,stream:qo,streamSimple:Jo}),!0)}const ny=[`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(`
173
- `);async function ry(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o,onFallback:s,titleGeneration:c}=e,l=t.trim().replace(/\s+/g,` `);if(!l)return`New session`;if(c?.enabled===!1||!r.flashModel)return cy(l);let u=cy(l),d=r.flashModel,f=ce({apiFormat:r.apiFormat,baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:d,hooks:a,hookCtx:o}),p=[{role:`user`,content:l}];n&&p.push({role:`assistant`,content:n});let m=ay(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await f.chat({system:ny,user:JSON.stringify(p),temperature:0,maxTokens:100,signal:m.signal})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(oy(t)){if(m.didTimeout())return s?.(`timeout`),u;throw t}e<3&&await iy(500*e,m.signal)}}catch(e){if(oy(e)&&m.didTimeout())return s?.(`timeout`),u;throw e}finally{m.clear()}return s?.(`error`),u}function iy(e,t){return t?t.aborted?Promise.reject(sy()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(sy())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function ay(e,t){let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},t);return e?.aborted?n.abort():e?.addEventListener(`abort`,()=>n.abort(),{once:!0}),{signal:n.signal,clear:()=>clearTimeout(i),didTimeout:()=>r}}function oy(e){return e instanceof Error&&e.name===`AbortError`}function sy(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function cy(e,t=80){if(!e)return`New session`;try{let t=JSON.parse(e);if(Array.isArray(t))return t?.[0]?.content?.[0].text??e}catch{}let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}async function ly(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});let l={eventDispatcher:c};if(await o.dispatch(`session_start`,{sessionId:t,reason:e.resetCommand?`reset`:`startup`},s,l),e.piExtensionDir&&e.registerSkillDir){let t=await o.dispatch(`resources_discover`,{extensionDir:e.piExtensionDir},s,l);for(let n of t)if(!(!n||!(`skillPaths`in n)||!n.skillPaths))for(let t of n.skillPaths)e.registerSkillDir(t)}}async function uy(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await py(await F(r.dataDir,t,{...$(r)}),r);await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs,messages:o},a,{eventDispatcher:e.eventDispatcher})}async function dy(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await F(r.dataDir,t,{...$(r)});await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs,reason:n.error?`error`:`normal`},a,{eventDispatcher:e.eventDispatcher}),a.toolParamOverrides?.clear()}async function fy(e){await uy(e),await dy(e)}async function py(e,t){return e.map(e=>({...e}))}function my(e){let t=[];for(let n of e){if(n.role!==`assistant`)continue;let e=typeof n.content==`string`?n.content.trim():``;e&&t.push(e)}if(t.length!==0)return t.join(`
170
+ `)}function R_(e,t){return!t?.initPrompt||typeof e!=`string`?e:Ma(t,e)}function z_(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const B_=q.Object({kind:q.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>q.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:q.Optional(q.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:q.Optional(q.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:q.Optional(q.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:q.Optional(q.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function V_(e){let t=ui({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??ai}),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:B_,async execute(r,i){try{return i.kind===`tool_result`?U_(await li({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?U_(await oi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?U_(await si({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?U_({...await ci({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):U_(await ci({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:H_(i),limits:t}))}catch(r){return U_({kind:i.kind,error:W_(r),limits:t,contextFiles:fi(e.dataDir,e.sessionId,n)})}}}}function H_(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 U_(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function W_(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function G_(e){let t=[Um(e.dataDir),Wm(e.dataDir),Gm(e.dataDir),V_({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(Km(e.dataDir)),t}const K_=`auto-skill-reviewer`;async function q_(e){let t=e.createModel??ga,n=e.tools??G_({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 A_({sessionId:e.sessionId,systemPrompt:J_(e.mode),message:Y_(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=X_(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 J_(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(`
171
+ `)}function Y_(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(`
172
+ `)}function X_(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=Z_(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 Z_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const Q_=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],$_=Q_,ev={session:{tool_call_volume:5,state_changing_tools:2},currentRun:{tool_call_volume:5,tool_diversity:3,state_changing_tools:3},reviewWindow:{tool_call_volume:5,state_changing_tools:1}},tv=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function nv(e){let t=iv(e.gates),n={session:ov(`session`,e.sessionTranscript,t.session),currentRun:ov(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:ov(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=uv(e.reviewState?.reviewCount,0),i=uv(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return fv(n,a,r,i,o,`run_error`);if(e.result?.paused)return fv(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return fv(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return fv(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 rv(e,t={}){let n=Yr(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??Q_),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(pv(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}mv(t)&&hv(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 iv(e){return{session:av(e?e.session:ev.session),currentRun:av(e?e.currentRun:ev.currentRun),reviewWindow:av(e?e.reviewWindow:ev.reviewWindow)}}function av(e){let t={};for(let n of tv){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?$_:void 0;if(typeof r==`number`){let e=lv(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=lv(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:dv(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:dv(r.toolNames,i)})}return t}function ov(e,t,n){let r=rv(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=tv.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];sv(t,o,r)?i.push({code:t,description:cv(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 sv(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 cv(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 lv(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function uv(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function dv(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function fv(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 pv(e){return e.role===`assistant`}function mv(e){return e.role===`tool_result`}function hv(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:gv(e.content)?.success===!1}function gv(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function _v(e){let t=Zr(e.transcript.length,e.transcriptStartIndex),n=Qr(e.transcript.length,e.recentEntryLimit),r=Zr(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Zr(e.transcript.length,0),a=$r(e.transcript,t),o=$r(e.transcript,r),s=rv(e.transcript),c=rv(a),l=rv(o),u=Jr(e.transcript),d=Jr(a),f=Jr(o),p=a.filter(yv),m=a.filter(bv);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:vv(p[0]?.content??``,800),finalResponse:vv(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:Xr(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 vv(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function yv(e){return e.role===`user`}function bv(e){return e.role===`assistant`}function xv(e,t,n){return K.join(r(e,t,n),`auto-skill-review-state.json`)}function Sv(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function Cv(e,t,n){let r=xv(e,t,n),i;try{i=await G.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return Sv(t);throw e}return Ov(JSON.parse(i),t)}async function wv(e,t,n){let r=xv(e,t.sessionId,n);await G.mkdir(K.dirname(r),{recursive:!0}),await G.writeFile(r,`${JSON.stringify(Ov(t,t.sessionId),null,2)}\n`,`utf-8`)}async function Tv(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await wv(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Ev(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 wv(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function Dv(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await wv(e.dataDir,t,{storeName:e.sessionStoreName}),t}function Ov(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:jv(n.reviewCount,0),lastAttemptedReviewAt:kv(n.lastAttemptedReviewAt),lastCompletedReviewAt:kv(n.lastCompletedReviewAt),lastFailedReviewAt:kv(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:Av(n.lastReviewedTranscriptEndIndex)}}function kv(e){return typeof e==`string`&&e.trim()?e:null}function Av(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function jv(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function Mv(e){return K.join(Ai(e),`.reviews`,`run-log.jsonl`)}async function Nv(e,t){let n=Mv(e);await G.mkdir(K.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await G.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const Pv=`write`,Fv=new Set([`off`,`gate`,`dry_run`,`write`]);async function Iv(e){let t=Lv(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=zv(e);if(n){await Uv(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=Bv(n,e.transcriptStartIndex),o=await Cv(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=Vv(o.lastReviewedTranscriptEndIndex,n.length),c=Bv(n,s);await Wv(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=nv({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await Wv(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:l.worthReview,selectedGateScope:l.selectedGateScope,skipReason:l.skipReason}),!l.worthReview){await Gv(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await Wv(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new Xi({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=_v({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:fi(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await Wv(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await Gv(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(K_);if(!p){W.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:K_}),await Uv(e,t,`reviewer_agent_missing`,{reviewerAgentName:K_});return}i={mode:f,decision:l,packet:d},r=await Tv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:o,sessionStoreName:e.runParams.sessionStoreName}),await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_started`,message:`auto-skill review agent started`,details:{mode:t.mode,selectedGateScope:l.selectedGateScope,reviewCount:l.reviewCount,maxReviewsPerSession:l.maxReviewsPerSession}});let m=e.curator??q_,h=G_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName,mode:t.mode,currentRunRange:d.currentRunRange,recentRange:d.recentRange,reviewWindowRange:d.reviewWindowRange}),g=await m({sessionId:e.sessionId,runParams:e.runParams,packet:d,mode:t.mode,tools:h,reviewerAgent:p,diagnosticDispatcher:e.eventDispatcher});if(g.error){r=await Dv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await Kv(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await Hv(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:qv(g.toolCalls),toolResults:ey(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await Ev({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await Kv(e.runParams.dataDir,i,{status:`completed`,curatorResult:g,reviewState:r});await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_completed`,message:`auto-skill review agent completed`,details:{mode:t.mode,usage:g.usage,text:$v(g.text,2e3),toolCalls:qv(g.toolCalls),toolResults:ey(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewState:r,reviewRunLogPath:_}})}catch(t){let n=t instanceof Error?t.message:String(t),a;r&&(r=await Dv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await Kv(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await Hv(e,n,a?{reviewRunLogPath:a}:void 0)}}function Lv(e){return{mode:Rv(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function Rv(e){if(e==null)return Pv;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?Fv.has(t)?t:`off`:Pv}function zv(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 Bv(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function Vv(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function Hv(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 Uv(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 Wv(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function Gv(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:Qv(n),...i.packet?{packet:i.packet}:{}}})}async function Kv(e,t,n){return Nv(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?Yv(n.curatorResult.text):void 0,conclusionText:n.curatorResult?Xv(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?qv(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?ey(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 qv(e){return e.map(e=>({...e,arguments:Jv(e.name,e.arguments)}))}function Jv(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 Yv(e){let t=Zv(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function Xv(e){return Yv(e)?void 0:$v(e,8e3)}function Zv(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 Qv(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 $v(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function ey(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let ty=!1;function ny(){ty||=(Qt(),Zt({api:`openai-completions`,stream:qo,streamSimple:Jo}),!0)}const ry=[`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(`
173
+ `);async function iy(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o,onFallback:s,titleGeneration:c}=e,l=t.trim().replace(/\s+/g,` `);if(!l)return`New session`;if(c?.enabled===!1||!r.flashModel)return ly(l);let u=ly(l),d=r.flashModel,f=ce({apiFormat:r.apiFormat,baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:d,hooks:a,hookCtx:o}),p=[{role:`user`,content:l}];n&&p.push({role:`assistant`,content:n});let m=oy(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await f.chat({system:ry,user:JSON.stringify(p),temperature:0,maxTokens:100,signal:m.signal})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(sy(t)){if(m.didTimeout())return s?.(`timeout`),u;throw t}e<3&&await ay(500*e,m.signal)}}catch(e){if(sy(e)&&m.didTimeout())return s?.(`timeout`),u;throw e}finally{m.clear()}return s?.(`error`),u}function ay(e,t){return t?t.aborted?Promise.reject(cy()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(cy())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function oy(e,t){let n=new AbortController,r=!1,i=setTimeout(()=>{r=!0,n.abort()},t);return e?.aborted?n.abort():e?.addEventListener(`abort`,()=>n.abort(),{once:!0}),{signal:n.signal,clear:()=>clearTimeout(i),didTimeout:()=>r}}function sy(e){return e instanceof Error&&e.name===`AbortError`}function cy(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function ly(e,t=80){if(!e)return`New session`;try{let t=JSON.parse(e);if(Array.isArray(t))return t?.[0]?.content?.[0].text??e}catch{}let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:n.slice(0,t-1)+`…`}async function uy(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});let l={eventDispatcher:c};if(await o.dispatch(`session_start`,{sessionId:t,reason:e.resetCommand?`reset`:`startup`},s,l),e.piExtensionDir&&e.registerSkillDir){let t=await o.dispatch(`resources_discover`,{extensionDir:e.piExtensionDir},s,l);for(let n of t)if(!(!n||!(`skillPaths`in n)||!n.skillPaths))for(let t of n.skillPaths)e.registerSkillDir(t)}}async function dy(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await my(await F(r.dataDir,t,{...$(r)}),r);await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs,messages:o},a,{eventDispatcher:e.eventDispatcher})}async function fy(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await F(r.dataDir,t,{...$(r)});await i.dispatch(`session_end`,{sessionId:t,messageCount:o.length,durationMs:n.durationMs,reason:n.error?`error`:`normal`},a,{eventDispatcher:e.eventDispatcher}),a.toolParamOverrides?.clear()}async function py(e){await dy(e),await fy(e)}async function my(e,t){return e.map(e=>({...e}))}function hy(e){let t=[];for(let n of e){if(n.role!==`assistant`)continue;let e=typeof n.content==`string`?n.content.trim():``;e&&t.push(e)}if(t.length!==0)return t.join(`
174
174
 
175
- `).slice(0,4e3)}async function hy(e){if(e.coreConfig?.capture?.enabled!==!0)return;let t=my(e.transcript);if(t)try{typeof e.runContext.memoryProvider.appendRecent==`function`?await e.runContext.memoryProvider.appendRecent(t,`daily`):await e.runContext.memoryProvider.append(t)}catch(t){await e.eventDispatcher?.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`memory`,phase:`capture_flush_failed`,message:`core capture flush failed`,details:{error:t instanceof Error?t.message:String(t)}}).catch(()=>{})}}async function gy(e){if(!(!e.runContext||e.runParams.memory?.core?.capture?.enabled!==!0||e.runParams.subagentContext))try{let t=await F(e.runParams.dataDir,e.sessionId,$(e.runParams));await hy({runContext:e.runContext,coreConfig:e.runParams.memory.core,sessionId:e.sessionId,transcript:t,eventDispatcher:e.eventDispatcher})}catch(t){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`memory`,phase:`capture_flush_failed`,message:`capture flush failed during finalize`,details:{error:t instanceof Error?t.message:String(t)}}).catch(()=>{})}}async function _y(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:a=!1,runParams:o,hookRegistry:c,hookContext:l,startTime:d,compactionEntry:f,eventDispatcher:p}=e,m=$(o);if(a||await h(o.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},m),f&&await h(o.dataDir,n,f,m),await h(o.dataDir,n,{role:`assistant`,content:t,...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{},timestamp:new Date().toISOString()},m),r){let t=await by({sessionId:n,titleSource:i.trim()?i:`New session`,text:e.replyText,runParams:o,hookRegistry:c,hookContext:l});await u(o.dataDir,n,{title:t},m),await p.dispatchProgress(n,{type:`title_updated`,title:t})}let g=Date.now()-d,v={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:g,...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{},context:{snapshotPath:_(o.dataDir,n,$(o)),toolResultsDir:s(o.dataDir,n,$(o))}};return W.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:g,isNewSession:r,textLength:t.length,hasCompactionEntry:!!f,snapshotPath:v.context.snapshotPath,toolResultsDir:v.context.toolResultsDir}),await gy({sessionId:n,runParams:o,runContext:e.runContext,eventDispatcher:p}),await fy({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function vy(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:a,hookContext:o,startTime:c,text:l,usage:d,error:f,paused:p,uiToolPending:m,artifacts:h,eventDispatcher:g,sessionEndOnly:v}=e;if(n){let n=$(i),s=await by({sessionId:t,titleSource:r,text:e.text,runParams:i,hookRegistry:a,hookContext:o,logLifecycle:!0});await u(i.dataDir,t,{title:s},n),await g.dispatchProgress(t,{type:`title_updated`,title:s})}let y={sessionId:t,text:l,usage:d,durationMs:Date.now()-c,error:f,paused:p,uiToolPending:m,...h&&h.length>0?{artifacts:h}:{},context:{snapshotPath:_(i.dataDir,t,$(i)),toolResultsDir:s(i.dataDir,t,$(i))}};h&&h.length>0&&e.transcriptStartIndex!==void 0&&!p&&!m&&await yy({dataDir:i.dataDir,sessionId:t,pathOptions:$(i),transcriptStartIndex:e.transcriptStartIndex,artifacts:h});let b={sessionId:t,kind:`completed`,durationMs:y.durationMs,isNewSession:n,inputTokens:d.input,outputTokens:d.output,totalTokens:d.total,hasError:!!f,error:f,paused:!!p,uiToolPending:!!m,textLength:l.length,snapshotPath:y.context.snapshotPath,toolResultsDir:y.context.toolResultsDir};f?W.warn(`agent run finalized with error`,b):W.info(`agent run finalized`,b),await gy({sessionId:t,runParams:i,runContext:e.runContext,eventDispatcher:g});let x={sessionId:t,result:y,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:g};return v?await dy(x):await fy(x),y}async function yy(e){let t=await F(e.dataDir,e.sessionId,e.pathOptions),n=Math.max(0,e.transcriptStartIndex),r=t[n]?.role===`user`?n+1:n,i=t.findIndex((e,t)=>t>=r&&e.role===`user`),a=i===-1?t.length:i,o=-1;for(let e=a-1;e>=n;--e)if(t[e]?.role===`assistant`){o=e;break}o!==-1&&await ee(e.dataDir,e.sessionId,t=>t.map((t,n)=>n!==o||t.role!==`assistant`?t:{...t,artifacts:e.artifacts}),e.pathOptions)}async function by(e){let t=cy(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&W.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await ry({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,titleGeneration:e.runParams.titleGeneration,onFallback:e=>{n=e}});return n?W.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&W.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return W.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const xy=new Set([`pause`,`resume`,`clear`,`help`]),Sy=`/goal
175
+ `).slice(0,4e3)}async function gy(e){if(e.coreConfig?.capture?.enabled!==!0)return;let t=hy(e.transcript);if(t)try{typeof e.runContext.memoryProvider.appendRecent==`function`?await e.runContext.memoryProvider.appendRecent(t,`daily`):await e.runContext.memoryProvider.append(t)}catch(t){await e.eventDispatcher?.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`memory`,phase:`capture_flush_failed`,message:`core capture flush failed`,details:{error:t instanceof Error?t.message:String(t)}}).catch(()=>{})}}async function _y(e){if(!(!e.runContext||e.runParams.memory?.core?.capture?.enabled!==!0||e.runParams.subagentContext))try{let t=await F(e.runParams.dataDir,e.sessionId,$(e.runParams));await gy({runContext:e.runContext,coreConfig:e.runParams.memory.core,sessionId:e.sessionId,transcript:t,eventDispatcher:e.eventDispatcher})}catch(t){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`memory`,phase:`capture_flush_failed`,message:`capture flush failed during finalize`,details:{error:t instanceof Error?t.message:String(t)}}).catch(()=>{})}}async function vy(e){let{replyText:t,sessionId:n,isNewSession:r,transcriptMessage:i,initialUserEntryPersisted:a=!1,runParams:o,hookRegistry:c,hookContext:l,startTime:d,compactionEntry:f,eventDispatcher:p}=e,m=$(o);if(a||await h(o.dataDir,n,{role:`user`,content:i,timestamp:new Date().toISOString()},m),f&&await h(o.dataDir,n,f,m),await h(o.dataDir,n,{role:`assistant`,content:t,...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{},timestamp:new Date().toISOString()},m),r){let t=await xy({sessionId:n,titleSource:i.trim()?i:`New session`,text:e.replyText,runParams:o,hookRegistry:c,hookContext:l});await u(o.dataDir,n,{title:t},m),await p.dispatchProgress(n,{type:`title_updated`,title:t})}let g=Date.now()-d,v={sessionId:n,text:t,usage:{input:0,output:0,total:0},durationMs:g,...e.artifacts&&e.artifacts.length>0?{artifacts:e.artifacts}:{},context:{snapshotPath:_(o.dataDir,n,$(o)),toolResultsDir:s(o.dataDir,n,$(o))}};return W.info(`agent run finalized`,{sessionId:n,kind:`short_circuit`,durationMs:g,isNewSession:r,textLength:t.length,hasCompactionEntry:!!f,snapshotPath:v.context.snapshotPath,toolResultsDir:v.context.toolResultsDir}),await _y({sessionId:n,runParams:o,runContext:e.runContext,eventDispatcher:p}),await py({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function yy(e){let{sessionId:t,isNewSession:n,transcriptMessage:r,runParams:i,hookRegistry:a,hookContext:o,startTime:c,text:l,usage:d,error:f,paused:p,uiToolPending:m,artifacts:h,eventDispatcher:g,sessionEndOnly:v}=e;if(n){let n=$(i),s=await xy({sessionId:t,titleSource:r,text:e.text,runParams:i,hookRegistry:a,hookContext:o,logLifecycle:!0});await u(i.dataDir,t,{title:s},n),await g.dispatchProgress(t,{type:`title_updated`,title:s})}let y={sessionId:t,text:l,usage:d,durationMs:Date.now()-c,error:f,paused:p,uiToolPending:m,...h&&h.length>0?{artifacts:h}:{},context:{snapshotPath:_(i.dataDir,t,$(i)),toolResultsDir:s(i.dataDir,t,$(i))}};h&&h.length>0&&e.transcriptStartIndex!==void 0&&!p&&!m&&await by({dataDir:i.dataDir,sessionId:t,pathOptions:$(i),transcriptStartIndex:e.transcriptStartIndex,artifacts:h});let b={sessionId:t,kind:`completed`,durationMs:y.durationMs,isNewSession:n,inputTokens:d.input,outputTokens:d.output,totalTokens:d.total,hasError:!!f,error:f,paused:!!p,uiToolPending:!!m,textLength:l.length,snapshotPath:y.context.snapshotPath,toolResultsDir:y.context.toolResultsDir};f?W.warn(`agent run finalized with error`,b):W.info(`agent run finalized`,b),await _y({sessionId:t,runParams:i,runContext:e.runContext,eventDispatcher:g});let x={sessionId:t,result:y,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:g};return v?await fy(x):await py(x),y}async function by(e){let t=await F(e.dataDir,e.sessionId,e.pathOptions),n=Math.max(0,e.transcriptStartIndex),r=t[n]?.role===`user`?n+1:n,i=t.findIndex((e,t)=>t>=r&&e.role===`user`),a=i===-1?t.length:i,o=-1;for(let e=a-1;e>=n;--e)if(t[e]?.role===`assistant`){o=e;break}o!==-1&&await ee(e.dataDir,e.sessionId,t=>t.map((t,n)=>n!==o||t.role!==`assistant`?t:{...t,artifacts:e.artifacts}),e.pathOptions)}async function xy(e){let t=ly(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&W.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await iy({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,titleGeneration:e.runParams.titleGeneration,onFallback:e=>{n=e}});return n?W.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&W.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return W.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const Sy=new Set([`pause`,`resume`,`clear`,`help`]),Cy=`/goal
176
176
  【目标】:把 src/auth 目录下重复的参数校验逻辑抽离成公共函数。
177
177
  【范围】:只处理 src/auth 目录,不扩散到用户模块或订单模块。
178
178
  【约束】:保持现有 API 兼容,不引入新依赖,不要改变数据库结构。
179
179
  【验证】:每次改动后请自主运行 npm test auth 以及 npm run typecheck。如果测试失败,请定位原因并修复。
180
- 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function Cy(){return[`/goal 命令`,` /goal <目标内容> 设置或替换 /goal 目标(设为进行中)`,` /goal --token-budget <n> <目标内容> 设置带 Token 预算的 /goal 目标(0 表示不限)`,` /goal 查看当前 /goal 目标摘要`,` /goal pause 暂停 /goal 目标继续执行`,` /goal resume 恢复已暂停的 /goal 目标`,` /goal clear 清除 /goal 目标`,``,`多行结构化示例(/goal 后换行;Console 用 Shift+Enter 换行,Enter 发送):`,Sy].join(`
181
- `)}function wy(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,Sy,``,`正文(写入 objective.txt 供 --goal-file):`,Sy.replace(/^\/goal\s+/,``)].join(`
182
- `)}async function Ty(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await H(e.dataDir,e.sessionId,t);if(!r){let r=await U(e.dataDir,e.sessionId,{goalId:Lt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await rr(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`created`,goal:r}}if((await z(e.dataDir,e.sessionId,r,t)).trim()!==n){let r=await U(e.dataDir,e.sessionId,{goalId:Lt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await rr(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`replaced`,goal:r}}if(r.status===`complete`)return{action:`unchanged`,goal:r};let i={};if(r.status===`paused`&&(i.status=`active`),e.tokenBudget!==void 0&&e.tokenBudget!==r.tokenBudget&&(i.tokenBudget=e.tokenBudget),Object.keys(i).length===0)return{action:`unchanged`,goal:r};let a=await V(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function Ey(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(xy.has(n))return{action:n,objective:``};let r=t,i,a=r.match(/^--token-budget\s+(\S+)(?:\s+([\s\S]*))?$/);if(a){let e=a[1]??``;if(i=e===`0`?null:Number.parseInt(e,10),i!==null&&(!Number.isFinite(i)||i<=0))throw Error(`--token-budget 必须是正整数,或使用 0 表示不限。`);r=(a[2]??``).trim()}if(!r)throw Error(`用法:/goal <目标内容> 或 /goal --token-budget <n> <目标内容>`);return{action:`set`,objective:r,tokenBudget:i}}function Dy(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function Oy(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function ky(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${Dy(e.status)}`,`目标内容:${t.length>200?`${t.slice(0,200)}...`:t}`,i,`已用时:${e.timeUsedSeconds} 秒`];return r===`workflow_not_initialized`?a.push(``,`Workflow:未初始化(goal/state.json 缺失)`):n&&(a.push(``,`Workflow:`,` 状态:${Oy(n.workflowStatus)}`,n.currentTaskTitle?` 当前任务:${n.currentTaskTitle}(${n.currentTaskStatus??`unknown`})`:` 当前任务:(无)`),n.blockedReason&&a.push(` 阻塞原因:${n.blockedReason}`),a.push(` 待完成必需任务:${n.openRequiredTasks}`)),a.push(``,jy(e.status)),a.join(`
183
- `)}async function Ay(e,t,n){let r=await tr(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return ky(t,n,r.goalState,r.workflowWarning)}function jy(e){switch(e){case`active`:return`可用命令:/goal pause、/goal clear`;case`paused`:return`可用命令:/goal resume、/goal clear`;case`budget_limited`:return`/goal 目标已触达预算限制。可用命令:/goal clear(不要仅因预算耗尽就判定为已完成)`;case`complete`:return`/goal 目标已完成。可用命令:/goal clear`;default:return`可用命令:/goal <目标内容>、/goal pause、/goal resume、/goal clear`}}async function My(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:Cy()};if(e.action===`get`){let e=await H(t.dataDir,t.sessionId,n);return e?{replyText:await Ay(t,e,await z(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
184
- `)}}if(e.action===`set`){let r=await Ty({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await z(t.dataDir,t.sessionId,r.goal,n);if(r.action===`unchanged`){let e=await Ay(t,r.goal,i);return{replyText:r.goal.status===`complete`?`/goal 目标已完成。\n\n${e}`:`/goal 目标未变化。\n\n${e}`}}return{replyText:`${r.action===`resumed`?`/goal 目标已恢复(进行中)。`:r.action===`updated`?`/goal 目标已更新。`:`/goal 目标已设置(进行中)。`}\n\n${await Ay(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await V(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await Ay(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能恢复。`);if(e.status===`budget_limited`)throw Error(`/goal 目标已触达预算限制,不能恢复;请使用 /goal clear 清除,或重新设置新的 /goal 目标。`);if(e.status===`active`)return{replyText:`/goal 目标已处于进行中状态。\n\n${await Ay(t,e,await z(t.dataDir,t.sessionId,e,n))}`};let r=await V(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${await Ay(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ae(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const Ny=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`},{name:`/goal`,description:`设置或查看 /goal 目标`},{name:`/goal pause`,description:`暂停 /goal 目标`},{name:`/goal resume`,description:`恢复 /goal 目标`},{name:`/goal clear`,description:`清除 /goal 目标`}];function Py(){return Ny.map(e=>({...e}))}function Fy(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Iy(e){let t=new Set,n=[];for(let r of e){let e=Fy(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Ly(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function Ry(e,t){let n=Py(),r=Iy(e),i=t?Ly(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function zy(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 By(e){let t=zy(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 Vy(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 Hy(e,t){let n=By(e);if(!n)return{kind:`none`};if(n.name===`help`)return n.rest?{kind:`unknown`,name:n.name,args:n.rest}:{kind:`help`};if(n.name===`compact`)return{kind:`compact`,instructions:n.rest};if(n.name===`goal`)try{let e=Ey(n.rest);return{kind:`goal`,action:e.action,objective:e.objective,tokenBudget:e.tokenBudget}}catch(e){return{kind:`unknown`,name:n.name,args:e.message}}if(n.name===`new`||n.name===`reset`)return{kind:`reset`,action:n.name===`new`?`new`:`reset`,remainder:n.rest};if(n.name===`skill`){if(!n.rest)return{kind:`unknown`,name:n.name,args:``};let e=n.rest.match(/^([^\s]+)(?:\s+([\s\S]+))?$/);return e?{kind:`skill`,name:Fy(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Iy(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 Uy=new Set([`/new`,`/reset`,`/compact`]),Wy=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),Gy=new Set([`/help`]);function Ky(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function qy(e){if(e.length===0)return[];let t=e.map(Ky),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Jy(e){let t=Ry(e.skills),n=t.builtin.filter(e=>Uy.has(e.name)),r=t.builtin.filter(e=>Wy.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>Gy.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...qy(n)),s.push(``),s.push(`目标命令`),s.push(...qy(r)),s.push(``),s.push(`技能命令`),s.push(...qy(i)),o.length>0?(s.push(...qy(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...qy(a)),{kind:`reply`,text:s.join(`
185
- `)}}function Yy(e,t){let n=t.trim().toLowerCase();return n&&Iy(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function Xy(e){let t=Yy(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(`
180
+ 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function wy(){return[`/goal 命令`,` /goal <目标内容> 设置或替换 /goal 目标(设为进行中)`,` /goal --token-budget <n> <目标内容> 设置带 Token 预算的 /goal 目标(0 表示不限)`,` /goal 查看当前 /goal 目标摘要`,` /goal pause 暂停 /goal 目标继续执行`,` /goal resume 恢复已暂停的 /goal 目标`,` /goal clear 清除 /goal 目标`,``,`多行结构化示例(/goal 后换行;Console 用 Shift+Enter 换行,Enter 发送):`,Cy].join(`
181
+ `)}function Ty(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,Cy,``,`正文(写入 objective.txt 供 --goal-file):`,Cy.replace(/^\/goal\s+/,``)].join(`
182
+ `)}async function Ey(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await H(e.dataDir,e.sessionId,t);if(!r){let r=await U(e.dataDir,e.sessionId,{goalId:Lt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await rr(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`created`,goal:r}}if((await z(e.dataDir,e.sessionId,r,t)).trim()!==n){let r=await U(e.dataDir,e.sessionId,{goalId:Lt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await rr(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`replaced`,goal:r}}if(r.status===`complete`)return{action:`unchanged`,goal:r};let i={};if(r.status===`paused`&&(i.status=`active`),e.tokenBudget!==void 0&&e.tokenBudget!==r.tokenBudget&&(i.tokenBudget=e.tokenBudget),Object.keys(i).length===0)return{action:`unchanged`,goal:r};let a=await V(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function Dy(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(Sy.has(n))return{action:n,objective:``};let r=t,i,a=r.match(/^--token-budget\s+(\S+)(?:\s+([\s\S]*))?$/);if(a){let e=a[1]??``;if(i=e===`0`?null:Number.parseInt(e,10),i!==null&&(!Number.isFinite(i)||i<=0))throw Error(`--token-budget 必须是正整数,或使用 0 表示不限。`);r=(a[2]??``).trim()}if(!r)throw Error(`用法:/goal <目标内容> 或 /goal --token-budget <n> <目标内容>`);return{action:`set`,objective:r,tokenBudget:i}}function Oy(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function ky(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function Ay(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${Oy(e.status)}`,`目标内容:${t.length>200?`${t.slice(0,200)}...`:t}`,i,`已用时:${e.timeUsedSeconds} 秒`];return r===`workflow_not_initialized`?a.push(``,`Workflow:未初始化(goal/state.json 缺失)`):n&&(a.push(``,`Workflow:`,` 状态:${ky(n.workflowStatus)}`,n.currentTaskTitle?` 当前任务:${n.currentTaskTitle}(${n.currentTaskStatus??`unknown`})`:` 当前任务:(无)`),n.blockedReason&&a.push(` 阻塞原因:${n.blockedReason}`),a.push(` 待完成必需任务:${n.openRequiredTasks}`)),a.push(``,My(e.status)),a.join(`
183
+ `)}async function jy(e,t,n){let r=await tr(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return Ay(t,n,r.goalState,r.workflowWarning)}function My(e){switch(e){case`active`:return`可用命令:/goal pause、/goal clear`;case`paused`:return`可用命令:/goal resume、/goal clear`;case`budget_limited`:return`/goal 目标已触达预算限制。可用命令:/goal clear(不要仅因预算耗尽就判定为已完成)`;case`complete`:return`/goal 目标已完成。可用命令:/goal clear`;default:return`可用命令:/goal <目标内容>、/goal pause、/goal resume、/goal clear`}}async function Ny(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:wy()};if(e.action===`get`){let e=await H(t.dataDir,t.sessionId,n);return e?{replyText:await jy(t,e,await z(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
184
+ `)}}if(e.action===`set`){let r=await Ey({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await z(t.dataDir,t.sessionId,r.goal,n);if(r.action===`unchanged`){let e=await jy(t,r.goal,i);return{replyText:r.goal.status===`complete`?`/goal 目标已完成。\n\n${e}`:`/goal 目标未变化。\n\n${e}`}}return{replyText:`${r.action===`resumed`?`/goal 目标已恢复(进行中)。`:r.action===`updated`?`/goal 目标已更新。`:`/goal 目标已设置(进行中)。`}\n\n${await jy(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await V(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await jy(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能恢复。`);if(e.status===`budget_limited`)throw Error(`/goal 目标已触达预算限制,不能恢复;请使用 /goal clear 清除,或重新设置新的 /goal 目标。`);if(e.status===`active`)return{replyText:`/goal 目标已处于进行中状态。\n\n${await jy(t,e,await z(t.dataDir,t.sessionId,e,n))}`};let r=await V(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${await jy(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ae(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const Py=[{name:`/help`,description:`显示可用命令`},{name:`/new`,description:`开始新会话`},{name:`/reset`,description:`重置当前会话`},{name:`/compact`,description:`精简会话上下文`},{name:`/skill`,description:`按名称运行技能`},{name:`/goal`,description:`设置或查看 /goal 目标`},{name:`/goal pause`,description:`暂停 /goal 目标`},{name:`/goal resume`,description:`恢复 /goal 目标`},{name:`/goal clear`,description:`清除 /goal 目标`}];function Fy(){return Py.map(e=>({...e}))}function Iy(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Ly(e){let t=new Set,n=[];for(let r of e){let e=Iy(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Ry(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function zy(e,t){let n=Fy(),r=Ly(e),i=t?Ry(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function By(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 Vy(e){let t=By(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 Hy(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 Uy(e,t){let n=Vy(e);if(!n)return{kind:`none`};if(n.name===`help`)return n.rest?{kind:`unknown`,name:n.name,args:n.rest}:{kind:`help`};if(n.name===`compact`)return{kind:`compact`,instructions:n.rest};if(n.name===`goal`)try{let e=Dy(n.rest);return{kind:`goal`,action:e.action,objective:e.objective,tokenBudget:e.tokenBudget}}catch(e){return{kind:`unknown`,name:n.name,args:e.message}}if(n.name===`new`||n.name===`reset`)return{kind:`reset`,action:n.name===`new`?`new`:`reset`,remainder:n.rest};if(n.name===`skill`){if(!n.rest)return{kind:`unknown`,name:n.name,args:``};let e=n.rest.match(/^([^\s]+)(?:\s+([\s\S]+))?$/);return e?{kind:`skill`,name:Iy(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Ly(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 Wy=new Set([`/new`,`/reset`,`/compact`]),Gy=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),Ky=new Set([`/help`]);function qy(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function Jy(e){if(e.length===0)return[];let t=e.map(qy),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Yy(e){let t=zy(e.skills),n=t.builtin.filter(e=>Wy.has(e.name)),r=t.builtin.filter(e=>Gy.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>Ky.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...Jy(n)),s.push(``),s.push(`目标命令`),s.push(...Jy(r)),s.push(``),s.push(`技能命令`),s.push(...Jy(i)),o.length>0?(s.push(...Jy(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...Jy(a)),{kind:`reply`,text:s.join(`
185
+ `)}}function Xy(e,t){let n=t.trim().toLowerCase();return n&&Ly(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function Zy(e){let t=Xy(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(`
186
186
 
187
- `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function Zy(e){let t=Hy(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Jy(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?Xy({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:t.kind===`unknown`&&t.name===`goal`?{kind:`reply`,text:t.args||`用法:/goal <目标内容> | /goal pause | /goal resume | /goal clear`}:{kind:`pass`,message:e.message}}async function Qy(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=$y(t),l=c>=0?t[c].content:void 0,u=Us(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}=uc(u,n);return f.length===0&&u.length>1&&(f=u.slice(0,u.length-1),d=u.slice(u.length-1)),f.length===0?{status:`skipped`,reason:`Not enough history to compact.`,estimatedTokens:J(u)}:{status:`compacted`,entry:{role:`compaction`,content:await $s({entries:f,llm:r,previousSummary:l,instructions:i,contextWindowTokens:n,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:J(d)}}function $y(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const eb=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
188
- `),tb=[`.aimax/new.txt`];async function nb(e){try{return(await Nt(e,`utf-8`)).trim()||null}catch{return null}}async function rb(e){for(let t of tb){let n=await nb(Pt(e,t));if(n)return n}return await nb(`/aimax_pvc/new.txt`)||eb}async function ib(e){return{kind:`reply`,text:await rb(e)}}function ab(){return{kind:`reply`,text:`✅ Session reset.`}}async function ob(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function sb(e,t,n){let r=n.before?.status??null,i=n.after?.status??null,a=n.before?.goalId,o=n.after?.goalId;r===i&&a===o||await ob(e,t,{action:n.action,goal:n.after??null})}function cb(e){let t=db(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?fb(r):null,a=n??i?.text,o=a?Vy(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?pb(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:mb(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function lb(e,t,n){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 r=e.slashCommandSource??``,i=r.match(/^\/([^\s]+)/);if(i&&n&&n.resolveCommand(i[1]??``)){let e=r.replace(/^\/[^\s]+\s*/,``).trim();return{kind:`extension`,name:i[1]??``,args:e}}let a=Hy(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=Zy({message:e.messageForRun??``,skills:t});if(o.kind===`reply`)return{kind:`reply`,replyText:o.text,transcriptMessage:e.transcriptMessage};if(o.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:o.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(o.kind===`rewrite`){let t=e.inputMode===`text`?o.message:pb(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:mb(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function ub(e){let t=lb(e.invocation,e.skills,e.extensionHost);if(t.kind===`extension`&&e.extensionHost){let n=e.extensionHost.resolveCommand(t.name);if(n){let r={sessionId:e.sessionId,workspaceDir:e.hookContext.workspaceDir},i=await n.handler(t.args.split(/\s+/).filter(Boolean),r);return{kind:`completed`,result:await _y({replyText:i&&typeof i==`object`&&`text`in i?String(i.text??`Command executed.`):`Command executed.`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:e.invocation.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}}if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await _y({replyText:(t.action===`reset`?ab():await ib(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await _y({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`goal`){let n;try{n=await My({action:t.action,objective:t.objective,tokenBudget:t.tokenBudget},{dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName})}catch(e){n={replyText:`/goal 错误:${e.message}`}}return n.goalUpdate&&(await ob(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),hb(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await z(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await _y({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}if(t.kind!==`compact`)return{kind:`continue`,effectivePrompt:e.invocation.promptInput,transcriptMessage:e.invocation.transcriptMessage};let n=await Qy({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,$(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 _y({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,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function db(e){return typeof e.message==`string`}function fb(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 pb(e,t){let n=fb(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 mb(e){return typeof e==`string`?e:JSON.stringify(e)}function hb(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function gb(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,artifactAccumulator:u,appendEntry:d}=e,f=0,p=``,m=0,h=0,g;for(;!c?.aborted&&n.needsAnnounce(r)&&f<10;){f++,W.info(`subagent announce round started`,{sessionId:r,announceRound:f,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){W.info(`subagent announce round skipped`,{sessionId:r,announceRound:f,reason:`no_completed_subagents`});break}W.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:f,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 _=_b(e);await d({role:`assistant`,content:_,timestamp:new Date().toISOString()});let v=await u_({agent:t,message:_,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,artifactAccumulator:u,onTurnRecordProduced:async(e,t)=>{e&&await d(e);for(let e of t)await d(e)}});p=v.text,m+=v.inputTokens,h+=v.outputTokens,v.error&&!g&&(g=v.error),n.markAnnounced(e.map(e=>e.runId));let y={sessionId:r,announceRound:f,completedCount:e.length,inputTokens:v.inputTokens,outputTokens:v.outputTokens,hasError:!!v.error,error:v.error,responseTextLength:v.text.length};v.error?W.warn(`subagent announce round completed with error`,y):W.info(`subagent announce round completed`,y)}return f>=10&&n.needsAnnounce(r)&&W.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:f,maxRounds:10}),{text:p,inputTokens:m,outputTokens:h,error:g}}function _b(e){if(e.length===1){let t=e[0];return th({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>th({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
187
+ `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function Qy(e){let t=Uy(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Yy(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?Zy({ctx:e,skillName:t.name,args:t.args}):t.kind===`unknown`&&t.name===`skill`?{kind:`reply`,text:`Usage: /skill <name> [input]`}:t.kind===`unknown`&&t.name===`goal`?{kind:`reply`,text:t.args||`用法:/goal <目标内容> | /goal pause | /goal resume | /goal clear`}:{kind:`pass`,message:e.message}}async function $y(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=eb(t),l=c>=0?t[c].content:void 0,u=Ws(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}=dc(u,n);return f.length===0&&u.length>1&&(f=u.slice(0,u.length-1),d=u.slice(u.length-1)),f.length===0?{status:`skipped`,reason:`Not enough history to compact.`,estimatedTokens:J(u)}:{status:`compacted`,entry:{role:`compaction`,content:await ec({entries:f,llm:r,previousSummary:l,instructions:i,contextWindowTokens:n,signal:a,hooks:o,hookCtx:s}),keptCount:d.length,droppedCount:f.length,timestamp:new Date().toISOString()},keptCount:d.length,droppedCount:f.length,estimatedTokens:J(d)}}function eb(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const tb=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
188
+ `),nb=[`.aimax/new.txt`];async function rb(e){try{return(await Nt(e,`utf-8`)).trim()||null}catch{return null}}async function ib(e){for(let t of nb){let n=await rb(Pt(e,t));if(n)return n}return await rb(`/aimax_pvc/new.txt`)||tb}async function ab(e){return{kind:`reply`,text:await ib(e)}}function ob(){return{kind:`reply`,text:`✅ Session reset.`}}async function sb(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function cb(e,t,n){let r=n.before?.status??null,i=n.after?.status??null,a=n.before?.goalId,o=n.after?.goalId;r===i&&a===o||await sb(e,t,{action:n.action,goal:n.after??null})}function lb(e){let t=fb(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?pb(r):null,a=n??i?.text,o=a?Hy(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?mb(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:hb(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function ub(e,t,n){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 r=e.slashCommandSource??``,i=r.match(/^\/([^\s]+)/);if(i&&n&&n.resolveCommand(i[1]??``)){let e=r.replace(/^\/[^\s]+\s*/,``).trim();return{kind:`extension`,name:i[1]??``,args:e}}let a=Uy(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=Qy({message:e.messageForRun??``,skills:t});if(o.kind===`reply`)return{kind:`reply`,replyText:o.text,transcriptMessage:e.transcriptMessage};if(o.kind===`compact`)return{kind:`compact`,transcriptMessage:e.transcriptMessage,instructions:o.instructions,initialUserEntryPersisted:e.resetCommand?!0:void 0};if(o.kind===`rewrite`){let t=e.inputMode===`text`?o.message:mb(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:hb(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function db(e){let t=ub(e.invocation,e.skills,e.extensionHost);if(t.kind===`extension`&&e.extensionHost){let n=e.extensionHost.resolveCommand(t.name);if(n){let r={sessionId:e.sessionId,workspaceDir:e.hookContext.workspaceDir},i=await n.handler(t.args.split(/\s+/).filter(Boolean),r);return{kind:`completed`,result:await vy({replyText:i&&typeof i==`object`&&`text`in i?String(i.text??`Command executed.`):`Command executed.`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:e.invocation.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}}if(t.kind===`run`)return{kind:`continue`,effectivePrompt:t.effectivePrompt,transcriptMessage:t.transcriptMessage};if(t.kind===`reset_reply`)return{kind:`completed`,result:await vy({replyText:(t.action===`reset`?ob():await ab(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await vy({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`goal`){let n;try{n=await Ny({action:t.action,objective:t.objective,tokenBudget:t.tokenBudget},{dataDir:e.runParams.dataDir,sessionId:e.sessionId,sessionStoreName:e.runParams.sessionStoreName})}catch(e){n={replyText:`/goal 错误:${e.message}`}}return n.goalUpdate&&(await sb(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),gb(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await z(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await vy({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}if(t.kind!==`compact`)return{kind:`continue`,effectivePrompt:e.invocation.promptInput,transcriptMessage:e.invocation.transcriptMessage};let n=await $y({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,$(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 vy({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,runContext:e.runContext,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function fb(e){return typeof e.message==`string`}function pb(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 mb(e,t){let n=pb(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 hb(e){return typeof e==`string`?e:JSON.stringify(e)}function gb(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function _b(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,artifactAccumulator:u,appendEntry:d}=e,f=0,p=``,m=0,h=0,g;for(;!c?.aborted&&n.needsAnnounce(r)&&f<10;){f++,W.info(`subagent announce round started`,{sessionId:r,announceRound:f,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){W.info(`subagent announce round skipped`,{sessionId:r,announceRound:f,reason:`no_completed_subagents`});break}W.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:f,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 _=vb(e);await d({role:`assistant`,content:_,timestamp:new Date().toISOString()});let v=await d_({agent:t,message:_,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,artifactAccumulator:u,onTurnRecordProduced:async(e,t)=>{e&&await d(e);for(let e of t)await d(e)}});p=v.text,m+=v.inputTokens,h+=v.outputTokens,v.error&&!g&&(g=v.error),n.markAnnounced(e.map(e=>e.runId));let y={sessionId:r,announceRound:f,completedCount:e.length,inputTokens:v.inputTokens,outputTokens:v.outputTokens,hasError:!!v.error,error:v.error,responseTextLength:v.text.length};v.error?W.warn(`subagent announce round completed with error`,y):W.info(`subagent announce round completed`,y)}return f>=10&&n.needsAnnounce(r)&&W.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:f,maxRounds:10}),{text:p,inputTokens:m,outputTokens:h,error:g}}function vb(e){if(e.length===1){let t=e[0];return nh({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>nh({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
189
189
 
190
190
  ---
191
191
 
192
- `)}`}async function vb(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i,runtimeBridge:a}=e,o=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},s=t.plugins?Date.now():void 0,c=t.plugins?Ne({...t.plugins,config:t.plugins.config,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):void 0,l=s===void 0?void 0:Math.max(0,Date.now()-s);if(!c)return o({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`}),{hookRegistry:new de,pluginSkillDirs:[],pluginTools:[]};o({level:c.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:c.registry.plugins.length,enabledPluginCount:c.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:c.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:c.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:c.diagnostics.length,durationMs:l}});for(let e of c.registry.plugins)o({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,durationMs:e.durationMs,errorMessage:e.error}});for(let e of c.diagnostics)o({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}});let u=je(c.normalizedConfig),d;if(u.length>0){let e=await Ae(c.normalizedConfig);if(e.length>0){d=new nt(e);let s=n.session?.getSessionDir?.(),l=t.createPiExtensionDialogBridge?.(r),u={};for(let[e,t]of Object.entries(c.normalizedConfig.entries??{}))t?.config&&typeof t.config==`object`&&(u[e]=t.config);let f=new Map;for(let t of e){let e=`pi:${t.name}`;u[e]&&f.set(e,u[e])}await d.activate({hookRegistry:c.registry.hooks,toolRegistry:c.registry.tools,hookContext:n,eventDispatcher:i,sessionId:r,sessionDir:s,runtimeBridge:a,dialogBridge:l,piExtensionConfigs:f}),o({level:`info`,scope:`plugin`,phase:`pi_extensions_activated`,message:`pi extensions activated`,details:{extensionCount:e.length,extensionNames:e.map(e=>e.name),commandCount:d.getRegisteredCommands().size}})}}return{hookRegistry:c.registry.hooks,pluginSkillDirs:c.registry.skills,pluginTools:[...c.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...c.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??c.normalizedConfig.slots?.memory,extensionHost:d}}var yb=class{agent=null;messageQueue=[];compactRequest=null;bindAgent(e){this.agent=e}dispose(){this.agent=null,this.messageQueue=[],this.compactRequest=null}sendUserMessage(e,t){this.messageQueue.push({content:e,deliverAs:t?.deliverAs,resolve:()=>{}})}isIdle(){if(!this.agent)return!0;let e=this.agent.state;return!e.isStreaming&&(e.pendingToolCalls?.size??0)===0}requestCompact(e){this.compactRequest=e??{}}drainMessages(){let e=this.messageQueue.map(e=>e.content);return this.messageQueue=[],e}drainCompactRequest(){let e=this.compactRequest;return this.compactRequest=null,e}hasPendingMessages(){return this.messageQueue.length>0}hasPendingCompact(){return this.compactRequest!==null}};async function bb(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=ph(t),o=n,s=!o,c=$(t);o?(await w(t.dataDir,o,c)||(s=!0),await v(t.dataDir,o,c)):o=await T(t.dataDir,t.channel,{...c});let l={sessionId:o,messageId:t.messageId,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>F(t.dataDir,o,c)}},u=new yb,d=await vb({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await mh({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:d.memoryPluginId,eventDispatcher:i,hookRegistry:f});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:f,pluginContext:d,runContext:p,runtimeBridge:u,start:e=>ly({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function xb(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Sb(e){if(!(e instanceof Error))return{errorValue:xb(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]=xb(n[e]));return t}async function Cb(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Sb(e.error)}})}function wb(e,t,n){return K.join(r(e,t,n),`pending-ui-tool.json`)}async function Tb(e,t,n,i){let a=r(e,t,i);await G.mkdir(a,{recursive:!0}),await L(wb(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function Eb(e,t,n){let r=await o(wb(e,t,n));return r===null?null:JSON.parse(r)}async function Db(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Tb(e,t,a,r),a}async function Ob(e,t,n,r,i){let a=await Eb(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 Tb(e,t,o,i),o}async function kb(e,t,n){try{await G.unlink(wb(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Ab(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function jb(e,t,n,r,i,a){let o=await H(e,t,{storeName:a?.storeName});await Ab(e,t,n,a);let s=await on(e,t,n,r,a);return s.goal&&await sb(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function Mb(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Mt(t))}async function Nb(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=wo();if(i=await To(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(So(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Pb(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 Pb(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}const Fb=2e4,Ib=15e4,Lb=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Rb(e){return K.join(e,`.aimax`)}async function zb(e){let t=Rb(e),n=[];for(let e of Lb){let r=K.join(t,e);try{let t=await G.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await G.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function Bb(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(`
192
+ `)}`}async function yb(e){let{runParams:t,hookContext:n,sessionId:r,eventDispatcher:i,runtimeBridge:a}=e,o=e=>{i.dispatchDiagnostic(r,e).catch(()=>void 0)},s=t.plugins?Date.now():void 0,c=t.plugins?Ne({...t.plugins,config:t.plugins.config,runtime:{llm:t.llm,hookCtx:n,llmAllowlist:t.plugins.llmAllowlist,env:t.env}}):void 0,l=s===void 0?void 0:Math.max(0,Date.now()-s);if(!c)return o({level:`info`,scope:`plugin`,phase:`plugin_system_disabled`,message:`plugin system disabled for this run`}),{hookRegistry:new de,pluginSkillDirs:[],pluginTools:[]};o({level:c.diagnostics.some(e=>e.level===`error`)?`warn`:`info`,scope:`plugin`,phase:`plugin_system_initialized`,message:`plugin system initialized`,details:{pluginCount:c.registry.plugins.length,enabledPluginCount:c.registry.plugins.filter(e=>e.status===`loaded`).length,disabledPluginCount:c.registry.plugins.filter(e=>e.status===`disabled`).length,errorPluginCount:c.registry.plugins.filter(e=>e.status===`error`).length,diagnosticCount:c.diagnostics.length,durationMs:l}});for(let e of c.registry.plugins)o({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,durationMs:e.durationMs,errorMessage:e.error}});for(let e of c.diagnostics)o({level:e.level===`error`?`error`:`warn`,scope:`plugin`,phase:`plugin_diagnostic`,message:e.message,details:{pluginId:e.pluginId,source:e.source}});let u=je(c.normalizedConfig),d;if(u.length>0){let e=await Ae(c.normalizedConfig);if(e.length>0){d=new nt(e);let s=n.session?.getSessionDir?.(),l=t.createPiExtensionDialogBridge?.(r),u={};for(let[e,t]of Object.entries(c.normalizedConfig.entries??{}))t?.config&&typeof t.config==`object`&&(u[e]=t.config);let f=new Map;for(let t of e){let e=`pi:${t.name}`;u[e]&&f.set(e,u[e])}await d.activate({hookRegistry:c.registry.hooks,toolRegistry:c.registry.tools,hookContext:n,eventDispatcher:i,sessionId:r,sessionDir:s,runtimeBridge:a,dialogBridge:l,piExtensionConfigs:f}),o({level:`info`,scope:`plugin`,phase:`pi_extensions_activated`,message:`pi extensions activated`,details:{extensionCount:e.length,extensionNames:e.map(e=>e.name),commandCount:d.getRegisteredCommands().size}})}}return{hookRegistry:c.registry.hooks,pluginSkillDirs:c.registry.skills,pluginTools:[...c.registry.tools.resolveEnabled(t.plugins?.toolAllowlist)??[],...c.registry.tools.resolveUiTools(r,t.uiToolResume,t.plugins?.toolAllowlist)??[]],memoryPluginId:t.memory?.pluginId??c.normalizedConfig.slots?.memory,extensionHost:d}}var bb=class{agent=null;messageQueue=[];compactRequest=null;bindAgent(e){this.agent=e}dispose(){this.agent=null,this.messageQueue=[],this.compactRequest=null}sendUserMessage(e,t){this.messageQueue.push({content:e,deliverAs:t?.deliverAs,resolve:()=>{}})}isIdle(){if(!this.agent)return!0;let e=this.agent.state;return!e.isStreaming&&(e.pendingToolCalls?.size??0)===0}requestCompact(e){this.compactRequest=e??{}}drainMessages(){let e=this.messageQueue.map(e=>e.content);return this.messageQueue=[],e}drainCompactRequest(){let e=this.compactRequest;return this.compactRequest=null,e}hasPendingMessages(){return this.messageQueue.length>0}hasPendingCompact(){return this.compactRequest!==null}};async function xb(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=mh(t),o=n,s=!o,c=$(t);o?(await w(t.dataDir,o,c)||(s=!0),await v(t.dataDir,o,c)):o=await T(t.dataDir,t.channel,{...c});let l={sessionId:o,messageId:t.messageId,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>F(t.dataDir,o,c)}},u=new bb,d=await yb({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await hh({runParams:t,sessionId:o,hookContext:l,memoryProviderId:t.memory?.providerId,memoryPluginId:d.memoryPluginId,eventDispatcher:i,hookRegistry:f});return{sessionId:o,isNewSession:s,workspaceDir:a,hookContext:l,hookRegistry:f,pluginContext:d,runContext:p,runtimeBridge:u,start:e=>uy({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function Sb(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Cb(e){if(!(e instanceof Error))return{errorValue:Sb(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]=Sb(n[e]));return t}async function wb(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Cb(e.error)}})}function Tb(e,t,n){return K.join(r(e,t,n),`pending-ui-tool.json`)}async function Eb(e,t,n,i){let a=r(e,t,i);await G.mkdir(a,{recursive:!0}),await L(Tb(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function Db(e,t,n){let r=await o(Tb(e,t,n));return r===null?null:JSON.parse(r)}async function Ob(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await Eb(e,t,a,r),a}async function kb(e,t,n,r,i){let a=await Db(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 Eb(e,t,o,i),o}async function Ab(e,t,n){try{await G.unlink(Tb(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function jb(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function Mb(e,t,n,r,i,a){let o=await H(e,t,{storeName:a?.storeName});await jb(e,t,n,a);let s=await on(e,t,n,r,a);return s.goal&&await cb(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function Nb(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Mt(t))}async function Pb(e){let t=e.params.hitlResume,n=t?.toolContext;if(!t||!n)throw Error(`before-tool HITL resume requires toolContext`);if(!(t.resolution.action===`submit`&&(t.resolution.values?.selectedChoiceIds?.includes(`approve`)??!1))){let t=`HITL approval denied; tool execution skipped.`;return await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.appendEntry({role:`tool_result`,toolCallId:n.toolCallId,toolName:n.toolName,content:t,isError:!0,timestamp:new Date().toISOString()}),{text:t,error:t}}let r=(Array.isArray(e.agent.state.tools)?e.agent.state.tools:[]).find(e=>e&&typeof e==`object`&&e.name===n.toolName&&typeof e.execute==`function`);if(!r)throw Error(`Cannot resume HITL tool call: tool not found: ${n.toolName}`);await e.appendEntry({role:`assistant`,content:``,toolCalls:[{id:n.toolCallId,name:n.toolName,arguments:n.toolArgs}],timestamp:new Date().toISOString()}),await e.eventDispatcher.dispatchProgress(e.sessionId,{type:`tool_start`,toolCallId:n.toolCallId,name:n.toolName,input:n.toolArgs});let i,a=!1;try{let t=wo();if(i=await To(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(So(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Fb(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 Fb(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}const Ib=2e4,Lb=15e4,Rb=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function zb(e){return K.join(e,`.aimax`)}async function Bb(e){let t=zb(e),n=[];for(let e of Rb){let r=K.join(t,e);try{let t=await G.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await G.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function Vb(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(`
193
193
  `),s].join(`
194
- `),truncated:!0,originalLength:r.length}}function Vb(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Hb(e,t){let n=t?.maxChars??Fb,r=Math.max(1,t?.totalMaxChars??Math.max(n,Ib)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Vb(`[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}=Bb(a.content??``,a.name,e),l=Vb(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 Ub=`You are a personal assistant running inside AiMax.`;async function Wb(e){try{return{presetSystemPrompt:Vt(await G.readFile(e,`utf-8`)).content.trim()||Ub}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:Ub};throw e}}async function Gb(){return Wb(`/aimax_pvc/system_prompt.md`)}async function Kb(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await zb(t.dataDir),o=[],s=Hb(a,{warn:e=>o.push(e)}),c=await Gb();await i.dispatchDiagnostic(n,{level:o.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length}}),W.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await bp(t.dataDir,r.pluginSkillDirs,l),d=await Ca({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),W.info(`skills loaded`,{sessionId:n,skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length}),await i.dispatchDiagnostic(n,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,agents:d.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),W.info(`custom agents loaded`,{sessionId:n,agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,requestedAgentName:m.requestedAgentName}),{contextFiles:s,bootstrapWarnings:o,skills:u,autoSkillCategories:await qb({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function qb(e){if(!e.enabled)return[];try{let t=await new Xi({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var Jb=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const Yb={Inferred:1,Child:2,Own:3};var Xb=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=Qb(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,Yb.Own)}addInferred(e){this.add(e,Yb.Inferred)}addChild(e){e&&e.length>0&&this.add(e,Yb.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=Zb(n),r=this.indices.get(e);if(r!==void 0){let e=this.records[r];e&&t>e.priority&&(this.records[r]={record:n,priority:t});continue}this.indices.set(e,this.records.length),this.records.push({record:n,priority:t})}}shouldCollect(e){if(e.kind!==`url`||!this.urlWhitelist)return!0;let t=$b(e.url);return t?this.urlWhitelist.has(t):!1}};function Zb(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function Qb(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function $b(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const ex=`crons`;function tx(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:oe(e.message)}}async function nx(e){let t,n=0,r=0,i;if(e.runtimeBridge.hasPendingMessages()){let a=e.runtimeBridge.drainMessages();for(let o of a){let a=await u_({agent:e.agent,message:o,continueFromHistory:!1,sessionId:e.sessionId,channel:e.channel,modelId:e.resolvedModelId,historyMessages:e.runtime.historyMessages,eventDispatcher:e.eventDispatcher,hooks:e.hookRegistry,hookCtx:e.hookContext,abortSignal:e.abortSignal,retry:e.retry,onTurnRecordProduced:async(t,n)=>{t&&await e.appendEntry(t);for(let t of n)await e.appendEntry(t)}});n+=a.inputTokens,r+=a.outputTokens,a.text&&(t=a.text),a.error&&(i=a.error);let s=await gb({agent:e.agent,registry:e.registry,sessionId:e.sessionId,resolvedModelId:e.resolvedModelId,eventDispatcher:e.eventDispatcher,hookRegistry:e.hookRegistry,hookContext:e.hookContext,abortSignal:e.abortSignal,appendEntry:e.appendEntry});n+=s.inputTokens,r+=s.outputTokens,s.text&&(t=s.text),s.error&&!i&&(i=s.error)}}let a=e.runtimeBridge.drainCompactRequest();if(a)try{let t=await Qy({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,$(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{apiFormat:e.runParams.llm.apiFormat,baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:a.customInstructions,signal:e.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});t.status===`compacted`&&await e.appendEntry(t.entry),a.onComplete?.(t)}catch(e){a.onError?.(e instanceof Error?e:Error(String(e)))}return{lastResponseText:t,inputTokens:n,outputTokens:r,error:i}}async function rx(e,t){ty();let n=Date.now(),i=new Ra(e),a=new Xb({urlWhitelist:e.artifactsUrlWhitelist}),o=cb(e);W.info(`agent invocation prepared`,{requestedSessionId:o.requestedSessionId,previousSessionId:o.previousSessionId,inputMode:o.inputMode,hasSlashCommand:!!o.slashCommandSource,resetAction:o.resetCommand?.action,resetShortCircuit:o.resetShortCircuit,transcriptLength:o.transcriptMessage.length,messageForRunLength:o.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let s=o.transcriptMessage,c=!1,l=o.previousSessionId,u=await bb({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;pe(e.dataDir,{messageId:e.messageId,sessionId:d,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,d,$(e))});let f=u.isNewSession,m=u.workspaceDir,h=u.hookContext,g=u.hookRegistry,_=u.pluginContext,v=u.runContext,y=u.runtimeBridge,b=0,x=!1,S=()=>{x||(x=!0,y.dispose())},C=(await F(e.dataDir,d,$(e))).length;if(W.info(`agent run started`,{sessionId:d,requestedSessionId:o.requestedSessionId,previousSessionId:l,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:f,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:f,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),W.info(f?`session created`:`session resumed`,{sessionId:d,requestedSessionId:o.requestedSessionId,previousSessionId:l,workspaceDir:m}),await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:f?`session_created`:`session_resumed`,message:f?`session created`:`session resumed`,details:{requestedSessionId:o.requestedSessionId,previousSessionId:l,workspaceDir:m}}),f&&await p(e.dataDir,gh({sessionId:d,title:cy(s),channel:e.channel}),$(e)),e.pendingGoal){let t=await U(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await rr(e.dataDir,d,{goalId:t.goalId,objective:e.pendingGoal.objective},{storeName:e.sessionStoreName})}o.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(c=await v.persistInitialUserEntry(s));let w=new AbortController;e.abortSignal?.aborted?w.abort():e.abortSignal?.addEventListener(`abort`,()=>w.abort()),h.signal=w.signal,await u.start({resetCommand:o.resetCommand,previousSessionId:l,resetMessage:o.slashCommandSource,startMessage:typeof o.promptInput==`string`?o.promptInput:s});let T=await Kb({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await ub({invocation:o,skills:T.skills,sessionId:d,isNewSession:f,initialUserEntryPersisted:c,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,extensionHost:_.extensionHost});if(D.kind===`completed`)return W.info(`agent run short-circuited`,{sessionId:d,durationMs:Date.now()-n,hasError:!!D.result.error,paused:!!D.result.paused,uiToolPending:!!D.result.uiToolPending,textLength:D.result.text.length}),S(),D.result;let O=D.effectivePrompt;s=D.transcriptMessage;let k=typeof O==`string`?O:s;await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length}}),W.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await Jg({session:{runParams:T.runParamsWithAgentPolicy,sessionId:d,hookRegistry:g,hookContext:h,runContext:v,eventDispatcher:i},runtimeInputs:{contextFiles:T.contextFiles,bootstrapWarnings:T.bootstrapWarnings,skills:T.skills,autoSkillCategories:T.autoSkillCategories,effectivePromptText:k,pluginTools:_.pluginTools,pluginSkillDirs:_.pluginSkillDirs,skillsLoadPaths:T.skillsLoadPaths,presetSystemPrompt:T.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>rx(e,new Zm),createModel:ga,abortSignal:w.signal}}),j=A.agent,M=A.resolvedModelId;y.bindAgent(j),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length}}),W.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=lx(e.timeoutMs),P=!1,ee=N===void 0?void 0:setTimeout(()=>{P=!0,w.abort(),j.abort(),i.dispatchDiagnostic(d,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:N}}),W.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let I=new Jb,L=``,R,te=!1,z=new an;await Ab(e.dataDir,d,z,{storeName:e.sessionStoreName}),w.signal;try{if(Mb(e)){let t=await Nb({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return L=t.text,S(),vy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let t=await v.persistInitialUserEntry(s);te=t,c=t||c;try{await Gn(e.dataDir,d,{storeName:e.sessionStoreName},()=>zr(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof Hn))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await H(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await Nr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof Hn)o=!0;else throw e}let u=!!(o||l&&Wr(l)),p=qr({hookRegistry:g,isGateActive:()=>u}),m=await Vr(e.dataDir,d,O,{storeName:e.sessionStoreName}),_;if(o){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Do not submit goal complete or blocked until the workflow state is repaired by the runtime.`,`</goal_context>`,``].join(`
195
- `);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await Br(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});W.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await u_({agent:j,message:_.prompt,continueFromHistory:!!e.uiToolResume,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,retry:e.llmRetry,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{e&&await E(e);for(let e of t)await E(e)}});p(),L=x.text,I.add(x.inputTokens,x.outputTokens),x.error&&(R=x.error),m.hadObjectiveUpdatedSteering&&!x.error&&await Hr(e.dataDir,d,{storeName:e.sessionStoreName}),await i.dispatchDiagnostic(d,{level:x.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens}});let C={sessionId:d,hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens};x.error?W.warn(`first agent turn completed with error`,C):W.info(`first agent turn completed`,C);let T=await jb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`});T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),W.info(`announce loop started`,{sessionId:d});let D=await gb({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,retry:e.llmRetry,artifactAccumulator:a,appendEntry:E});if(D.text&&(L=D.text),I.add(D.inputTokens,D.outputTokens),D.error&&!R&&(R=D.error),await i.dispatchDiagnostic(d,{level:D.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!D.error,error:D.error,inputTokens:D.inputTokens,outputTokens:D.outputTokens}}),T=await jb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`}),T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Pr()){let n=new Mr;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=kt;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Lr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:z,abortSignal:w.signal,executeTurn:async t=>{let n=await u_({agent:j,message:t,continueFromHistory:!1,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{await Rr(E,e,t)}});I.add(n.inputTokens,n.outputTokens),L=n.text||L,n.error&&!R&&(R=n.error);let r=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:r}},flushAccountingAfterTurn:async()=>{(await jb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),r){let e=await gb({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,artifactAccumulator:a,appendEntry:E});I.add(e.inputTokens,e.outputTokens),e.text&&(L=e.text),e.error&&!R&&(R=e.error)}}do{if(w.signal.aborted)break;if(b++,b>8){i.dispatchDiagnostic(d,{level:`warn`,scope:`runner`,phase:`bridge_cycle_limit`,message:`SessionRuntimeBridge exceeded max cycles (8)`}).catch(()=>{});break}await uy({sessionId:d,result:{sessionId:d,text:L??``,usage:I.snapshot(),durationMs:Date.now()-n,error:R},runParams:e,hookRegistry:g,hookContext:h,eventDispatcher:i});let r=await nx({runtimeBridge:y,agent:A.agent,runtime:A,sessionId:d,channel:e.channel,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,retry:e.llmRetry,appendEntry:E,runParams:e,registry:t});I.add(r.inputTokens,r.outputTokens),r.lastResponseText&&(L=r.lastResponseText),r.error&&!R&&(R=r.error)}while(!w.signal.aborted&&(y.hasPendingMessages()||y.hasPendingCompact()));S();let k={sessionId:d,hasError:!!D.error,error:D.error,inputTokens:D.inputTokens,outputTokens:D.outputTokens};D.error?W.warn(`announce loop completed with error`,k):W.info(`announce loop completed`,k)}catch(t){if(So(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await ot(e.dataDir,o,c,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(o,{type:`hitl_requested`,request:c}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),W.info(`agent paused for HITL`,{sessionId:d,requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let l={...I.snapshot()};return await ix({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:te}),S(),vy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:l,error:void 0,paused:{requestId:c.requestId,kind:c.kind,title:c.title}})}if(Re(t)){let r=t,o=r.request.outputSchema.properties??{};await Db(e.dataDir,d,r.request,$(e)),await i.dispatchProgress(d,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(d,{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(o).length}}),W.info(`agent paused for UI tool input`,{sessionId:d,requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(o).length});let c={...I.snapshot()};return await ix({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:te}),S(),vy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L||``,usage:c,error:void 0,uiToolPending:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchema:r.request.outputSchema,extra:r.request.extra}})}if(P&&ux(t))R=`Run timed out after ${N}ms`;else throw await Cb({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),W.error(`agent run failed`,{sessionId:d,channel:e.channel,isNewSession:f,error:t instanceof Error?t.message:String(t)}),t}finally{ee!==void 0&&clearTimeout(ee);try{await jb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}z.clearActiveGoal(),Ag(d);try{A.processRegistry.disposeAll()}catch{}try{Ve.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let B=I.snapshot();P&&(R=`Run timed out after ${N}ms`),await i.dispatchDiagnostic(d,{level:R?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:B.input,outputTokens:B.output,totalTokens:B.total,hasError:!!R,error:R}});let V={sessionId:d,durationMs:Date.now()-n,inputTokens:B.input,outputTokens:B.output,totalTokens:B.total,hasError:!!R,error:R};return R?W.warn(`agent run completed with error`,V):W.info(`agent run completed`,V),await ix({runtime:A,resolvedModelId:M,usage:B,currentUserEntryCoveredByUsage:te}),await Fv({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:L,usage:B,durationMs:Date.now()-n,error:R}}),vy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),transcriptStartIndex:C,text:L,usage:B,error:R,sessionEndOnly:b>0})}async function ix(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 ax(e){let t=Date.now(),i=new Ra(e),a=cb(e),o=a.transcriptMessage.trim()||`CRON task`,c=ex;W.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...tx(e)});let l=a.requestedSessionId,d=!l;l?(await n(e.dataDir,l,{storeName:c})||(d=!0),await v(e.dataDir,l,{storeName:c})):l=await T(e.dataDir,e.channel,{storeName:c}),d&&await p(e.dataDir,gh({sessionId:l,title:cy(o),channel:e.channel}),{storeName:c});let f=r(e.dataDir,l,{storeName:c});pe(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f});let m={parentSessionId:l,parentDir:f},g=await T(e.dataDir,e.channel,{storeName:ex,subagent:m});await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:g,task:o}),W.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:g,taskLength:o.length,taskPreview:oe(o)});let y={...e,sessionId:g,sessionStoreName:ex,sessionPathScope:{subagent:m},subagentContext:{depth:1,parentSessionId:l}},b,x=`done`;try{b=await rx(y,new Zm),b.error&&(x=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);b={sessionId:g,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:_(e.dataDir,g,{storeName:ex,subagent:m}),toolResultsDir:s(e.dataDir,g,{storeName:ex,subagent:m})}},x=`error`,W.error(`cron child run failed`,{parentSessionId:l,childSessionId:g,error:r})}pe(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f}),await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:g,task:o,status:x}),W.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:g,status:x,durationMs:Date.now()-t,hasError:!!b.error});let C=th({task:o,status:x,result:b.text,error:b.error}),w=new Date().toISOString();await h(e.dataDir,l,{role:`assistant`,content:C,timestamp:w,source:`cron`},{storeName:c});let E={task:o,status:x,content:C,childSessionId:g,createdAt:w};return await S(e.dataDir,l,E,{storeName:c}),await ee(e.dataDir,l,e=>ox(e,8),{storeName:c}),await u(e.dataDir,l,{},{storeName:c}),{...b,sessionId:l,context:{snapshotPath:_(e.dataDir,l,{storeName:c}),toolResultsDir:s(e.dataDir,l,{storeName:c})}}}function ox(e,t){if(t<=0)return e.filter(e=>!sx(e));let n=e.reduce((e,t,n)=>(sx(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!sx(e)||r.has(t))}function sx(e){return`source`in e&&e.source===`cron`}async function cx(e,t){let n=async()=>{if(W.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...tx(e)}),e.channel===`CRON`&&!e.subagentContext)return ax(e);let n=t??new Zm;try{return await rx(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:Sb(t)}),W.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};try{return await(e.onLog?Ee(e.onLog,n):n())}finally{e.onLog||await De()}}function lx(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function ux(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const dx={"AGENTS.md":`---
194
+ `),truncated:!0,originalLength:r.length}}function Hb(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Ub(e,t){let n=t?.maxChars??Ib,r=Math.max(1,t?.totalMaxChars??Math.max(n,Lb)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Hb(`[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}=Vb(a.content??``,a.name,e),l=Hb(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 Wb=`You are a personal assistant running inside AiMax.`;async function Gb(e){try{return{presetSystemPrompt:Vt(await G.readFile(e,`utf-8`)).content.trim()||Wb}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:Wb};throw e}}async function Kb(){return Gb(`/aimax_pvc/system_prompt.md`)}async function qb(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await Bb(t.dataDir),o=[],s=Ub(a,{warn:e=>o.push(e)}),c=await Kb();await i.dispatchDiagnostic(n,{level:o.length>0?`warn`:`info`,scope:`runner`,phase:`bootstrap_loaded`,message:`bootstrap context loaded`,details:{bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length}}),W.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await xp(t.dataDir,r.pluginSkillDirs,l),d=await Ca({dataDir:t.dataDir,projectDir:t.projectDir,systemAgentsDir:t.systemAgentsDir,agentPolicy:t.agentPolicy}),f=d.stats(),p=t.agentPolicy?.activeAgent??d.findPublic(t.agentPolicy?.requestedAgentName);if(t.agentPolicy?.requestedAgentName&&!p)throw Error(`Unknown custom agent: ${t.agentPolicy.requestedAgentName}`);let m={...d,...p?{activeAgent:p}:{},...t.agentPolicy?.requestedAgentName?{requestedAgentName:t.agentPolicy.requestedAgentName}:{}},h={...t,agentPolicy:m};return await i.dispatchDiagnostic(n,{level:`info`,scope:`skill`,phase:`skills_loaded`,message:`skills loaded`,details:{skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length,skills:u.map(e=>({name:e.name,description:e.description,location:e.location}))}}),W.info(`skills loaded`,{sessionId:n,skillCount:u.length,pluginSkillDirCount:r.pluginSkillDirs.length,skillsLoadPathCount:l.length}),await i.dispatchDiagnostic(n,{level:`info`,scope:`runner`,phase:`agents_loaded`,message:`custom agents loaded`,details:{agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,agents:d.availableAgents.map(e=>({name:e.name,description:e.description,source:e.source,sourcePath:e.sourcePath}))}}),W.info(`custom agents loaded`,{sessionId:n,agentCount:f.public,allAgentCount:f.total,internalAgentCount:f.internal,activeAgent:m.activeAgent?.name,requestedAgentName:m.requestedAgentName}),{contextFiles:s,bootstrapWarnings:o,skills:u,autoSkillCategories:await Jb({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function Jb(e){if(!e.enabled)return[];try{let t=await new Xi({dataDir:e.dataDir}).autoSkillCategories();return t.length===0?[]:(await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skills_loaded`,message:`auto-skill categories loaded`,details:{categoryCount:t.length,categories:t.map(e=>({path:e.path,description:e.description}))}}),t)}catch(t){return await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`skill`,phase:`auto_skills_load_failed`,message:`auto-skill categories failed to load`,details:{error:t instanceof Error?t.message:String(t)}}),[]}}var Yb=class{#e=0;#t=0;add(e,t){this.#e+=e,this.#t+=t}snapshot(){return{input:this.#e,output:this.#t,total:this.#e+this.#t}}};const Xb={Inferred:1,Child:2,Own:3};var Zb=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=$b(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,Xb.Own)}addInferred(e){this.add(e,Xb.Inferred)}addChild(e){e&&e.length>0&&this.add(e,Xb.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=Qb(n),r=this.indices.get(e);if(r!==void 0){let e=this.records[r];e&&t>e.priority&&(this.records[r]={record:n,priority:t});continue}this.indices.set(e,this.records.length),this.records.push({record:n,priority:t})}}shouldCollect(e){if(e.kind!==`url`||!this.urlWhitelist)return!0;let t=ex(e.url);return t?this.urlWhitelist.has(t):!1}};function Qb(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function $b(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function ex(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const tx=`crons`;function nx(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:oe(e.message)}}async function rx(e){let t,n=0,r=0,i;if(e.runtimeBridge.hasPendingMessages()){let a=e.runtimeBridge.drainMessages();for(let o of a){let a=await d_({agent:e.agent,message:o,continueFromHistory:!1,sessionId:e.sessionId,channel:e.channel,modelId:e.resolvedModelId,historyMessages:e.runtime.historyMessages,eventDispatcher:e.eventDispatcher,hooks:e.hookRegistry,hookCtx:e.hookContext,abortSignal:e.abortSignal,retry:e.retry,onTurnRecordProduced:async(t,n)=>{t&&await e.appendEntry(t);for(let t of n)await e.appendEntry(t)}});n+=a.inputTokens,r+=a.outputTokens,a.text&&(t=a.text),a.error&&(i=a.error);let s=await _b({agent:e.agent,registry:e.registry,sessionId:e.sessionId,resolvedModelId:e.resolvedModelId,eventDispatcher:e.eventDispatcher,hookRegistry:e.hookRegistry,hookContext:e.hookContext,abortSignal:e.abortSignal,appendEntry:e.appendEntry});n+=s.inputTokens,r+=s.outputTokens,s.text&&(t=s.text),s.error&&!i&&(i=s.error)}}let a=e.runtimeBridge.drainCompactRequest();if(a)try{let t=await $y({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,$(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{apiFormat:e.runParams.llm.apiFormat,baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:a.customInstructions,signal:e.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});t.status===`compacted`&&await e.appendEntry(t.entry),a.onComplete?.(t)}catch(e){a.onError?.(e instanceof Error?e:Error(String(e)))}return{lastResponseText:t,inputTokens:n,outputTokens:r,error:i}}async function ix(e,t){ny();let n=Date.now(),i=new Ra(e),a=new Zb({urlWhitelist:e.artifactsUrlWhitelist}),o=lb(e);W.info(`agent invocation prepared`,{requestedSessionId:o.requestedSessionId,previousSessionId:o.previousSessionId,inputMode:o.inputMode,hasSlashCommand:!!o.slashCommandSource,resetAction:o.resetCommand?.action,resetShortCircuit:o.resetShortCircuit,transcriptLength:o.transcriptMessage.length,messageForRunLength:o.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let s=o.transcriptMessage,c=!1,l=o.previousSessionId,u=await xb({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;pe(e.dataDir,{messageId:e.messageId,sessionId:d,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,d,$(e))});let f=u.isNewSession,m=u.workspaceDir,h=u.hookContext,g=u.hookRegistry,_=u.pluginContext,v=u.runContext,y=u.runtimeBridge,b=0,x=!1,S=()=>{x||(x=!0,y.dispose())},C=(await F(e.dataDir,d,$(e))).length;if(W.info(`agent run started`,{sessionId:d,requestedSessionId:o.requestedSessionId,previousSessionId:l,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:f,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:f,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),W.info(f?`session created`:`session resumed`,{sessionId:d,requestedSessionId:o.requestedSessionId,previousSessionId:l,workspaceDir:m}),await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:f?`session_created`:`session_resumed`,message:f?`session created`:`session resumed`,details:{requestedSessionId:o.requestedSessionId,previousSessionId:l,workspaceDir:m}}),f&&await p(e.dataDir,_h({sessionId:d,title:ly(s),channel:e.channel}),$(e)),e.pendingGoal){let t=await U(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await rr(e.dataDir,d,{goalId:t.goalId,objective:e.pendingGoal.objective},{storeName:e.sessionStoreName})}o.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(c=await v.persistInitialUserEntry(s));let w=new AbortController;e.abortSignal?.aborted?w.abort():e.abortSignal?.addEventListener(`abort`,()=>w.abort()),h.signal=w.signal,await u.start({resetCommand:o.resetCommand,previousSessionId:l,resetMessage:o.slashCommandSource,startMessage:typeof o.promptInput==`string`?o.promptInput:s});let T=await qb({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await db({invocation:o,skills:T.skills,sessionId:d,isNewSession:f,initialUserEntryPersisted:c,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,extensionHost:_.extensionHost});if(D.kind===`completed`)return W.info(`agent run short-circuited`,{sessionId:d,durationMs:Date.now()-n,hasError:!!D.result.error,paused:!!D.result.paused,uiToolPending:!!D.result.uiToolPending,textLength:D.result.text.length}),S(),D.result;let O=D.effectivePrompt;s=D.transcriptMessage;let k=typeof O==`string`?O:s;await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length}}),W.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await Yg({session:{runParams:T.runParamsWithAgentPolicy,sessionId:d,hookRegistry:g,hookContext:h,runContext:v,eventDispatcher:i},runtimeInputs:{contextFiles:T.contextFiles,bootstrapWarnings:T.bootstrapWarnings,skills:T.skills,autoSkillCategories:T.autoSkillCategories,effectivePromptText:k,pluginTools:_.pluginTools,pluginSkillDirs:_.pluginSkillDirs,skillsLoadPaths:T.skillsLoadPaths,presetSystemPrompt:T.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>ix(e,new Qm),createModel:ga,abortSignal:w.signal}}),j=A.agent,M=A.resolvedModelId;y.bindAgent(j),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length}}),W.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=ux(e.timeoutMs),P=!1,ee=N===void 0?void 0:setTimeout(()=>{P=!0,w.abort(),j.abort(),i.dispatchDiagnostic(d,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:N}}),W.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let I=new Yb,L=``,R,te=!1,z=new an;await jb(e.dataDir,d,z,{storeName:e.sessionStoreName}),w.signal;try{if(Nb(e)){let t=await Pb({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return L=t.text,S(),yy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let t=await v.persistInitialUserEntry(s);te=t,c=t||c;try{await Gn(e.dataDir,d,{storeName:e.sessionStoreName},()=>zr(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof Hn))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await H(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await Nr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof Hn)o=!0;else throw e}let u=!!(o||l&&Wr(l)),p=qr({hookRegistry:g,isGateActive:()=>u}),m=await Vr(e.dataDir,d,O,{storeName:e.sessionStoreName}),_;if(o){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Do not submit goal complete or blocked until the workflow state is repaired by the runtime.`,`</goal_context>`,``].join(`
195
+ `);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await Br(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});W.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await d_({agent:j,message:_.prompt,continueFromHistory:!!e.uiToolResume,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,retry:e.llmRetry,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{e&&await E(e);for(let e of t)await E(e)}});p(),L=x.text,I.add(x.inputTokens,x.outputTokens),x.error&&(R=x.error),m.hadObjectiveUpdatedSteering&&!x.error&&await Hr(e.dataDir,d,{storeName:e.sessionStoreName}),await i.dispatchDiagnostic(d,{level:x.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens}});let C={sessionId:d,hasError:!!x.error,error:x.error,inputTokens:x.inputTokens,outputTokens:x.outputTokens};x.error?W.warn(`first agent turn completed with error`,C):W.info(`first agent turn completed`,C);let T=await Mb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`});T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),W.info(`announce loop started`,{sessionId:d});let D=await _b({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,retry:e.llmRetry,artifactAccumulator:a,appendEntry:E});if(D.text&&(L=D.text),I.add(D.inputTokens,D.outputTokens),D.error&&!R&&(R=D.error),await i.dispatchDiagnostic(d,{level:D.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!D.error,error:D.error,inputTokens:D.inputTokens,outputTokens:D.outputTokens}}),T=await Mb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`}),T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),Pr()){let n=new Mr;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=kt;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Lr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:z,abortSignal:w.signal,executeTurn:async t=>{let n=await d_({agent:j,message:t,continueFromHistory:!1,sessionId:d,channel:e.channel,modelId:M,historyMessages:A.historyMessages,eventDispatcher:i,hooks:g,hookCtx:h,abortSignal:w.signal,artifactAccumulator:a,onTurnRecordProduced:async(e,t)=>{await Rr(E,e,t)}});I.add(n.inputTokens,n.outputTokens),L=n.text||L,n.error&&!R&&(R=n.error);let r=n.turnRecords.reduce((e,t)=>e+t.toolResults.length,0);return{text:n.text,inputTokens:n.inputTokens,outputTokens:n.outputTokens,error:n.error,toolResultCount:r}},flushAccountingAfterTurn:async()=>{(await Mb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),r){let e=await _b({agent:j,registry:t,sessionId:d,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,artifactAccumulator:a,appendEntry:E});I.add(e.inputTokens,e.outputTokens),e.text&&(L=e.text),e.error&&!R&&(R=e.error)}}do{if(w.signal.aborted)break;if(b++,b>8){i.dispatchDiagnostic(d,{level:`warn`,scope:`runner`,phase:`bridge_cycle_limit`,message:`SessionRuntimeBridge exceeded max cycles (8)`}).catch(()=>{});break}await dy({sessionId:d,result:{sessionId:d,text:L??``,usage:I.snapshot(),durationMs:Date.now()-n,error:R},runParams:e,hookRegistry:g,hookContext:h,eventDispatcher:i});let r=await rx({runtimeBridge:y,agent:A.agent,runtime:A,sessionId:d,channel:e.channel,resolvedModelId:M,eventDispatcher:i,hookRegistry:g,hookContext:h,abortSignal:w.signal,retry:e.llmRetry,appendEntry:E,runParams:e,registry:t});I.add(r.inputTokens,r.outputTokens),r.lastResponseText&&(L=r.lastResponseText),r.error&&!R&&(R=r.error)}while(!w.signal.aborted&&(y.hasPendingMessages()||y.hasPendingCompact()));S();let k={sessionId:d,hasError:!!D.error,error:D.error,inputTokens:D.inputTokens,outputTokens:D.outputTokens};D.error?W.warn(`announce loop completed with error`,k):W.info(`announce loop completed`,k)}catch(t){if(So(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await ot(e.dataDir,o,c,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(o,{type:`hitl_requested`,request:c}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),W.info(`agent paused for HITL`,{sessionId:d,requestId:c.requestId,kind:c.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let l={...I.snapshot()};return await ax({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:te}),S(),yy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:l,error:void 0,paused:{requestId:c.requestId,kind:c.kind,title:c.title}})}if(Re(t)){let r=t,o=r.request.outputSchema.properties??{};await Ob(e.dataDir,d,r.request,$(e)),await i.dispatchProgress(d,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(d,{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(o).length}}),W.info(`agent paused for UI tool input`,{sessionId:d,requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(o).length});let c={...I.snapshot()};return await ax({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:te}),S(),yy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L||``,usage:c,error:void 0,uiToolPending:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchema:r.request.outputSchema,extra:r.request.extra}})}if(P&&dx(t))R=`Run timed out after ${N}ms`;else throw await wb({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),W.error(`agent run failed`,{sessionId:d,channel:e.channel,isNewSession:f,error:t instanceof Error?t.message:String(t)}),t}finally{ee!==void 0&&clearTimeout(ee);try{await Mb(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}z.clearActiveGoal(),jg(d);try{A.processRegistry.disposeAll()}catch{}try{Ve.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let B=I.snapshot();P&&(R=`Run timed out after ${N}ms`),await i.dispatchDiagnostic(d,{level:R?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:B.input,outputTokens:B.output,totalTokens:B.total,hasError:!!R,error:R}});let V={sessionId:d,durationMs:Date.now()-n,inputTokens:B.input,outputTokens:B.output,totalTokens:B.total,hasError:!!R,error:R};return R?W.warn(`agent run completed with error`,V):W.info(`agent run completed`,V),await ax({runtime:A,resolvedModelId:M,usage:B,currentUserEntryCoveredByUsage:te}),await Iv({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:L,usage:B,durationMs:Date.now()-n,error:R}}),yy({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),transcriptStartIndex:C,text:L,usage:B,error:R,sessionEndOnly:b>0})}async function ax(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 ox(e){let t=Date.now(),i=new Ra(e),a=lb(e),o=a.transcriptMessage.trim()||`CRON task`,c=tx;W.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...nx(e)});let l=a.requestedSessionId,d=!l;l?(await n(e.dataDir,l,{storeName:c})||(d=!0),await v(e.dataDir,l,{storeName:c})):l=await T(e.dataDir,e.channel,{storeName:c}),d&&await p(e.dataDir,_h({sessionId:l,title:ly(o),channel:e.channel}),{storeName:c});let f=r(e.dataDir,l,{storeName:c});pe(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f});let m={parentSessionId:l,parentDir:f},g=await T(e.dataDir,e.channel,{storeName:tx,subagent:m});await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:g,task:o}),W.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:g,taskLength:o.length,taskPreview:oe(o)});let y={...e,sessionId:g,sessionStoreName:tx,sessionPathScope:{subagent:m},subagentContext:{depth:1,parentSessionId:l}},b,x=`done`;try{b=await ix(y,new Qm),b.error&&(x=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);b={sessionId:g,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:_(e.dataDir,g,{storeName:tx,subagent:m}),toolResultsDir:s(e.dataDir,g,{storeName:tx,subagent:m})}},x=`error`,W.error(`cron child run failed`,{parentSessionId:l,childSessionId:g,error:r})}pe(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f}),await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:g,task:o,status:x}),W.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:g,status:x,durationMs:Date.now()-t,hasError:!!b.error});let C=nh({task:o,status:x,result:b.text,error:b.error}),w=new Date().toISOString();await h(e.dataDir,l,{role:`assistant`,content:C,timestamp:w,source:`cron`},{storeName:c});let E={task:o,status:x,content:C,childSessionId:g,createdAt:w};return await S(e.dataDir,l,E,{storeName:c}),await ee(e.dataDir,l,e=>sx(e,8),{storeName:c}),await u(e.dataDir,l,{},{storeName:c}),{...b,sessionId:l,context:{snapshotPath:_(e.dataDir,l,{storeName:c}),toolResultsDir:s(e.dataDir,l,{storeName:c})}}}function sx(e,t){if(t<=0)return e.filter(e=>!cx(e));let n=e.reduce((e,t,n)=>(cx(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!cx(e)||r.has(t))}function cx(e){return`source`in e&&e.source===`cron`}async function lx(e,t){let n=async()=>{if(W.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...nx(e)}),e.channel===`CRON`&&!e.subagentContext)return ox(e);let n=t??new Qm;try{return await ix(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:Cb(t)}),W.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};try{return await(e.onLog?Ee(e.onLog,n):n())}finally{e.onLog||await De()}}function ux(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function dx(e){if(e instanceof Error)return e.name===`AbortError`||e.message===`aborted`;if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`AbortError`||t.message===`aborted`||t.code===`aborted`}const fx={"AGENTS.md":`---
196
196
  title: "AGENTS.md Template"
197
197
  summary: ".aimax template for AGENTS.md"
198
198
  read_when:
@@ -485,7 +485,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
485
485
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
486
486
 
487
487
  Add whatever helps you do your job. This is your cheat sheet.
488
- `},fx=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function px(e,t){try{if(!(await G.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await G.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function mx(e,t,n){try{if(!(await G.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await G.mkdir(K.dirname(e),{recursive:!0});try{await G.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function hx(e){let t=Rb(e);return[e,t,K.join(t,`skills`),K.join(t,`sessions`),K.join(t,`memory`),K.join(e,`workspace`)]}function gx(e){let t=Rb(e);return[...fx.filter(e=>e!==`BOOTSTRAP.md`).map(e=>K.join(t,e)),K.join(t,`MEMORY.md`)]}function _x(e){return K.join(Rb(e),`.bootstrapped`)}async function vx(e){try{return(await G.stat(_x(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function yx(e){let t=_x(e);await G.mkdir(K.dirname(t),{recursive:!0}),await G.writeFile(t,``,{encoding:`utf-8`})}async function bx(e){let t=[],n=[];for(let n of hx(e))try{(await G.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of gx(e))try{(await G.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function xx(e){return(await bx(e)).ready}async function Sx(e){if(await vx(e))return{ready:!0,performedBootstrap:!1};if((await bx(e)).ready)return await yx(e),{ready:!0,performedBootstrap:!1};let t=await Cx(e);return await yx(e),{ready:!0,performedBootstrap:!0,result:t}}async function Cx(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=Rb(e),r=K.join(e,`workspace`),i=K.join(n,`skills`),a=K.join(n,`sessions`),o=K.join(n,`memory`);await px(e,t),await px(n,t),await px(i,t),await px(a,t),await px(o,t),await px(r,t);for(let e of fx){let r=dx[e]??``;await mx(K.join(n,e),r,t)}return await mx(K.join(n,`MEMORY.md`),``,t),t}async function wx(e){let t=K.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await G.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function Tx(e,t){let n=K.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await G.mkdir(K.dirname(n),{recursive:!0}),await G.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Ex(e,t){let n=await wx(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 Dx(e,t=7){let n=await wx(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 Tx(e,n),i}var Ox=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function kx(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function Ax(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await H(t,n,s);if(!l){let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`created`,goal:e}}let u=(await z(t,n,l,s)).trim();if(u!==c){if(!a)throw new Ox(`A different goal already exists for this session. Use --force to replace it.`,kx(u));let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new Ox(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,kx(u));if(a){let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await V(t,n,d,{storeName:o,eventSource:`cli`})}}async function jx(e,t,n,r){let i=await lt(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?jt(i.request)?(await at(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 Mx(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ct(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 jx(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await at(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 Nx={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 Px(e){return e.action===`timeout`?Nx.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?Nx.approval.summary.approved:Nx.approval.summary.denied}function Fx(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Px(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Ix(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 Lx(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 Rx(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
488
+ `},px=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function mx(e,t){try{if(!(await G.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await G.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function hx(e,t,n){try{if(!(await G.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await G.mkdir(K.dirname(e),{recursive:!0});try{await G.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function gx(e){let t=zb(e);return[e,t,K.join(t,`skills`),K.join(t,`sessions`),K.join(t,`memory`),K.join(e,`workspace`)]}function _x(e){let t=zb(e);return[...px.filter(e=>e!==`BOOTSTRAP.md`).map(e=>K.join(t,e)),K.join(t,`MEMORY.md`)]}function vx(e){return K.join(zb(e),`.bootstrapped`)}async function yx(e){try{return(await G.stat(vx(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function bx(e){let t=vx(e);await G.mkdir(K.dirname(t),{recursive:!0}),await G.writeFile(t,``,{encoding:`utf-8`})}async function xx(e){let t=[],n=[];for(let n of gx(e))try{(await G.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of _x(e))try{(await G.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function Sx(e){return(await xx(e)).ready}async function Cx(e){if(await yx(e))return{ready:!0,performedBootstrap:!1};if((await xx(e)).ready)return await bx(e),{ready:!0,performedBootstrap:!1};let t=await wx(e);return await bx(e),{ready:!0,performedBootstrap:!0,result:t}}async function wx(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=zb(e),r=K.join(e,`workspace`),i=K.join(n,`skills`),a=K.join(n,`sessions`),o=K.join(n,`memory`);await mx(e,t),await mx(n,t),await mx(i,t),await mx(a,t),await mx(o,t),await mx(r,t);for(let e of px){let r=fx[e]??``;await hx(K.join(n,e),r,t)}return await hx(K.join(n,`MEMORY.md`),``,t),t}async function Tx(e){let t=K.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await G.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function Ex(e,t){let n=K.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await G.mkdir(K.dirname(n),{recursive:!0}),await G.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Dx(e,t){let n=await Tx(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 Ox(e,t=7){let n=await Tx(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 Ex(e,n),i}var kx=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function Ax(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function jx(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await H(t,n,s);if(!l){let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`created`,goal:e}}let u=(await z(t,n,l,s)).trim();if(u!==c){if(!a)throw new kx(`A different goal already exists for this session. Use --force to replace it.`,Ax(u));let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new kx(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,Ax(u));if(a){let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await rr(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await V(t,n,d,{storeName:o,eventSource:`cli`})}}async function Mx(e,t,n,r){let i=await lt(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?jt(i.request)?(await at(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 Nx(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ct(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 Mx(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await at(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 Px={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 Fx(e){return e.action===`timeout`?Px.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?Px.approval.summary.approved:Px.approval.summary.denied}function Ix(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Fx(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Lx(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 Rx(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 zx(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
489
489
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
490
490
  `)):(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(`
491
- `))}export{Xi as AutoSkillsLoader,Lb as BOOTSTRAP_FILE_NAMES,Fb as BOOTSTRAP_MAX_CHARS,Ib as BOOTSTRAP_TOTAL_MAX_CHARS,cn as CLARIFY_ACCEPTANCE_TEXT,Ur as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,sn as CLARIFY_TASK_TITLE,Mr as ContinuationState,Hn as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,jr as ENV_GOAL_CONTINUATION,wr as FIRST_TURN_GOAL_WORKFLOW_INTRO,Sy as GOAL_MULTILINE_TEMPLATE_EXAMPLE,zn as GOAL_WORKFLOW_STATE_VERSION,an as GoalAccounting,Ox as GoalConflictError,Nx as HITL_MESSAGES,xo as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,Xm as MAX_CHILDREN_PER_SESSION,Ym as MAX_SUBAGENT_DEPTH,Ve as MemoryIndexManager,Ie as PLUGIN_MANIFEST_FILENAME,xe as PLUGIN_MANIFEST_FILENAMES,de as PluginHookRegistry,_e as PluginToolRegistry,_a as SYSTEM_AGENTS_DIR,Zm as SubagentRegistry,se as UiToolPauseSignal,Tt as addAgent,xt as addBinding,ya as agentDirCandidates,Da as agentVisibility,Rb as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,te as appendGoalEvent,Cf as appendRecentToMemory,i as appendSessionFile,Sf as appendToMemory,h as appendTranscriptEntry,Ax as applyCliGoalBeforeRun,Px as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,Ai as autoSkillsDir,Cx as bootstrapMountLayout,ja as buildAgentDelegationPrompt,Ma as buildAgentTaskPrompt,wy as buildAimaxGoalCliHelpExtra,Hb as buildBootstrapContextFiles,Dr as buildBudgetLimitPrompt,Er as buildContinuationPrompt,Tr as buildFirstTurnGoalWorkflowPrompt,kr as buildGoalContextItem,Cy as buildGoalSlashHelpText,Or as buildObjectiveUpdatedPrompt,Rx as buildResumeNarration,Tp as buildSkillsPrompt,th as buildSubagentAnnounceMessage,Yh as buildSystemPrompt,Dx as cleanupOldSubagentRecords,ut as clearPendingHitl,kb as clearPendingUiTool,j as collapseLogPath,Hr as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,Ir as continuationTurnHadMeaningfulOutput,xa as createAgentDefinitionsContext,xh as createAgentTools,_d as createApplyPatchTool,Vm as createAutoSkillCategoriesTool,Hm as createAutoSkillListTool,Um as createAutoSkillSearchTool,Wm as createAutoSkillViewTool,Ji as createAutoSkillsLoader,Qu as createBashTool,ah as createBatchSubagentSpawnTool,Ue as createBuiltinMemoryProvider,Fu as createContextManager,Je as createDefaultMemoryProvider,cd as createEditFileTool,qu as createExecTool,bh as createImageTool,ud as createListDirTool,jf as createMemoryAppendTool,Gf as createMemoryForgetTool,kf as createMemoryGetTool,Uf as createMemoryListTool,Vf as createMemoryLogTool,Df as createMemorySearchTool,qf as createMemoryUpdateTool,Nf as createMemoryWriteTool,ot as createPendingHitl,Db as createPendingUiTool,fe as createPluginProgressEmitter,be as createPluginRuntime,Zu as createProcessTool,id as createReadFileTool,T as createSession,ou as createSessionContextStore,Yf as createSessionSearchTool,kp as createSkillListTool,Ap as createSkillLoadTool,ih as createSubagentSpawnTool,lh as createSubagentsTool,Be as createUiTool,od as createWriteFileTool,N as cronExecutionsPath,ye as defaultUiToolInputSchema,ae as deleteGoal,nr as deleteGoalWorkflow,Tf as deleteMemoryFile,ke as discoverAIMaxPlugins,ob as emitGoalUpdatedProgress,Sx as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,xn as extractWorkflowPlanFromObjective,ka as filterSkillsForAgent,Aa as filterToolsForAgent,Ea as findAgentDefinition,Sp as findSkillByName,on as flushAccounting,Fx as formatApprovalResolution,Ix as formatClarifyResolution,Lx as formatReviewResolution,ry as generateSessionTitle,vt as getAgentConfig,xf as getMemoryLines,Ne as getPluginSystem,Jn as goalArtifactsDir,ne as goalDir,R as goalEventsPath,ie as goalObjectiveMdPath,B as goalPath,qn as goalWorkflowPlanPath,Kn as goalWorkflowStatePath,vx as hasBootstrapSentinel,it as hitlHistoryPath,rr as initializeGoalWorkflow,Te as initializePluginSystem,bx as inspectBootstrapMountLayout,k as inspectSession,qr as installClarifyFirstTurnGate,xx as isBootstrapMountLayoutReady,Gr as isClarifyFirstTurnBlockedTool,Wr as isClarifyWorkflowTask,Pr as isContinuationEnabled,Ar as isGoalContext,So as isHitlPauseSignal,Re as isUiToolPauseSignal,ft as listAgents,Ry as listAvailableSlashCommands,St as listBindings,_f as listMemoryFiles,E as listSessionSummaries,x as listSessions,Ex as listSubagentRunsFromDisk,wa as loadAgentDefinitionsFromDir,wt as loadAgentsConfig,b as loadArtifactOperations,zb as loadBootstrapFiles,m as loadCronExecutionRecords,lt as loadPendingHitl,lt as readPendingHitl,Eb as loadPendingUiTool,Eb as readPendingUiTool,Se as loadPluginManifest,Oe as loadPluginManifestRegistry,Pe as loadPlugins,P as loadSessionContextSnapshot,zs as loadSessionExportSnapshots,I as loadSessionMetadata,wp as loadSkillView,yp as loadSkills,xp as loadSkillsFromDirs,bp as loadSkillsWithPluginDirs,wx as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,F as loadTranscript,Nr as loadWorkflowPromptContext,Lr as maybeContinueGoalIfIdle,pf as memoryDir,f as metadataPath,re as mirrorGoalStatusToSession,pt as normalizeAgentId,we as normalizePluginsConfig,t as normalizeSessionStoreName,Ta as parseAgentDefinition,rt as pendingHitlPath,wb as pendingUiToolPath,Rs as persistSessionExportSnapshots,ve as preloadPluginSystem,Fe as prepareSystemRuntime,Br as prependFirstGoalWorkflowSteeringIfNeeded,Vr as prependObjectiveUpdatedSteeringIfNeeded,mf as primaryMemoryPath,Oa as publicAgentDefinitions,H as readGoal,Qn as readGoalWorkflowState,er as readGoalWorkflowSummary,st as readHitlHistory,vf as readMemoryFile,yf as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,zr as recoverBlockedWorkflowOnUserTurn,Ze as registerEmbeddingProvider,tt as registerMemoryProvider,yt as removeAgent,Et as removeBindings,wn as renderGoalPlanMarkdown,$n as repairGoalWorkflowState,wf as replaceMemoryFile,Xe as resetEmbeddingProviderRegistryForTests,Qe as resetMemoryProviderRegistryForTests,Ca as resolveAgentDefinitionsContext,mt as resolveAgentDir,ht as resolveAgentIdByBinding,Ct as resolveAgentsConfigPath,bt as resolveDefaultAgentId,$e as resolveEmbeddingProvider,z as resolveGoalObjective,tr as resolveGoalToolWorkflowView,Mx as resolveHitlRequest,Mx as resolvePendingHitl,et as resolveMemoryProvider,Ke as resolveMemoryProviderOrDefault,_t as resolveModelFallbacks,gt as resolveModelString,Ob as resolvePendingUiTool,Me as resolvePluginManifestPath,ee as rewriteTranscript,cx as runAgent,dt as saveAgentsConfig,p as saveSessionMetadata,Tx as saveSubagentRegistryToDisk,ba as scanAgentDefinitions,bf as searchMemory,Is as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,Fs as sessionToolsSnapshotPath,e as sessionsDir,Fr as shouldContinueGoal,pp as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,at as transitionHitlStatus,Dt as updateAgent,Ot as updateAgentIdentity,V as updateGoal,u as updateSessionMetadata,Ce as validatePluginsConfig,jx as validateResume,Gn as withGoalWorkflowLock,Xh as wrapToolsWithHooks,U as writeGoal,L as writeSessionFile};
491
+ `))}export{Xi as AutoSkillsLoader,Rb as BOOTSTRAP_FILE_NAMES,Ib as BOOTSTRAP_MAX_CHARS,Lb as BOOTSTRAP_TOTAL_MAX_CHARS,cn as CLARIFY_ACCEPTANCE_TEXT,Ur as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,sn as CLARIFY_TASK_TITLE,Mr as ContinuationState,Hn as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,jr as ENV_GOAL_CONTINUATION,wr as FIRST_TURN_GOAL_WORKFLOW_INTRO,Cy as GOAL_MULTILINE_TEMPLATE_EXAMPLE,zn as GOAL_WORKFLOW_STATE_VERSION,an as GoalAccounting,kx as GoalConflictError,Px as HITL_MESSAGES,xo as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,Zm as MAX_CHILDREN_PER_SESSION,Xm as MAX_SUBAGENT_DEPTH,Ve as MemoryIndexManager,Ie as PLUGIN_MANIFEST_FILENAME,xe as PLUGIN_MANIFEST_FILENAMES,de as PluginHookRegistry,_e as PluginToolRegistry,_a as SYSTEM_AGENTS_DIR,Qm as SubagentRegistry,se as UiToolPauseSignal,Tt as addAgent,xt as addBinding,ya as agentDirCandidates,Da as agentVisibility,zb as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,te as appendGoalEvent,wf as appendRecentToMemory,i as appendSessionFile,Cf as appendToMemory,h as appendTranscriptEntry,jx as applyCliGoalBeforeRun,Fx as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,Ai as autoSkillsDir,wx as bootstrapMountLayout,ja as buildAgentDelegationPrompt,Ma as buildAgentTaskPrompt,Ty as buildAimaxGoalCliHelpExtra,Ub as buildBootstrapContextFiles,Dr as buildBudgetLimitPrompt,Er as buildContinuationPrompt,Tr as buildFirstTurnGoalWorkflowPrompt,kr as buildGoalContextItem,wy as buildGoalSlashHelpText,Or as buildObjectiveUpdatedPrompt,zx as buildResumeNarration,Ep as buildSkillsPrompt,nh as buildSubagentAnnounceMessage,Xh as buildSystemPrompt,Ox as cleanupOldSubagentRecords,ut as clearPendingHitl,Ab as clearPendingUiTool,j as collapseLogPath,Hr as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,Ir as continuationTurnHadMeaningfulOutput,xa as createAgentDefinitionsContext,Sh as createAgentTools,vd as createApplyPatchTool,Hm as createAutoSkillCategoriesTool,Um as createAutoSkillListTool,Wm as createAutoSkillSearchTool,Gm as createAutoSkillViewTool,Ji as createAutoSkillsLoader,$u as createBashTool,oh as createBatchSubagentSpawnTool,Ue as createBuiltinMemoryProvider,Iu as createContextManager,Je as createDefaultMemoryProvider,ld as createEditFileTool,Ju as createExecTool,xh as createImageTool,dd as createListDirTool,Mf as createMemoryAppendTool,Kf as createMemoryForgetTool,Af as createMemoryGetTool,Wf as createMemoryListTool,Hf as createMemoryLogTool,Of as createMemorySearchTool,Jf as createMemoryUpdateTool,Pf as createMemoryWriteTool,ot as createPendingHitl,Ob as createPendingUiTool,fe as createPluginProgressEmitter,be as createPluginRuntime,Qu as createProcessTool,ad as createReadFileTool,T as createSession,su as createSessionContextStore,Xf as createSessionSearchTool,Ap as createSkillListTool,jp as createSkillLoadTool,ah as createSubagentSpawnTool,uh as createSubagentsTool,Be as createUiTool,sd as createWriteFileTool,N as cronExecutionsPath,ye as defaultUiToolInputSchema,ae as deleteGoal,nr as deleteGoalWorkflow,Ef as deleteMemoryFile,ke as discoverAIMaxPlugins,sb as emitGoalUpdatedProgress,Cx as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,xn as extractWorkflowPlanFromObjective,ka as filterSkillsForAgent,Aa as filterToolsForAgent,Ea as findAgentDefinition,Cp as findSkillByName,on as flushAccounting,Ix as formatApprovalResolution,Lx as formatClarifyResolution,Rx as formatReviewResolution,iy as generateSessionTitle,vt as getAgentConfig,Sf as getMemoryLines,Ne as getPluginSystem,Jn as goalArtifactsDir,ne as goalDir,R as goalEventsPath,ie as goalObjectiveMdPath,B as goalPath,qn as goalWorkflowPlanPath,Kn as goalWorkflowStatePath,yx as hasBootstrapSentinel,it as hitlHistoryPath,rr as initializeGoalWorkflow,Te as initializePluginSystem,xx as inspectBootstrapMountLayout,k as inspectSession,qr as installClarifyFirstTurnGate,Sx as isBootstrapMountLayoutReady,Gr as isClarifyFirstTurnBlockedTool,Wr as isClarifyWorkflowTask,Pr as isContinuationEnabled,Ar as isGoalContext,So as isHitlPauseSignal,Re as isUiToolPauseSignal,ft as listAgents,zy as listAvailableSlashCommands,St as listBindings,vf as listMemoryFiles,E as listSessionSummaries,x as listSessions,Dx as listSubagentRunsFromDisk,wa as loadAgentDefinitionsFromDir,wt as loadAgentsConfig,b as loadArtifactOperations,Bb as loadBootstrapFiles,m as loadCronExecutionRecords,lt as loadPendingHitl,lt as readPendingHitl,Db as loadPendingUiTool,Db as readPendingUiTool,Se as loadPluginManifest,Oe as loadPluginManifestRegistry,Pe as loadPlugins,P as loadSessionContextSnapshot,Bs as loadSessionExportSnapshots,I as loadSessionMetadata,Rs as loadSessionToolsSnapshot,Tp as loadSkillView,bp as loadSkills,Sp as loadSkillsFromDirs,xp as loadSkillsWithPluginDirs,Tx as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,F as loadTranscript,Nr as loadWorkflowPromptContext,Lr as maybeContinueGoalIfIdle,mf as memoryDir,f as metadataPath,re as mirrorGoalStatusToSession,pt as normalizeAgentId,we as normalizePluginsConfig,t as normalizeSessionStoreName,Ta as parseAgentDefinition,rt as pendingHitlPath,Tb as pendingUiToolPath,zs as persistSessionExportSnapshots,Ls as persistSessionToolsSnapshot,ve as preloadPluginSystem,Fe as prepareSystemRuntime,Br as prependFirstGoalWorkflowSteeringIfNeeded,Vr as prependObjectiveUpdatedSteeringIfNeeded,hf as primaryMemoryPath,Oa as publicAgentDefinitions,H as readGoal,Qn as readGoalWorkflowState,er as readGoalWorkflowSummary,st as readHitlHistory,yf as readMemoryFile,bf as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,zr as recoverBlockedWorkflowOnUserTurn,Ze as registerEmbeddingProvider,tt as registerMemoryProvider,yt as removeAgent,Et as removeBindings,wn as renderGoalPlanMarkdown,$n as repairGoalWorkflowState,Tf as replaceMemoryFile,Xe as resetEmbeddingProviderRegistryForTests,Qe as resetMemoryProviderRegistryForTests,Ca as resolveAgentDefinitionsContext,mt as resolveAgentDir,ht as resolveAgentIdByBinding,Ct as resolveAgentsConfigPath,bt as resolveDefaultAgentId,$e as resolveEmbeddingProvider,z as resolveGoalObjective,tr as resolveGoalToolWorkflowView,Nx as resolveHitlRequest,Nx as resolvePendingHitl,et as resolveMemoryProvider,Ke as resolveMemoryProviderOrDefault,_t as resolveModelFallbacks,gt as resolveModelString,kb as resolvePendingUiTool,Me as resolvePluginManifestPath,ee as rewriteTranscript,lx as runAgent,dt as saveAgentsConfig,p as saveSessionMetadata,Ex as saveSubagentRegistryToDisk,ba as scanAgentDefinitions,xf as searchMemory,Is as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,Fs as sessionToolsSnapshotPath,e as sessionsDir,Fr as shouldContinueGoal,mp as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,at as transitionHitlStatus,Dt as updateAgent,Ot as updateAgentIdentity,V as updateGoal,u as updateSessionMetadata,Ce as validatePluginsConfig,Mx as validateResume,Gn as withGoalWorkflowLock,Zh as wrapToolsWithHooks,U as writeGoal,L as writeSessionFile};