@gencode/agents 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,161 +1,195 @@
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-CvZsdTZJ.js";import{n as R,t as z}from"./goal-events-BtFriEK5.js";import{c as B,i as V,l as H,n as te,o as ne,r as re,s as U,t as ie,u as W}from"./goal-store-CmMXXTIZ.js";import{A as ae,C as oe,D as G,E as se,F as ce,M as le,N as ue,O as de,P as fe,S as pe,T as me,_ as he,a as ge,b as _e,c as ve,d as ye,f as be,g as xe,h as Se,i as Ce,j as we,k as Te,l as Ee,m as De,n as Oe,o as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe,v as Fe,w as Ie,x as Le,y as Re}from"./system-runtime-DfAhRq2L.js";import{a as ze,c as Be,i as Ve,l as He,o as Ue,r as We,s as Ge,t as Ke,u as qe}from"./default-provider-DchVtHkL.js";import{a as Je,i as Ye,n as Xe,o as Ze,r as Qe,t as $e}from"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";import{t as et}from"./host-BC9sAhdH.js";import{a as tt,i as nt,l as rt,n as it,o as at,r as ot,s as st,t as ct}from"./session-store-BaH2Dvmo.js";import{_ as lt,a as ut,c as dt,d as ft,f as pt,g as mt,h as ht,i as gt,l as _t,m as vt,n as yt,o as bt,p as xt,s as St,t as Ct,u as wt,v as Tt,y as Et}from"./config-DDlWxQf7.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Dt,formatTaskForDisplay as Ot,isHitlExpired as kt,isHitlTool as At}from"@gencode/shared";import K,{readFile as jt}from"node:fs/promises";import q,{join as Mt}from"node:path";import{createHash as Nt,randomBytes as Pt,randomUUID as Ft}from"node:crypto";import It from"node:os";import{spawn as Lt}from"node:child_process";import{TextDecoder as Rt}from"node:util";import zt from"gray-matter";import{Agent as Bt}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as Vt}from"node:async_hooks";import Ht from"node:fs";import Ut from"openai";import{Type as J,calculateCost as Wt,clampThinkingLevel as Gt,createAssistantMessageEventStream as Kt,getEnvApiKey as qt,parseStreamingJson as Jt,registerApiProvider as Yt,registerBuiltInApiProviders as Xt,streamSimple as Zt}from"@earendil-works/pi-ai";import{fileURLToPath as Qt}from"node:url";import{isBinaryFile as $t}from"isbinaryfile";var en=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 tn(e,t,n,r,i){let a=await U(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 H(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const nn=`clarify plan and acceptance`,rn=`补齐后续 task list、每个 task 的验收项和当前下一步`,an={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},on=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function sn(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function cn(e,t){let n=sn(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function ln(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 un(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(an))cn(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?ln(t.steps):[],acceptance:t.acceptance?ln(t.acceptance):[],raw:e.trim()}}function dn(e){let t=e.toLowerCase();return on.some(e=>t.includes(e.toLowerCase()))}function fn(e){return e.some(dn)}function pn(e,t){return{id:e,text:t,required:!0}}function mn(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 hn(e){return mn({id:`task-1`,kind:`clarify`,title:nn,status:`doing`,acceptanceCriteria:[pn(`ac-1`,rn)],updatedAt:e})}function gn(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>pn(`ac-${t+1}`,e)):[pn(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>mn({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[pn(`ac-1`,`完成:${e}`)],updatedAt:n}))}function _n(e){let t=new Date().toISOString(),n=un(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:gn(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&fn(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&fn(ln(n.raw))){let e=ln(n.raw).filter(dn);return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[hn(t)]}}function vn(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function yn(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>vn(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-CvZsdTZJ.js";import{n as R,t as z}from"./goal-events-BtFriEK5.js";import{c as B,i as V,l as H,n as te,o as ne,r as re,s as U,t as ie,u as W}from"./goal-store-CmMXXTIZ.js";import{A as ae,C as oe,D as G,E as se,F as ce,M as le,N as ue,O as de,P as fe,S as pe,T as me,_ as he,a as ge,b as _e,c as ve,d as ye,f as be,g as xe,h as Se,i as Ce,j as we,k as Te,l as Ee,m as De,n as Oe,o as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe,v as Fe,w as Ie,x as Le,y as Re}from"./system-runtime-7UR4nDc0.js";import{a as ze,c as Be,i as Ve,l as He,o as Ue,r as We,s as Ge,t as Ke,u as qe}from"./default-provider-DchVtHkL.js";import{a as Je,i as Ye,n as Xe,o as Ze,r as Qe,t as $e}from"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";import{t as et}from"./host-BC9sAhdH.js";import{a as tt,i as nt,l as rt,n as it,o as at,r as ot,s as st,t as ct}from"./session-store-BaH2Dvmo.js";import{_ as lt,a as ut,c as dt,d as ft,f as pt,g as mt,h as ht,i as gt,l as _t,m as vt,n as yt,o as bt,p as xt,s as St,t as Ct,u as wt,v as Tt,y as Et}from"./config-DDlWxQf7.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Dt,formatTaskForDisplay as Ot,isHitlExpired as kt,isHitlTool as At}from"@gencode/shared";import K,{readFile as jt}from"node:fs/promises";import q,{join as Mt}from"node:path";import{createHash as Nt,randomBytes as Pt,randomUUID as Ft}from"node:crypto";import It from"node:os";import{spawn as Lt}from"node:child_process";import{TextDecoder as Rt}from"node:util";import zt from"gray-matter";import{Agent as Bt}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as Vt}from"node:async_hooks";import Ht from"node:fs";import Ut from"openai";import{Type as J,calculateCost as Wt,clampThinkingLevel as Gt,createAssistantMessageEventStream as Kt,getEnvApiKey as qt,parseStreamingJson as Jt,registerApiProvider as Yt,registerBuiltInApiProviders as Xt,streamSimple as Zt}from"@earendil-works/pi-ai";import{fileURLToPath as Qt}from"node:url";import{isBinaryFile as $t}from"isbinaryfile";var en=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 tn(e,t,n,r,i){let a=await U(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 H(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const nn=`clarify plan and acceptance`,rn=`补齐后续 task list、每个 task 的验收项和当前下一步`,an={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},on=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function sn(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function cn(e,t){let n=sn(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function ln(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 un(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(an))cn(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?ln(t.steps):[],acceptance:t.acceptance?ln(t.acceptance):[],raw:e.trim()}}function dn(e){let t=e.toLowerCase();return on.some(e=>t.includes(e.toLowerCase()))}function fn(e){return e.some(dn)}function pn(e,t){return{id:e,text:t,required:!0}}function mn(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 hn(e){return mn({id:`task-1`,kind:`clarify`,title:nn,status:`doing`,acceptanceCriteria:[pn(`ac-1`,rn)],updatedAt:e})}function gn(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>pn(`ac-${t+1}`,e)):[pn(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>mn({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[pn(`ac-1`,`完成:${e}`)],updatedAt:n}))}function _n(e){let t=new Date().toISOString(),n=un(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:gn(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&fn(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&fn(ln(n.raw))){let e=ln(n.raw).filter(dn);return{interpretation:r,assumptions:i,openQuestions:a,tasks:gn([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[hn(t)]}}function vn(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function yn(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>vn(n.has(e.id),e)),``].join(`
2
2
  `)}function bn(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[yn(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 xn=process.platform===`win32`;function Sn(e){return xn?{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 Cn(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(xn&&typeof e.pid==`number`){let n=[`/pid`,String(e.pid),`/T`];t===`SIGKILL`&&n.push(`/F`);try{Lt(`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 wn=2e5;function Tn(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function En(e,t){let n=e+t;return n.length<=wn?{text:n,truncated:!1}:{text:n.slice(-wn),truncated:!0}}function Dn(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=En(e.output,r);e.output=i.text;let a=En(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function On(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:Tn(e.output),stdoutTail:Tn(e.stdout),stderrTail:Tn(e.stderr),outputTruncated:e.outputTruncated}}function kn(e,t){return t?e.scopeKey===t:!0}function An(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function jn(e){return e?e.split(/\r?\n/):[]}function Mn(e){let t=jn(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=An(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
- `);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 Nn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Pn(){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),Nn(e))};return{start(t){let{file:n,args:r,shell:a}=Sn(t.command),o=Lt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!xn}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:Ft(),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=>Dn(l,`stdout`,e)),o.stderr.on(`data`,e=>Dn(l,`stderr`,e));let u=e=>t=>{Dn(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=An(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,Dn(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Cn(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Cn(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),Dn(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`)})}),On(l)},get(e,t){let n=r(e);return!n||!kn(n,t)?null:On(n)},list(n){return[...e.values(),...t.values()].filter(e=>kn(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>On(e))},async wait(e,t,n){let i=r(e);if(!i||!kn(i,t))return null;if(i.status!==`running`)return On(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||!kn(a,t)?null:On(a)},readLog(e){let t=r(e.sessionId);return!t||!kn(t,e.scopeKey)?null:Mn({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!kn(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||!kn(n,t))return null;if(n.status!==`running`)return On(n);n.status=`killed`,Cn(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Cn(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?On(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Cn(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Cn(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const Fn=1;var In=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},Ln=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},Rn=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 zn=new Map;function Bn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function Vn(e,t,n,r){let i=Bn(e,t,n),a=zn.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});zn.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function Hn(e,t,n){return q.join(te(e,t,n),`state.json`)}function Un(e,t,n){return q.join(te(e,t,n),`plan.md`)}function Wn(e,t,n){return q.join(te(e,t,n),`artifacts`)}async function Gn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${Pt(4).toString(`hex`)}.tmp`;try{await K.writeFile(n,t,`utf-8`),await K.rename(n,e)}finally{await K.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function Kn(e){if(e.version!==1)throw new In(e.version)}function qn(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 Jn(e,t,n){let r=Hn(e,t,n);try{let e=await K.readFile(r,`utf-8`);try{let t=JSON.parse(e);return Kn(t),t}catch(t){throw t instanceof In?t:new Rn(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof Rn||e instanceof In?e:new Rn(`corrupt_goal_workflow_state`,{cause:e})}}async function Yn(e,t,n){let r=Hn(e,t,n),i;try{i=await K.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return Kn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof In)throw e}let a=await U(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await B(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 K.writeFile(s,i,`utf-8`),c=s}catch{}return await $n(e,t,{goalId:a.goalId,objective:o},n),await Dr(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 Xn(e,t,n){let r=await Jn(e,t,n);return r?qn(r):null}async function Zn(e,t,n){let r=await Jn(e,t,n);return r?{goalState:qn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function Qn(e,t,n){let r=Hn(e,t,n),i=Un(e,t,n),a=Wn(e,t,n);await Promise.all([K.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),K.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),K.rm(a,{recursive:!0,force:!0})])}async function $n(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await Qn(e,t,r);let a=_n(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=te(e,t,r);await K.mkdir(l,{recursive:!0}),await Gn(Hn(e,t,r),JSON.stringify(c,null,2));let u=bn(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await Gn(Un(e,t,r),u),c}const er=1048576,tr=/KEY|TOKEN|SECRET|PASSWORD|COOKIE|AUTH/i,nr=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g],rr=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.pdf`]);function ir(e,t,n){return q.join(Wn(e,t,n),`registry.jsonl`)}function ar(e,t,n){return q.join(Wn(e,t,n),`notes`)}function or(e,t,n){return q.join(Wn(e,t,n),`commands`)}function sr(e,t,n){return q.join(Wn(e,t,n),`snapshots`)}function cr(e,t,n){return q.join(te(e,t,n),`plan-meta.json`)}function lr(e){let t=e,n=!1;for(let e of nr)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function ur(e){return`sha256:${Nt(`sha256`).update(e).digest(`hex`)}`}async function dr(e){return ur(await K.readFile(e))}function fr(e,t){let n=q.normalize(e);return t.some(e=>{let t=q.normalize(e);return n===t||n.startsWith(t+q.sep)})}function pr(e){let t=[q.normalize(e.workspaceDir),q.normalize(It.tmpdir())],n=e.projectDir?.trim();n&&t.push(q.normalize(n));let r=q.join(e.dataDir,`workspace`);return t.includes(q.normalize(r))||t.push(q.normalize(r)),t}function mr(e,t){return t?.trim()?q.isAbsolute(t)?q.normalize(t):q.normalize(q.join(e,t)):e}function hr(e,t){return e.byteLength<=t?{data:e,truncated:!1,originalBytes:e.byteLength}:{data:e.subarray(0,t),truncated:!0,originalBytes:e.byteLength}}function gr(e){return`${e}-${Date.now().toString(36)}-${Pt(3).toString(`hex`)}`}async function _r(e,t,n,r){let i=await vr(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${gr(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function vr(e,t,n){let r=ir(e,t,n);try{let e=await K.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 Ln(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function yr(e,t,n,r){let i=ir(e,t,r);await K.mkdir(q.dirname(i),{recursive:!0}),await K.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function br(e,t,n,r){let i=[...new Set(n.filter(e=>e.trim().length>0))];if(i.length===0)return{valid:!1,errors:[{ref:``,code:`unregistered_evidence_ref`,message:`no evidence refs provided`}]};let a=await vr(e,t,r),o=new Map(a.map(e=>[e.id,e])),s=[],c=xr(e,t,r);for(let e of i){let t=o.get(e);if(!t){s.push({ref:e,code:`unregistered_evidence_ref`,message:`evidence ref not registered: ${e}`});continue}if(t.kind===`command`){let n=t.stdoutRef?q.join(c,t.stdoutRef):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`stdout artifact missing for ${e}`});continue}try{let r=await K.readFile(n);if(t.hash&&ur(r)!==t.hash){s.push({ref:e,code:`artifact_integrity_mismatch`,message:`stdout hash mismatch for ${e}`});continue}}catch{s.push({ref:e,code:`missing_artifact_file`,message:`stdout artifact missing for ${e}`});continue}r?.requireCommandSuccess!==!1&&t.exitCode!==0&&s.push({ref:e,code:`command_exit_nonzero`,message:`command evidence exit code ${t.exitCode}`});continue}if(t.kind===`snapshot`){let n=t.snapshotPath?q.join(c,t.snapshotPath):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`snapshot path missing for ${e}`});continue}try{let r=await K.stat(n);if(t.sizeBytes!==void 0&&r.size!==t.sizeBytes){s.push({ref:e,code:`artifact_integrity_mismatch`,message:`snapshot size mismatch for ${e}`});continue}t.hash&&await dr(n)!==t.hash&&s.push({ref:e,code:`artifact_integrity_mismatch`,message:`snapshot hash mismatch for ${e}`})}catch{s.push({ref:e,code:`missing_artifact_file`,message:`snapshot artifact missing for ${e}`})}continue}let n=t.notePath?q.join(c,t.notePath):null;if(!n){s.push({ref:e,code:`missing_artifact_file`,message:`note path missing for ${e}`});continue}try{let r=await K.stat(n);t.contentBytes!==void 0&&r.size!==t.contentBytes&&s.push({ref:e,code:`artifact_integrity_mismatch`,message:`note size mismatch for ${e}`})}catch{s.push({ref:e,code:`missing_artifact_file`,message:`note artifact missing for ${e}`})}}return{valid:s.length===0,errors:s}}function xr(e,t,n){return q.dirname(te(e,t,n))}async function Sr(e,t,n,r){Kn(n),await Gn(Hn(e,t,r),JSON.stringify(n,null,2))}async function Cr(e,t,n){let r=cr(e,t,n);try{let e=await K.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function wr(e,t,n,r){await Gn(cr(e,t,r),JSON.stringify(n,null,2))}async function Tr(e,t,n,r){let i=await Cr(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 wr(e,t,a,r),a}async function Er(e,t,n,r){try{let i=bn(n,await Cr(e,t,r));return await Gn(Un(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 Dr(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 K.mkdir(q.dirname(s),{recursive:!0}),await K.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}function Or(e){let t=e.map(e=>Number.parseInt(e.id.replace(/^task-/,``),10)).filter(e=>Number.isFinite(e));return`task-${(t.length>0?Math.max(...t):0)+1}`}function kr(e,t=[]){let n=t.map(e=>Number.parseInt(e.id.replace(/^ac-/,``),10)).filter(e=>Number.isFinite(e)),r=n.length>0?Math.max(...n):0,i=[];for(let t=0;t<e;t+=1)r+=1,i.push(`ac-${r}`);return i}async function Ar(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 _r(e,t,n.kind,r),a=i.split(`:`)[1]??gr(n.kind),o=ar(e,t,r);await K.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=q.join(ar(e,t,r),`${a}.md`),l=lr(n.content);await K.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 yr(e,t,u,r)}catch{return await K.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}async function jr(e,t,n,r){let i=mr(n.workspaceDir,n.cwd);if(!fr(i,n.allowedRoots))return{error:`cwd_outside_allowed_roots`};let a=Math.min(Math.max(n.timeoutMs??12e4,1),6e5),o=Math.ceil(a/1e3),s=Pn(),c=s.start({command:n.command,cwd:i,baseEnv:n.baseEnv,timeoutSec:o,scopeKey:n.workspaceDir}),l=await s.wait(c.sessionId,n.workspaceDir)??c,u=s.readOutput(l.sessionId,n.workspaceDir),d=Buffer.from(u?.stdout??l.stdoutTail,`utf-8`),f=Buffer.from(u?.stderr??l.stderrTail,`utf-8`),p=hr(d,er),m=hr(f,er),h=lr(p.data.toString(`utf-8`)),g=lr(m.data.toString(`utf-8`)),_=h.redactionIncomplete||g.redactionIncomplete,v=await _r(e,t,`command`,r),y=v.split(`:`)[1]??gr(`command`),b=or(e,t,r);await K.mkdir(b,{recursive:!0});let x=`goal/artifacts/commands/${y}.out.txt`,S=`goal/artifacts/commands/${y}.err.txt`,C=q.join(b,`${y}.out.txt`),w=q.join(b,`${y}.err.txt`);await K.writeFile(C,h.text,`utf-8`),await K.writeFile(w,g.text,`utf-8`);let T=Object.keys({...process.env,...n.baseEnv}).filter(e=>tr.test(e)),E={id:v,kind:`command`,command:lr(n.command).text,cwd:i,exitCode:l.exitCode??1,stdoutRef:x,stderrRef:S,stdoutTruncated:p.truncated,stderrTruncated:m.truncated,stdoutBytes:p.originalBytes,stderrBytes:m.originalBytes,timeoutMs:a,envKeys:T,redactionIncomplete:_,hash:ur(h.text),createdAt:new Date().toISOString()};try{await yr(e,t,E,r)}catch{return await Promise.all([K.unlink(C).catch(()=>{}),K.unlink(w).catch(()=>{})]),{error:`registry_write_failed`}}return{evidenceRef:v,exitCode:l.exitCode??1}}function Mr(e,t){let n=q.normalize(e),r=n.split(q.sep).filter(Boolean);if(r.includes(`.aimax`)||r.includes(`.ssh`)||r.includes(`.gnupg`))return!0;let i=q.normalize(t);return n.startsWith(q.join(i,`.aimax`)+q.sep)||n===q.join(i,`.aimax`)}async function Nr(e,t,n,r){let i=q.isAbsolute(n.path)?q.normalize(n.path):q.normalize(q.join(n.workspaceDir,n.path));if(!fr(i,n.allowedRoots))return{error:`snapshot_path_outside_allowed_roots`};if(Mr(i,e))return{error:`snapshot_sensitive_path_not_allowed`};let a;try{a=await K.stat(i)}catch{return{error:`snapshot_file_not_found`}}if(!a.isFile())return{error:`snapshot_not_a_file`};if(a.size>5242880)return{error:`snapshot_too_large`};let o=q.extname(i).toLowerCase(),s=o.length>0&&rr.has(o),c;try{c=await K.readFile(i)}catch{return{error:`snapshot_read_failed`}}if(!s){let e=lr(c.toString(`utf-8`));c=Buffer.from(e.text,`utf-8`)}else if(!rr.has(o))return{error:`snapshot_binary_type_not_allowed`};let l=await _r(e,t,`snapshot`,r),u=l.split(`:`)[1]??gr(`snapshot`),d=sr(e,t,r);await K.mkdir(d,{recursive:!0});let f=`${u}${o||q.extname(i)}`,p=`goal/artifacts/snapshots/${f}`,m=q.join(d,f);await K.writeFile(m,c);let h={id:l,kind:`snapshot`,summary:n.summary,path:i,hash:ur(c),sizeBytes:c.byteLength,snapshotPath:p,createdAt:new Date().toISOString()};try{await yr(e,t,h,r)}catch{return await K.unlink(m).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:l}}function Pr(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function Fr(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${Pr(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${Pr(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${Pr(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}: ${Pr(n.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${Pr(n)}`)}return t}function Ir(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 only unless you call goal_add_task.`,`- Do not claim task completion in prose; use goal_task_done with evidence refs.`,`- Use only evidenceRef values returned by goal_record_evidence when filling evidenceRefs, acceptanceEvidence, or finalEvidenceRefs.`,`- Natural-language descriptions and file paths are not evidence refs; strings like "goal/state.json ..." must first be registered with a goal_record_* tool.`,`- In goal workflow, use goal_record_evidence(kind="exec") instead of exec for bounded command execution; it records command evidence, while exec output is not registered in the goal evidence registry.`,`- If blocked, use goal_task_blocked with a clear reason and needed input.`,`- Finish the goal with goal_complete (final evidence refs); do NOT call update_goal(status="complete").`,`- Use goal_plan_update for plan interpretation, assumptions, or open questions.`,`- 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===nn)&&t.unshift(`- Current task is "${nn}": explore, clarify, and refine the plan and acceptance criteria.`,`- Do NOT implement deliverables yet; use goal tools to add tasks and criteria before execution work.`),t}function Lr(){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.`,`- Do not call update_goal(status="complete"); V2-lite completion requires goal_complete with evidence refs after workflow initialization.`,`- 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 Rr=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function zr(e,t,n){return Br(e,t,n,{introLine:Rr})}function Br(e,t,n,r){let i=Pr(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>`,...Fr(n),`</workflow>`,``,`Rules:`,...Ir(n)):l.push(`Rules:`,...Lr()),l.push(``,`</goal_context>`),l.join(`
5
- `)}function Vr(e,t){let n=Pr(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=String(e.tokensUsed);return[`<goal_context>`,``,`The token budget for the current thread goal has been exhausted.`,`The goal status has been set to "budget_limited" automatically.`,``,`<objective>`,n,`</objective>`,``,`Token budget: ${r}`,`Tokens used: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Instructions:`,`- Wrap up the current turn soon. Do not start new substantive work.`,`- Summarize progress made, any blockers, and what would be needed next.`,`- Do NOT call update_goal(complete) unless the objective is truly achieved.`,`- The user can increase the budget or resume the goal later via the CLI.`,``,`</goal_context>`].join(`
6
- `)}function Hr(e,t){let n=Pr(t),r=e.tokenBudget===null?`none`:String(e.tokenBudget),i=e.tokenBudget===null?`unbounded`:String(Math.max(0,e.tokenBudget-e.tokensUsed));return[`<goal_context>`,``,`The thread goal objective has been edited by the user.`,`The following objective supersedes any previous thread goal objective.`,`Adjust your work direction accordingly.`,``,`<untrusted_objective>`,n,`</untrusted_objective>`,``,`Token budget: ${r}`,`Tokens remaining: ${i}`,`Time used: ${e.timeUsedSeconds}s`,``,`Do not call update_goal(status="complete"); V2-lite completion must use goal_complete with evidence refs after workflow initialization.`,``,`</goal_context>`].join(`
7
- `)}function Ur(e){return{role:`user`,content:e}}function Wr(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Gr=`AIMAX_GOAL_CONTINUATION`;var Kr=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function qr(e,t,n){let r=await Jn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await Cr(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??[],openQuestions:i.openQuestions??[]}}function Jr(){let e=process.env[Gr];return e===void 0||e===``||e!==`0`}async function Yr(e,t,n,r){if(!Jr()||n.continuationCount>=Dt)return!1;let i=await U(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-BaH2Dvmo.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Xr(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Zr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await Yr(n,r,a,{storeName:i}))return!1;let u=await U(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await B(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await qr(n,r,{storeName:i}),h=Ur(p?Vr(u,f):Br(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Xr(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=Dt){let e=await U(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-CmMXXTIZ.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-BtFriEK5.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 (${Dt}), goal paused`)}}return!0}async function Qr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function $r(e,t,n){let r=await Jn(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 Sr(e,t,c,{storeName:n?.storeName}),await Dr(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await Cr(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await Tr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await Er(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function ei(e,t,n,r){let i=await U(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await qr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=Ur(zr(i,await B(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 ti(e,t,n,r){let i=await U(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Ur(Hr(i,await B(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function ni(e,t,n){(await U(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await H(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const ri=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function ii(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===nn}function ai(e){return ri.has(e)}function oi(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use goal_record_evidence(kind='exec') for bounded command execution that should be recorded as workflow evidence.`,`Use goal_plan_update, goal_add_task, goal_task_done, or goal_repair_workflow_state to refine or recover the plan.`].join(` `):[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use goal workflow tools such as goal_plan_update, goal_add_task, goal_task_done, goal_record_evidence, or goal_repair_workflow_state to refine, record evidence, or recover before executing deliverables directly.`].join(` `)}function si(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())&&ai(n.toolName))return{block:!0,blockReason:oi(n.toolName)}}}),()=>{t=!1}}function ci(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 li(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(_i(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}vi(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 ui(e,t={}){let n=hi(t.limit,`limit`),r=gi(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!vi(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:mi(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function di(e,t){let n=gi(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 fi(e,t=80){let n=gi(e,`totalEntryCount`),r=gi(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function pi(e,t){return e.slice(t.startIndex,t.endIndex)}function mi(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function hi(e,t){return e===void 0?1/0:gi(e,t)}function gi(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function _i(e){return e.role===`assistant`}function vi(e){return e.role===`tool_result`}const yi=24e3;async function bi(e){return Oi({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function xi(e){return Oi({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Si(e){return Oi({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Ci(e){let t=Ii(e),n=await Ti(e),r=await Mi(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:Ei(e.dataDir,e.sessionId,e.sessionOptions)}}function wi(e){return{maxEntries:Li(e?.maxEntries??80,`limits.maxEntries`),maxBytes:Li(e?.maxBytes??yi,`limits.maxBytes`)}}async function Ti(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=ki(await Ai(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 ji({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Ei(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function Di(e,t,n){let r=Ri(e.startIndex,`startIndex`),i=Ri(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 Oi(e){let t=Ii(e.params),n=Di(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=Ni(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:Ei(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function ki(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 Ai(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)Vi(e)&&e.toolResultRef?.sessionId===t&&a.set(Hi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(Hi(e),e);return Array.from(a.values())}async function ji(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(q.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=q.resolve(e.dataDir,e.reference.storagePath);if(!Bi(q.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Bi(q.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([zi(t),zi(n),zi(i)]);if(!Bi(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Bi(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function Mi(e,t){let n=await K.stat(e),r=await K.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:Fi(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function Ni(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=Pi(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 Pi(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:Fi(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function Fi(e){let t=new Rt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function Ii(e){return wi(e.limits)}function Li(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function Ri(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function zi(e){try{return await K.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Ui(e)}`)}}function Bi(e,t){let n=q.relative(e,t);return n===``||!n.startsWith(`..`)&&!q.isAbsolute(n)}function Vi(e){return e.role===`tool_result`}function Hi(e){return`${e.toolCallId}\n${e.storagePath}`}function Ui(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Wi(e){return q.join(e,`.aimax`,`auto-skills`)}function Gi(e){return q.join(e,`categories.json`)}function Ki(e){return q.join(e,`.auto_skills_prompt_snapshot.json`)}const qi=/^[a-z0-9][a-z0-9-]*$/,Ji=/^[a-z0-9][a-z0-9-]*$/;function Yi(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(`\\`)||q.win32.isAbsolute(t)||q.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(!qi.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function Xi(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(`.`)||!Ji.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Zi(e,t){return`auto:${Yi(e)}/${Xi(t)}`}function Qi(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=Yi(n.slice(0,r)),a=Xi(n.slice(r+1));return{skillId:Zi(i,a),categoryPath:i,skillName:a}}function $i(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function ea(e,t,n){let r=q.resolve(e),i=q.resolve(r,...Yi(t).split(`/`),Xi(n));return na(r,i),i}function ta(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||q.win32.isAbsolute(n)||q.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=q.resolve(e),a=q.resolve(i,...r);return na(i,a),a}function na(e,t){let n=q.resolve(e),r=q.resolve(t),i=q.relative(n,r);if(i.startsWith(`..`)||q.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function ra(e){let t=Gi(e),n;try{n=await K.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=Yi(e),r=aa(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 ia(e){return new Map(e.map(e=>[e.path,e]))}function aa(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 oa=32*1024,sa=new Map;function ca(e){return new ua(e)}async function la(e){let t=q.resolve(e);for(let e of Array.from(sa.keys()))e.startsWith(`${t}|`)&&sa.delete(e);await K.rm(Ki(t),{force:!0}).catch(()=>{})}var ua=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=q.resolve(e.rootDir??Wi(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return fa(ia((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Yi(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>pa(e.categoryPath,t)).map(da)}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:ma(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})=>({...da(e),score:t}))}async autoSkillView(e){let t=Qi(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=ta(n.skillDir,e.filePath),r=await Ca(t,this.maxResourceBytes);return{...da(n),status:n.status,content:r,path:Ea(q.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Ea(q.relative(n.skillDir,t))}}let r=await Ca(n.skillFile,this.maxSkillBytes);return{...da(n),status:n.status,content:r,path:Ea(q.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 ha(this.rootDir),i=sa.get(n);if(!e&&i&&ba(i.manifest,r))return i;let a=e?void 0:await va(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return sa.set(n,e),e}let o=await ra(this.rootDir),s=ia(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return sa.set(n,c),await ya(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 ka({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:oa})}async loadEntry(e){try{let t=q.dirname(e),n=Xi(q.basename(t)),r=Ea(q.relative(this.rootDir,t)),i=Yi(q.posix.dirname(r)),a=Zi(i,n),o=q.join(t,`metadata.json`),s=await xa(o);if(s?.skillId&&Qi(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Yi(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=$i(s?.status);return{skillId:a,name:n,description:wa(await Sa(e,oa)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:Ta(s?.tags),relatedSkills:Ta(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}: ${Da(t)}\n`);return}}};function da(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function fa(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function pa(e,t){return t?e===t:!0}function ma(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 ha(e){let t;try{t=await K.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await _a(q.join(e,`categories.json`),`categories`,n),await ga(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function ga(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=q.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await _a(t,`skill`,n),await _a(q.join(e,`metadata.json`),`metadata`,n),await _a(q.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await K.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await ga(t,i,n)}}async function _a(e,t,n){try{let r=await K.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 va(e,t,n){let r;try{r=await K.readFile(Ki(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)||!ba(e.manifest,n)?void 0:e}catch{return}}async function ya(e,t){if(!await Oa(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await K.writeFile(Ki(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function ba(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 xa(e){try{let t=await K.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 Sa(e,t){let n=await K.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 Ca(e,t){if((await K.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return K.readFile(e,`utf-8`)}function wa(e){let t=zt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
8
- `)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function Ta(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Ea(e){return e.split(q.sep).join(`/`)}function Da(e){return e instanceof Error?e.message:String(e)}async function Oa(e){try{return await K.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ka(e){return Nt(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Aa(e,t,n,r){return fe(ce(e.apiFormat)).createModel(e,t,n,r)}const ja=`/aimax/agents`,Ma=/^[a-z]+(?:-[a-z]+)*$/;function Na(e){let t=[{dir:e.systemAgentsDir??ja,source:`system`},{dir:q.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:q.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function Pa(e){let t=new Map;for(let n of Na(e)){let e=await Ra(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function Fa(e={}){let t=e.allAgents??e.availableAgents??[],n=Ha(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Ba(n,e),findAny:e=>Ba(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function Ia(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 La(e){return Ia(e.agentPolicy)?e.agentPolicy:Fa({allAgents:await Pa(e)})}async function Ra(e,t){let n;try{n=await K.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=q.join(e,i.name),a=za(await K.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function za(e,t){let n=zt(e),r=qa(n.data.name)?.trim(),i=qa(n.data.description)?.trim();if(!r||!Ma.test(r)||!i)return;let a=qa(n.data.model)?.trim(),o=qa(n.data.initPrompt)?.trim()??qa(n.data.initialPrompt)?.trim(),s=Ja(n.data.maxTurns),c=Ya(n.data.tools),l=Ya(n.data.disallowedTools),u=Ya(n.data.skills),d=Xa(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 Ba(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Va(e)===`public`))}function Va(e){return e.visibility??`public`}function Ha(e){return e.filter(e=>Va(e)===`public`)}function Ua(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Wa(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Za)):void 0,r=new Set((t.disallowedTools??[]).map(Za));return e.filter(e=>{let t=typeof e.name==`string`?Za(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Ga(e){let t=Ha(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(`
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 Nn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function Pn(){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),Nn(e))};return{start(t){let{file:n,args:r,shell:a}=Sn(t.command),o=Lt(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!xn}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:Ft(),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=>Dn(l,`stdout`,e)),o.stderr.on(`data`,e=>Dn(l,`stderr`,e));let u=e=>t=>{Dn(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=An(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,Dn(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Cn(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Cn(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),Dn(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`)})}),On(l)},get(e,t){let n=r(e);return!n||!kn(n,t)?null:On(n)},list(n){return[...e.values(),...t.values()].filter(e=>kn(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>On(e))},async wait(e,t,n){let i=r(e);if(!i||!kn(i,t))return null;if(i.status!==`running`)return On(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||!kn(a,t)?null:On(a)},readLog(e){let t=r(e.sessionId);return!t||!kn(t,e.scopeKey)?null:Mn({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!kn(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||!kn(n,t))return null;if(n.status!==`running`)return On(n);n.status=`killed`,Cn(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Cn(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?On(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Cn(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Cn(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const Fn=1;var In=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},Ln=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},Rn=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 zn=new Map;function Bn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function Vn(e,t,n,r){let i=Bn(e,t,n),a=zn.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});zn.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function Hn(e,t,n){return q.join(te(e,t,n),`state.json`)}function Un(e,t,n){return q.join(te(e,t,n),`plan.md`)}function Wn(e,t,n){return q.join(te(e,t,n),`artifacts`)}async function Gn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${Pt(4).toString(`hex`)}.tmp`;try{await K.writeFile(n,t,`utf-8`),await K.rename(n,e)}finally{await K.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function Kn(e){if(e.version!==1)throw new In(e.version)}function qn(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 Jn(e,t,n){let r=Hn(e,t,n);try{let e=await K.readFile(r,`utf-8`);try{let t=JSON.parse(e);return Kn(t),t}catch(t){throw t instanceof In?t:new Rn(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof Rn||e instanceof In?e:new Rn(`corrupt_goal_workflow_state`,{cause:e})}}async function Yn(e,t,n){let r=Hn(e,t,n),i;try{i=await K.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return Kn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof In)throw e}let a=await U(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await B(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 K.writeFile(s,i,`utf-8`),c=s}catch{}return await $n(e,t,{goalId:a.goalId,objective:o},n),await mr(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 Xn(e,t,n){let r=await Jn(e,t,n);return r?qn(r):null}async function Zn(e,t,n){let r=await Jn(e,t,n);return r?{goalState:qn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function Qn(e,t,n){let r=Hn(e,t,n),i=Un(e,t,n),a=Wn(e,t,n);await Promise.all([K.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),K.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),K.rm(a,{recursive:!0,force:!0})])}async function $n(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await Qn(e,t,r);let a=_n(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=te(e,t,r);await K.mkdir(l,{recursive:!0}),await Gn(Hn(e,t,r),JSON.stringify(c,null,2));let u=bn(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await Gn(Un(e,t,r),u),c}const er=[/(?: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 tr(e,t,n){return q.join(Wn(e,t,n),`registry.jsonl`)}function nr(e,t,n){return q.join(Wn(e,t,n),`notes`)}function rr(e,t,n){return q.join(te(e,t,n),`plan-meta.json`)}function ir(e){let t=e,n=!1;for(let e of er)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function ar(e){return`${e}-${Date.now().toString(36)}-${Pt(3).toString(`hex`)}`}async function or(e,t,n,r){let i=await sr(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${ar(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function sr(e,t,n){let r=tr(e,t,n);try{let e=await K.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 Ln(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function cr(e,t,n,r){let i=tr(e,t,r);await K.mkdir(q.dirname(i),{recursive:!0}),await K.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function lr(e,t,n,r){Kn(n),await Gn(Hn(e,t,r),JSON.stringify(n,null,2))}async function ur(e,t,n){let r=rr(e,t,n);try{let e=await K.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function dr(e,t,n,r){await Gn(rr(e,t,r),JSON.stringify(n,null,2))}async function fr(e,t,n,r){let i=await ur(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 dr(e,t,a,r),a}async function pr(e,t,n,r){try{let i=bn(n,await ur(e,t,r));return await Gn(Un(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 mr(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 K.mkdir(q.dirname(s),{recursive:!0}),await K.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}async function hr(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 or(e,t,n.kind,r),a=i.split(`:`)[1]??ar(n.kind),o=nr(e,t,r);await K.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=q.join(nr(e,t,r),`${a}.md`),l=ir(n.content);await K.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 cr(e,t,u,r)}catch{return await K.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}function gr(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function _r(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${gr(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${gr(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${gr(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}: ${gr(n.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${gr(n)}`)}return t}function vr(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 }).`,`- 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===nn)&&t.unshift(`- Current task is "${nn}": 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 yr(){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 }).`,`- 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 br=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function xr(e,t,n){return Sr(e,t,n,{introLine:br})}function Sr(e,t,n,r){let i=gr(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>`,..._r(n),`</workflow>`,``,`Rules:`,...vr(n)):l.push(`Rules:`,...yr()),l.push(``,`</goal_context>`),l.join(`
5
+ `)}function Cr(e,t){let n=gr(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
+ `)}function wr(e,t){let n=gr(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 Tr(e){return{role:`user`,content:e}}function Er(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const Dr=`AIMAX_GOAL_CONTINUATION`;var Or=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function kr(e,t,n){let r=await Jn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await ur(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??[],openQuestions:i.openQuestions??[]}}function Ar(){let e=process.env[Dr];return e===void 0||e===``||e!==`0`}async function jr(e,t,n,r){if(!Ar()||n.continuationCount>=Dt)return!1;let i=await U(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-BaH2Dvmo.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function Mr(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function Nr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await jr(n,r,a,{storeName:i}))return!1;let u=await U(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await B(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await kr(n,r,{storeName:i}),h=Tr(p?Cr(u,f):Sr(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=Mr(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=Dt){let e=await U(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-CmMXXTIZ.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-BtFriEK5.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 (${Dt}), goal paused`)}}return!0}async function Pr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function Fr(e,t,n){let r=await Jn(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 lr(e,t,c,{storeName:n?.storeName}),await mr(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await ur(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await fr(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await pr(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Ir(e,t,n,r){let i=await U(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await kr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=Tr(xr(i,await B(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 Lr(e,t,n,r){let i=await U(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=Tr(wr(i,await B(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function Rr(e,t,n){(await U(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await H(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const zr=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Br(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===nn}function Vr(e){return zr.has(e)}function Hr(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 Ur(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())&&Vr(n.toolName))return{block:!0,blockReason:Hr(n.toolName)}}}),()=>{t=!1}}function Wr(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 Gr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if($r(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}ei(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 Kr(e,t={}){let n=Zr(t.limit,`limit`),r=Qr(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!ei(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Xr(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function qr(e,t){let n=Qr(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 Jr(e,t=80){let n=Qr(e,`totalEntryCount`),r=Qr(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Yr(e,t){return e.slice(t.startIndex,t.endIndex)}function Xr(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Zr(e,t){return e===void 0?1/0:Qr(e,t)}function Qr(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function $r(e){return e.role===`assistant`}function ei(e){return e.role===`tool_result`}const ti=24e3;async function ni(e){return ui({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ri(e){return ui({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ii(e){return ui({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function ai(e){let t=vi(e),n=await si(e),r=await mi(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:ci(e.dataDir,e.sessionId,e.sessionOptions)}}function oi(e){return{maxEntries:yi(e?.maxEntries??80,`limits.maxEntries`),maxBytes:yi(e?.maxBytes??ti,`limits.maxBytes`)}}async function si(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=di(await fi(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 pi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function ci(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function li(e,t,n){let r=bi(e.startIndex,`startIndex`),i=bi(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 ui(e){let t=vi(e.params),n=li(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=hi(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:ci(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function di(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 fi(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)Ci(e)&&e.toolResultRef?.sessionId===t&&a.set(wi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(wi(e),e);return Array.from(a.values())}async function pi(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(q.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=q.resolve(e.dataDir,e.reference.storagePath);if(!Si(q.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!Si(q.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([xi(t),xi(n),xi(i)]);if(!Si(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!Si(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function mi(e,t){let n=await K.stat(e),r=await K.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:_i(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function hi(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=gi(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 gi(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:_i(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function _i(e){let t=new Rt(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function vi(e){return oi(e.limits)}function yi(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function bi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function xi(e){try{return await K.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${Ti(e)}`)}}function Si(e,t){let n=q.relative(e,t);return n===``||!n.startsWith(`..`)&&!q.isAbsolute(n)}function Ci(e){return e.role===`tool_result`}function wi(e){return`${e.toolCallId}\n${e.storagePath}`}function Ti(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ei(e){return q.join(e,`.aimax`,`auto-skills`)}function Di(e){return q.join(e,`categories.json`)}function Oi(e){return q.join(e,`.auto_skills_prompt_snapshot.json`)}const ki=/^[a-z0-9][a-z0-9-]*$/,Ai=/^[a-z0-9][a-z0-9-]*$/;function Y(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||q.win32.isAbsolute(t)||q.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(!ki.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function ji(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(`.`)||!Ai.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Mi(e,t){return`auto:${Y(e)}/${ji(t)}`}function Ni(e){let t=e.trim();if(!t.startsWith(`auto:`))throw Error(`Invalid auto-skill id: ${e}`);let n=t.slice(5),r=n.indexOf(`/`);if(r<=0||r===n.length-1)throw Error(`Invalid auto-skill id: ${e}`);if(n.indexOf(`/`,r+1)!==-1)throw Error(`Auto-skill id category path must be a single slug.`);let i=Y(n.slice(0,r)),a=ji(n.slice(r+1));return{skillId:Mi(i,a),categoryPath:i,skillName:a}}function Pi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Fi(e,t,n){let r=q.resolve(e),i=q.resolve(r,...Y(t).split(`/`),ji(n));return Li(r,i),i}function Ii(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||q.win32.isAbsolute(n)||q.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=q.resolve(e),a=q.resolve(i,...r);return Li(i,a),a}function Li(e,t){let n=q.resolve(e),r=q.resolve(t),i=q.relative(n,r);if(i.startsWith(`..`)||q.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Ri(e){let t=Di(e),n;try{n=await K.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=Y(e),r=Bi(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 zi(e){return new Map(e.map(e=>[e.path,e]))}function Bi(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 Vi=32*1024,Hi=new Map;function Ui(e){return new Gi(e)}async function Wi(e){let t=q.resolve(e);for(let e of Array.from(Hi.keys()))e.startsWith(`${t}|`)&&Hi.delete(e);await K.rm(Oi(t),{force:!0}).catch(()=>{})}var Gi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=q.resolve(e.rootDir??Ei(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return qi(zi((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?Y(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Ji(e.categoryPath,t)).map(Ki)}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:Yi(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})=>({...Ki(e),score:t}))}async autoSkillView(e){let t=Ni(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=Ii(n.skillDir,e.filePath),r=await ia(t,this.maxResourceBytes);return{...Ki(n),status:n.status,content:r,path:sa(q.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:sa(q.relative(n.skillDir,t))}}let r=await ia(n.skillFile,this.maxSkillBytes);return{...Ki(n),status:n.status,content:r,path:sa(q.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 Xi(this.rootDir),i=Hi.get(n);if(!e&&i&&ta(i.manifest,r))return i;let a=e?void 0:await $i(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return Hi.set(n,e),e}let o=await Ri(this.rootDir),s=zi(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return Hi.set(n,c),await ea(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 ua({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Vi})}async loadEntry(e){try{let t=q.dirname(e),n=ji(q.basename(t)),r=sa(q.relative(this.rootDir,t)),i=Y(q.posix.dirname(r)),a=Mi(i,n),o=q.join(t,`metadata.json`),s=await na(o);if(s?.skillId&&Ni(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&Y(s.categoryPath)!==i)throw Error(`metadata categoryPath does not match path for ${a}`);if(s?.source&&s.source!==`auto`)throw Error(`metadata source must be auto for ${a}`);let c=Pi(s?.status);return{skillId:a,name:n,description:aa(await ra(e,Vi)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:oa(s?.tags),relatedSkills:oa(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}: ${ca(t)}\n`);return}}};function Ki(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 Ji(e,t){return t?e===t:!0}function Yi(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 Xi(e){let t;try{t=await K.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await Qi(q.join(e,`categories.json`),`categories`,n),await Zi(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Zi(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=q.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await Qi(t,`skill`,n),await Qi(q.join(e,`metadata.json`),`metadata`,n),await Qi(q.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await K.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Zi(t,i,n)}}async function Qi(e,t,n){try{let r=await K.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 $i(e,t,n){let r;try{r=await K.readFile(Oi(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)||!ta(e.manifest,n)?void 0:e}catch{return}}async function ea(e,t){if(!await la(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await K.writeFile(Oi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function ta(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 na(e){try{let t=await K.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 ra(e,t){let n=await K.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 ia(e,t){if((await K.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return K.readFile(e,`utf-8`)}function aa(e){let t=zt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim();for(let e of t.content.split(`
8
+ `)){let t=e.trim();if(t)return(t.match(/^#+\s+(.+)$/)?.[1]??t).trim()}return``}function oa(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function sa(e){return e.split(q.sep).join(`/`)}function ca(e){return e instanceof Error?e.message:String(e)}async function la(e){try{return await K.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ua(e){return Nt(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function da(e,t,n,r){return fe(ce(e.apiFormat)).createModel(e,t,n,r)}const fa=`/aimax/agents`,pa=/^[a-z]+(?:-[a-z]+)*$/;function ma(e){let t=[{dir:e.systemAgentsDir??fa,source:`system`},{dir:q.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:q.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function ha(e){let t=new Map;for(let n of ma(e)){let e=await ya(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function ga(e={}){let t=e.allAgents??e.availableAgents??[],n=Ca(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>xa(n,e),findAny:e=>xa(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function _a(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 va(e){return _a(e.agentPolicy)?e.agentPolicy:ga({allAgents:await ha(e)})}async function ya(e,t){let n;try{n=await K.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=q.join(e,i.name),a=ba(await K.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function ba(e,t){let n=zt(e),r=Oa(n.data.name)?.trim(),i=Oa(n.data.description)?.trim();if(!r||!pa.test(r)||!i)return;let a=Oa(n.data.model)?.trim(),o=Oa(n.data.initPrompt)?.trim()??Oa(n.data.initialPrompt)?.trim(),s=ka(n.data.maxTurns),c=Aa(n.data.tools),l=Aa(n.data.disallowedTools),u=Aa(n.data.skills),d=ja(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 xa(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Sa(e)===`public`))}function Sa(e){return e.visibility??`public`}function Ca(e){return e.filter(e=>Sa(e)===`public`)}function wa(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Ta(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Ma)):void 0,r=new Set((t.disallowedTools??[]).map(Ma));return e.filter(e=>{let t=typeof e.name==`string`?Ma(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Ea(e){let t=Ca(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
- `)}function Ka(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function qa(e){return typeof e==`string`?e:void 0}function Ja(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Ya(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 Xa(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Za(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 Qa=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){G.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 $a=`<aimax_artifacts>`,eo=`</aimax_artifacts>`;function to(e,t={}){let n=[];if(!e.includes($a))return{cleanedText:e,artifacts:[],warnings:n};let r=e,i,a=[];for(;;){let e=r.indexOf($a);if(e===-1)break;let o=r.indexOf(eo,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(...no(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(`
11
- `).trimEnd()}return{cleanedText:r,artifacts:a,warnings:n}}function no(e,t){let{warnings:n,timestamp:r,workspaceDir:i}=t,a;try{a=JSON.parse(e)}catch(e){return n.push(`Failed to parse artifacts JSON: ${e instanceof Error?e.message:String(e)}`),[]}if(!Array.isArray(a))return n.push(`Artifacts block content is not a JSON array`),[];let o=[];for(let e=0;e<a.length;e+=1){let t=a[e];if(!t||typeof t!=`object`){n.push(`Artifact at index ${e} is not an object, skipping`);continue}let s=ro(t,{index:e,warnings:n,timestamp:r,workspaceDir:i});s&&o.push(s)}return o}function ro(e,t){let{index:n,warnings:r,timestamp:i,workspaceDir:a}=t,o=e.kind;if(o!==`file`&&o!==`url`)return r.push(`Artifact at index ${n}: invalid kind "${String(o)}", expected "file" or "url", skipping`),null;if(o===`file`){let t=typeof e.file==`string`?e.file.trim():``;if(!t)return r.push(`Artifact at index ${n}: kind=file but missing file path, skipping`),null;let o=ao(t,a);return o?{kind:`file`,file:o,timestamp:i,label:io(e.label,q.basename(o)||`File artifact`,n,r)}:(r.push(`Artifact at index ${n}: file path must be absolute, skipping`),null)}let s=typeof e.url==`string`?e.url.trim():``;if(!s)return r.push(`Artifact at index ${n}: kind=url but missing url, skipping`),null;let c=so(s)??`URL artifact`;return oo(s)?{kind:`url`,url:s,timestamp:i,label:io(e.label,c,n,r)}:(r.push(`Artifact at index ${n}: url is invalid, skipping`),null)}function io(e,t,n,r){return typeof e==`string`&&e.trim()?e.trim():(r.push(`Artifact at index ${n}: missing or empty label, using fallback label`),t)}function ao(e,t){return q.isAbsolute(e)?q.normalize(e):t?.trim()?q.normalize(q.join(t,e)):null}function oo(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}function so(e){try{return new URL(e).host||void 0}catch{return}}var co=class{buffer=``;suppressing=!1;push(e){if(!e)return``;this.buffer+=e;let t=``;for(;this.buffer.length>0;){if(this.suppressing){let e=this.buffer.indexOf(eo);if(e===-1){let e=lo(this.buffer,eo);return this.buffer=e===0?``:this.buffer.slice(this.buffer.length-e),t}this.buffer=this.buffer.slice(e+18),this.suppressing=!1;continue}let e=this.buffer.indexOf($a);if(e!==-1){t+=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e+17),this.suppressing=!0;continue}let n=lo(this.buffer,$a);if(n===0)return t+=this.buffer,this.buffer=``,t;let r=this.buffer.length-n;return t+=this.buffer.slice(0,r),this.buffer=this.buffer.slice(r),t}return t}finish(){if(this.suppressing)return this.buffer=``,this.suppressing=!1,``;let e=this.buffer;return this.buffer=``,e}reset(){this.buffer=``,this.suppressing=!1}};function lo(e,t){let n=Math.min(e.length,t.length-1);for(let r=n;r>0;--r)if(e.endsWith(t.slice(0,r)))return r;return 0}function uo(e){if(e.isError)return[];let t=(e.now??(()=>new Date))().toISOString(),n=vo(e.result),r=[];if(e.toolName===`write_file`){let i=bo(ko(n.details?.path),e.workspaceDir);return i&&r.push(Co(i,t,Eo(i))),To(r)}if(e.toolName===`edit_file`){let i=Ao(n.details?.occurrences),a=bo(ko(n.details?.path),e.workspaceDir);return a&&i!==0&&r.push(Co(a,t,Eo(a))),To(r)}if(e.toolName===`apply_patch`)return r.push(...fo(n.details,e.workspaceDir,t)),To(r);if(e.toolName===`exec`||e.toolName===`bash`||e.toolName===`process`){if(So(n.details))return[];let i=ko(e.input?.command),a=yo(ko(n.details?.cwd),e.workspaceDir);return r.push(...po({command:i,output:n.content,cwd:a,workspaceDir:e.workspaceDir,timestamp:t})),r}let i=xo(n.content);return i?[wo(i,t,Do(i))]:[]}function fo(e,t,n){let r=e?.summary&&typeof e.summary==`object`?e.summary:void 0;return r?[...Oo(r.added),...Oo(r.modified)].flatMap(e=>{let r=bo(e,t);return r?[Co(r,n,Eo(r))]:[]}):[]}function po(e){let t=[],n=e.cwd??e.workspaceDir,r=r=>{let i=bo(r,n);i&&t.push(Co(i,e.timestamp,Eo(i)))};if(e.command)for(let t of mo(e.command))r(t);for(let t of _o(e.output))r(t);let i=xo(e.output);return i&&t.push(wo(i,e.timestamp,Do(i))),To(t)}function mo(e){let t=ho(e),n=[];for(let e of t.matchAll(/(^|[\s;])(?:>|>>)\s*(?!&)(["']?)([^"'\s;&|<>]+)\2/g))n.push(e[3]??``);for(let e of t.matchAll(/--output(?:=|\s+)(["']?)([^"'\s]+)\1/g))n.push(e[2]??``);return n}function ho(e){let t=[],n=[];for(let r of e.split(/\r?\n/)){if(n.length>0){r.trim()===n[0]&&n.shift();continue}t.push(r),n.push(...go(r))}return t.join(`
12
- `)}function go(e){let t=[];for(let n of e.matchAll(/(^|[^<])<<-?\s*(["']?)([A-Za-z0-9_./-]+)\2/g)){let e=n[3]?.trim();e&&t.push(e)}return t}function _o(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e)continue;let r=e.match(/\bfile\s+(?:generated|created|written|saved)\s*:\s*(.+)$/i)??e.match(/\b(?:generated|created|written|saved)\s+(?:file|to)\s*:\s*(.+)$/i),i=e.match(/文件已生成[::]\s*(.+)$/),a=r?.[1]??i?.[1];a&&t.push(Mo(a.trim()))}return t}function vo(e){if(!e||typeof e!=`object`)return{content:typeof e==`string`?e:``};let t=e,n=t.details&&typeof t.details==`object`?t.details:void 0;return{content:Array.isArray(t.content)?t.content.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>typeof e.text==`string`?e.text:``).join(``):typeof e==`string`?e:``,details:n}}function yo(e,t){return e?.trim()?q.normalize(e):t}function bo(e,t){let n=jo(e?.trim()??``);return!n||n.startsWith(`-`)||n===`/dev/null`||n.startsWith(`/dev/`)||No(n)?null:q.isAbsolute(n)?q.normalize(n):t?.trim()?q.normalize(q.join(t,n)):null}function xo(e){let t=e.trim();return!t||/\s/.test(t)?null:Po(t)?new URL(t).toString():null}function So(e){let t=ko(e?.status);return t===`running`||t===`failed`||t===`killed`||t===`timeout`}function Co(e,t,n){return{kind:`file`,file:e,timestamp:t,label:n}}function wo(e,t,n){return{kind:`url`,url:e,timestamp:t,label:n}}function To(e){let t=new Set,n=[];for(let r of e){let e=r.kind===`file`?`file:${r.file}`:`url:${r.url}`;t.has(e)||(t.add(e),n.push(r))}return n}function Eo(e){return q.basename(e)||`File artifact`}function Do(e){try{return new URL(e).host||`URL artifact`}catch{return`URL artifact`}}function Oo(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function ko(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function Ao(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function jo(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function Mo(e){return e.replace(/[),.;,。;)]+$/u,``)}function No(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)}function Po(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}var Fo=class extends Error{isHitlPause=!0;constructor(e,t,n,r=!1){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.transparentPause=r,this.name=`HitlPauseSignal`}};function Io(e){return!!(e instanceof Fo||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const Lo=new Vt;function Ro(){return{}}async function zo(e,t){return await Lo.run(e,t)}function Bo(e){let t=Lo.getStore();!t||t.signal||(t.signal=e)}function Vo(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function Ho(e,t,n){return{temperature:t?.temperature,maxTokens:t?.maxTokens,signal:t?.signal,apiKey:n||t?.apiKey,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata}}function Uo(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function Wo(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:Uo(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:Uo(e.content,`(tool image omitted: model does not support images)`)}:e)}function Go(e,t,n){let r=new Map,i=Wo(e,t).map(e=>{if(e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return e.redacted?a?e:[]:a&&e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:a?e:{type:`text`,text:e.thinking};if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}};for(let e=0;e<i.length;e+=1){let t=i[e];if(t.role===`assistant`){c();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):(t.role===`user`&&c(),a.push(t))}return c(),a}function Ko(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function qo(e){if(!Ko(e))return null;let t=e,n=Jo(t.message),r=Xo(n?.code)??Xo(t.code),i=Xo(n?.type)??Xo(t.type),a=Xo(n?.message)??Yo(t.error)??Xo(t.message)??`Unknown upstream error`;return{message:Zo(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Qo(r,i),raw:e}}function Jo(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function Yo(e){if(!(!e||typeof e!=`object`))return Xo(e.message)}function Xo(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Zo(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function Qo(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}function $o(e,t=`error`){let n={};es(n,t,e);let r=as(e);return r!==void 0&&es(n,`${t}Cause`,r),n}function es(e,t,n){e[`${t}Type`]=ts(n),e[`${t}Name`]=rs(n,`name`),e[`${t}Message`]=ns(n),e[`${t}Code`]=is(n,`code`),e[`${t}Status`]=is(n,`status`),e[`${t}StatusCode`]=is(n,`statusCode`)}function ts(e){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let t=e.constructor?.name;return typeof t==`string`&&t.length>0?t:void 0}function ns(e){if(e instanceof Error)return os(e.message);if(typeof e==`string`)return os(e);let t=rs(e,`message`);return t?os(t):void 0}function rs(e,t){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function is(e,t){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let n=e[t];return typeof n==`string`&&n.length>0||typeof n==`number`&&Number.isFinite(n)?n:void 0}function as(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function os(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const ss=(e,t,n)=>{let r=Kt();return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0},a=0,o=!1;try{let s=us(e,t,n?.apiKey||qt(e.provider)||``,n?.headers),c=ds(e,t,n);n?.onPayload?.(c);let l=await s.chat.completions.create(c,{signal:n?.signal});r.push({type:`start`,partial:i}),o=!0;let u=null,d=i.content,f=()=>d.length-1,p=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:f(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:f(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=Jt(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:f(),toolCall:e,partial:i}))}};for await(let t of l){a+=1;let n=qo(t);if(n)throw new me({message:n.message,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Wt(e,i.usage)}let o=t.choices?.[0];if(!o||(o.finish_reason&&(i.stopReason=gs(o.finish_reason)),!o.delta))continue;o.delta.content!==null&&o.delta.content!==void 0&&o.delta.content.length>0&&((!u||u.type!==`text`)&&(p(u),u={type:`text`,text:``},i.content.push(u),r.push({type:`text_start`,contentIndex:f(),partial:i})),u.text+=o.delta.content,r.push({type:`text_delta`,contentIndex:f(),delta:o.delta.content,partial:i}));let s=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=o.delta[e];return t!=null&&t.length>0});if(s){(!u||u.type!==`thinking`)&&(p(u),u={type:`thinking`,thinking:``,thinkingSignature:s},i.content.push(u),r.push({type:`thinking_start`,contentIndex:f(),partial:i}));let e=o.delta[s];u.thinking+=e,r.push({type:`thinking_delta`,contentIndex:f(),delta:e,partial:i})}if(o.delta.tool_calls)for(let e of o.delta.tool_calls){(!u||u.type!==`toolCall`||e.id&&u.id!==e.id)&&(p(u),u={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(u),r.push({type:`toolcall_start`,contentIndex:f(),partial:i})),e.id&&(u.id=e.id),e.function?.name&&(u.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,u.partialArgs+=e.function.arguments,u.arguments=Jt(u.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:f(),delta:t,partial:i})}let c=o.delta.reasoning_details;if(c&&Array.isArray(c)){for(let e of c)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(p(u),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(t){G.warn(`openai completions stream failed`,{sessionId:n?.sessionId,modelId:e.id,provider:e.provider,api:e.api,chunkCount:a,streamStarted:o,signalAborted:!!n?.signal?.aborted,stopReason:i.stopReason,...$o(t,`streamError`)});for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`;let s=bs(t);i.errorMessage=s.message,s instanceof me&&Object.assign(i,{errorCode:s.code,statusCode:s.statusCode,statusText:s.statusText,providerMessage:s.providerMessage,providerCode:s.providerCode,providerType:s.providerType,retryable:s.retryable});let c=t?.error?.metadata?.raw;c&&(i.errorMessage+=`\n${c}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},cs=(e,t,n)=>{let r=n?.apiKey||qt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Ho(e,n,r),a=n?.reasoning?Gt(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return ss(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function ls(e,t,n){return ds(e,t,n)}function us(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};return r&&Object.assign(i,r),new Ut({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function ds(e,t,n){let r=vs(e),i=ms(e,t,r);ps(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=hs(t.tools,r):fs(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning||r.thinkingFormat===`qwen`&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:r.thinkingFormat===`qwen-chat-template`&&e.reasoning?a.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0}:r.thinkingFormat===`deepseek`&&e.reasoning&&(a.thinking={type:n?.reasoningEffort?`enabled`:`disabled`},n?.reasoningEffort&&r.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function fs(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function ps(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function ms(e,t,n){let r=[],i=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=Go(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:Vo(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:Vo(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:Vo(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>Vo(e.text)).join(``):a.map(e=>({type:`text`,text:Vo(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
10
+ `)}function Da(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Oa(e){return typeof e==`string`?e:void 0}function ka(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Aa(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 ja(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Ma(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 Na=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){G.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 Pa=`<aimax_artifacts>`,Fa=`</aimax_artifacts>`;function Ia(e,t={}){let n=[];if(!e.includes(Pa))return{cleanedText:e,artifacts:[],warnings:n};let r=e,i,a=[];for(;;){let e=r.indexOf(Pa);if(e===-1)break;let o=r.indexOf(Fa,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(...La(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(`
11
+ `).trimEnd()}return{cleanedText:r,artifacts:a,warnings:n}}function La(e,t){let{warnings:n,timestamp:r,workspaceDir:i}=t,a;try{a=JSON.parse(e)}catch(e){return n.push(`Failed to parse artifacts JSON: ${e instanceof Error?e.message:String(e)}`),[]}if(!Array.isArray(a))return n.push(`Artifacts block content is not a JSON array`),[];let o=[];for(let e=0;e<a.length;e+=1){let t=a[e];if(!t||typeof t!=`object`){n.push(`Artifact at index ${e} is not an object, skipping`);continue}let s=Ra(t,{index:e,warnings:n,timestamp:r,workspaceDir:i});s&&o.push(s)}return o}function Ra(e,t){let{index:n,warnings:r,timestamp:i,workspaceDir:a}=t,o=e.kind;if(o!==`file`&&o!==`url`)return r.push(`Artifact at index ${n}: invalid kind "${String(o)}", expected "file" or "url", skipping`),null;if(o===`file`){let t=typeof e.file==`string`?e.file.trim():``;if(!t)return r.push(`Artifact at index ${n}: kind=file but missing file path, skipping`),null;let o=Ba(t,a);return o?{kind:`file`,file:o,timestamp:i,label:za(e.label,q.basename(o)||`File artifact`,n,r)}:(r.push(`Artifact at index ${n}: file path must be absolute, skipping`),null)}let s=typeof e.url==`string`?e.url.trim():``;if(!s)return r.push(`Artifact at index ${n}: kind=url but missing url, skipping`),null;let c=Ha(s)??`URL artifact`;return Va(s)?{kind:`url`,url:s,timestamp:i,label:za(e.label,c,n,r)}:(r.push(`Artifact at index ${n}: url is invalid, skipping`),null)}function za(e,t,n,r){return typeof e==`string`&&e.trim()?e.trim():(r.push(`Artifact at index ${n}: missing or empty label, using fallback label`),t)}function Ba(e,t){return q.isAbsolute(e)?q.normalize(e):t?.trim()?q.normalize(q.join(t,e)):null}function Va(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}function Ha(e){try{return new URL(e).host||void 0}catch{return}}var Ua=class{buffer=``;suppressing=!1;push(e){if(!e)return``;this.buffer+=e;let t=``;for(;this.buffer.length>0;){if(this.suppressing){let e=this.buffer.indexOf(Fa);if(e===-1){let e=Wa(this.buffer,Fa);return this.buffer=e===0?``:this.buffer.slice(this.buffer.length-e),t}this.buffer=this.buffer.slice(e+18),this.suppressing=!1;continue}let e=this.buffer.indexOf(Pa);if(e!==-1){t+=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e+17),this.suppressing=!0;continue}let n=Wa(this.buffer,Pa);if(n===0)return t+=this.buffer,this.buffer=``,t;let r=this.buffer.length-n;return t+=this.buffer.slice(0,r),this.buffer=this.buffer.slice(r),t}return t}finish(){if(this.suppressing)return this.buffer=``,this.suppressing=!1,``;let e=this.buffer;return this.buffer=``,e}reset(){this.buffer=``,this.suppressing=!1}};function Wa(e,t){let n=Math.min(e.length,t.length-1);for(let r=n;r>0;--r)if(e.endsWith(t.slice(0,r)))return r;return 0}function Ga(e){if(e.isError)return[];let t=(e.now??(()=>new Date))().toISOString(),n=Qa(e.result),r=[];if(e.toolName===`write_file`){let i=eo(lo(n.details?.path),e.workspaceDir);return i&&r.push(ro(i,t,oo(i))),ao(r)}if(e.toolName===`edit_file`){let i=uo(n.details?.occurrences),a=eo(lo(n.details?.path),e.workspaceDir);return a&&i!==0&&r.push(ro(a,t,oo(a))),ao(r)}if(e.toolName===`apply_patch`)return r.push(...Ka(n.details,e.workspaceDir,t)),ao(r);if(e.toolName===`exec`||e.toolName===`bash`||e.toolName===`process`){if(no(n.details))return[];let i=lo(e.input?.command),a=$a(lo(n.details?.cwd),e.workspaceDir);return r.push(...qa({command:i,output:n.content,cwd:a,workspaceDir:e.workspaceDir,timestamp:t})),r}let i=to(n.content);return i?[io(i,t,so(i))]:[]}function Ka(e,t,n){let r=e?.summary&&typeof e.summary==`object`?e.summary:void 0;return r?[...co(r.added),...co(r.modified)].flatMap(e=>{let r=eo(e,t);return r?[ro(r,n,oo(r))]:[]}):[]}function qa(e){let t=[],n=e.cwd??e.workspaceDir,r=r=>{let i=eo(r,n);i&&t.push(ro(i,e.timestamp,oo(i)))};if(e.command)for(let t of Ja(e.command))r(t);for(let t of Za(e.output))r(t);let i=to(e.output);return i&&t.push(io(i,e.timestamp,so(i))),ao(t)}function Ja(e){let t=Ya(e),n=[];for(let e of t.matchAll(/(^|[\s;])(?:>|>>)\s*(?!&)(["']?)([^"'\s;&|<>]+)\2/g))n.push(e[3]??``);for(let e of t.matchAll(/--output(?:=|\s+)(["']?)([^"'\s]+)\1/g))n.push(e[2]??``);return n}function Ya(e){let t=[],n=[];for(let r of e.split(/\r?\n/)){if(n.length>0){r.trim()===n[0]&&n.shift();continue}t.push(r),n.push(...Xa(r))}return t.join(`
12
+ `)}function Xa(e){let t=[];for(let n of e.matchAll(/(^|[^<])<<-?\s*(["']?)([A-Za-z0-9_./-]+)\2/g)){let e=n[3]?.trim();e&&t.push(e)}return t}function Za(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e)continue;let r=e.match(/\bfile\s+(?:generated|created|written|saved)\s*:\s*(.+)$/i)??e.match(/\b(?:generated|created|written|saved)\s+(?:file|to)\s*:\s*(.+)$/i),i=e.match(/文件已生成[::]\s*(.+)$/),a=r?.[1]??i?.[1];a&&t.push(po(a.trim()))}return t}function Qa(e){if(!e||typeof e!=`object`)return{content:typeof e==`string`?e:``};let t=e,n=t.details&&typeof t.details==`object`?t.details:void 0;return{content:Array.isArray(t.content)?t.content.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>typeof e.text==`string`?e.text:``).join(``):typeof e==`string`?e:``,details:n}}function $a(e,t){return e?.trim()?q.normalize(e):t}function eo(e,t){let n=fo(e?.trim()??``);return!n||n.startsWith(`-`)||n===`/dev/null`||n.startsWith(`/dev/`)||mo(n)?null:q.isAbsolute(n)?q.normalize(n):t?.trim()?q.normalize(q.join(t,n)):null}function to(e){let t=e.trim();return!t||/\s/.test(t)?null:ho(t)?new URL(t).toString():null}function no(e){let t=lo(e?.status);return t===`running`||t===`failed`||t===`killed`||t===`timeout`}function ro(e,t,n){return{kind:`file`,file:e,timestamp:t,label:n}}function io(e,t,n){return{kind:`url`,url:e,timestamp:t,label:n}}function ao(e){let t=new Set,n=[];for(let r of e){let e=r.kind===`file`?`file:${r.file}`:`url:${r.url}`;t.has(e)||(t.add(e),n.push(r))}return n}function oo(e){return q.basename(e)||`File artifact`}function so(e){try{return new URL(e).host||`URL artifact`}catch{return`URL artifact`}}function co(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function lo(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function uo(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function fo(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function po(e){return e.replace(/[),.;,。;)]+$/u,``)}function mo(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)}function ho(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}var go=class extends Error{isHitlPause=!0;constructor(e,t,n,r=!1){super(`HITL_PAUSED`),this.request=e,this.checkpoint=t,this.toolContext=n,this.transparentPause=r,this.name=`HitlPauseSignal`}};function _o(e){return!!(e instanceof go||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}const vo=new Vt;function yo(){return{}}async function bo(e,t){return await vo.run(e,t)}function xo(e){let t=vo.getStore();!t||t.signal||(t.signal=e)}function So(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function Co(e,t,n){return{temperature:t?.temperature,maxTokens:t?.maxTokens,signal:t?.signal,apiKey:n||t?.apiKey,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata}}function wo(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function To(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:wo(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:wo(e.content,`(tool image omitted: model does not support images)`)}:e)}function Eo(e,t,n){let r=new Map,i=To(e,t).map(e=>{if(e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return e.redacted?a?e:[]:a&&e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:a?e:{type:`text`,text:e.thinking};if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}};for(let e=0;e<i.length;e+=1){let t=i[e];if(t.role===`assistant`){c();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):(t.role===`user`&&c(),a.push(t))}return c(),a}function Do(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Oo(e){if(!Do(e))return null;let t=e,n=ko(t.message),r=jo(n?.code)??jo(t.code),i=jo(n?.type)??jo(t.type),a=jo(n?.message)??Ao(t.error)??jo(t.message)??`Unknown upstream error`;return{message:Mo(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:No(r,i),raw:e}}function ko(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return null;try{let e=JSON.parse(t);return e&&typeof e==`object`?e:null}catch{return null}}function Ao(e){if(!(!e||typeof e!=`object`))return jo(e.message)}function jo(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Mo(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function No(e,t){let n=Number(e);if(Number.isFinite(n))return n===408||n===409||n===425||n===429||n>=500;let r=t?.toLowerCase();return r===`ratelimiterror`||r===`internalservererror`}function Po(e,t=`error`){let n={};Fo(n,t,e);let r=Bo(e);return r!==void 0&&Fo(n,`${t}Cause`,r),n}function Fo(e,t,n){e[`${t}Type`]=Io(n),e[`${t}Name`]=Ro(n,`name`),e[`${t}Message`]=Lo(n),e[`${t}Code`]=zo(n,`code`),e[`${t}Status`]=zo(n,`status`),e[`${t}StatusCode`]=zo(n,`statusCode`)}function Io(e){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let t=e.constructor?.name;return typeof t==`string`&&t.length>0?t:void 0}function Lo(e){if(e instanceof Error)return Vo(e.message);if(typeof e==`string`)return Vo(e);let t=Ro(e,`message`);return t?Vo(t):void 0}function Ro(e,t){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function zo(e,t){if(!e||typeof e!=`object`&&typeof e!=`function`)return;let n=e[t];return typeof n==`string`&&n.length>0||typeof n==`number`&&Number.isFinite(n)?n:void 0}function Bo(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function Vo(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const Ho=(e,t,n)=>{let r=Kt();return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now(),errorMessage:void 0},a=0,o=!1;try{let s=Go(e,t,n?.apiKey||qt(e.provider)||``,n?.headers),c=Ko(e,t,n);n?.onPayload?.(c);let l=await s.chat.completions.create(c,{signal:n?.signal});r.push({type:`start`,partial:i}),o=!0;let u=null,d=i.content,f=()=>d.length-1,p=e=>{if(e){if(e.type===`text`){r.push({type:`text_end`,contentIndex:f(),content:e.text,partial:i});return}if(e.type===`thinking`){r.push({type:`thinking_end`,contentIndex:f(),content:e.thinking,partial:i});return}e.type===`toolCall`&&(e.arguments=Jt(e.partialArgs),delete e.partialArgs,r.push({type:`toolcall_end`,contentIndex:f(),toolCall:e,partial:i}))}};for await(let t of l){a+=1;let n=Oo(t);if(n)throw new me({message:n.message,code:`stream_payload_error`,providerMessage:n.providerMessage,providerCode:n.providerCode,providerType:n.providerType,retryable:n.retryable,cause:n.raw});if(t.usage){let n=t.usage.prompt_tokens_details?.cached_tokens||0,r=t.usage.completion_tokens_details?.reasoning_tokens||0,a=(t.usage.prompt_tokens||0)-n,o=(t.usage.completion_tokens||0)+r;i.usage={input:a,output:o,cacheRead:n,cacheWrite:0,totalTokens:a+o+n,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Wt(e,i.usage)}let o=t.choices?.[0];if(!o||(o.finish_reason&&(i.stopReason=Zo(o.finish_reason)),!o.delta))continue;o.delta.content!==null&&o.delta.content!==void 0&&o.delta.content.length>0&&((!u||u.type!==`text`)&&(p(u),u={type:`text`,text:``},i.content.push(u),r.push({type:`text_start`,contentIndex:f(),partial:i})),u.text+=o.delta.content,r.push({type:`text_delta`,contentIndex:f(),delta:o.delta.content,partial:i}));let s=[`reasoning_content`,`reasoning`,`reasoning_text`].find(e=>{let t=o.delta[e];return t!=null&&t.length>0});if(s){(!u||u.type!==`thinking`)&&(p(u),u={type:`thinking`,thinking:``,thinkingSignature:s},i.content.push(u),r.push({type:`thinking_start`,contentIndex:f(),partial:i}));let e=o.delta[s];u.thinking+=e,r.push({type:`thinking_delta`,contentIndex:f(),delta:e,partial:i})}if(o.delta.tool_calls)for(let e of o.delta.tool_calls){(!u||u.type!==`toolCall`||e.id&&u.id!==e.id)&&(p(u),u={type:`toolCall`,id:e.id||``,name:e.function?.name||``,arguments:{},partialArgs:``},i.content.push(u),r.push({type:`toolcall_start`,contentIndex:f(),partial:i})),e.id&&(u.id=e.id),e.function?.name&&(u.name=e.function.name);let t=``;e.function?.arguments&&(t=e.function.arguments,u.partialArgs+=e.function.arguments,u.arguments=Jt(u.partialArgs)),r.push({type:`toolcall_delta`,contentIndex:f(),delta:t,partial:i})}let c=o.delta.reasoning_details;if(c&&Array.isArray(c)){for(let e of c)if(e.type===`reasoning.encrypted`&&e.id&&e.data){let t=i.content.find(t=>t.type===`toolCall`&&t.id===e.id);t&&(t.thoughtSignature=JSON.stringify(e))}}}if(p(u),n?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(i.errorMessage??(i.stopReason===`aborted`?`Request was aborted`:`LLM stream ended with stopReason=${i.stopReason}`));r.push({type:`done`,reason:i.stopReason,message:i}),r.end()}catch(t){G.warn(`openai completions stream failed`,{sessionId:n?.sessionId,modelId:e.id,provider:e.provider,api:e.api,chunkCount:a,streamStarted:o,signalAborted:!!n?.signal?.aborted,stopReason:i.stopReason,...Po(t,`streamError`)});for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`;let s=ts(t);i.errorMessage=s.message,s instanceof me&&Object.assign(i,{errorCode:s.code,statusCode:s.statusCode,statusText:s.statusText,providerMessage:s.providerMessage,providerCode:s.providerCode,providerType:s.providerType,retryable:s.retryable});let c=t?.error?.metadata?.raw;c&&(i.errorMessage+=`\n${c}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Uo=(e,t,n)=>{let r=n?.apiKey||qt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Co(e,n,r),a=n?.reasoning?Gt(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return Ho(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function Wo(e,t,n){return Ko(e,t,n)}function Go(e,t,n,r){if(!n){if(!process.env.OPENAI_API_KEY)throw Error(`OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.`);n=process.env.OPENAI_API_KEY}let i={...e.headers};return r&&Object.assign(i,r),new Ut({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Ko(e,t,n){let r=$o(e),i=Yo(e,t,r);Jo(e,i);let a={model:e.id,messages:i,stream:!0};if(r.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),r.supportsStore&&(a.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?a.max_tokens=n.maxTokens:a.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(a.temperature=n.temperature),t.tools?a.tools=Xo(t.tools,r):qo(t.messages)&&(a.tools=[]),n?.toolChoice&&(a.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning||r.thinkingFormat===`qwen`&&e.reasoning?a.enable_thinking=!!n?.reasoningEffort:r.thinkingFormat===`qwen-chat-template`&&e.reasoning?a.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0}:r.thinkingFormat===`deepseek`&&e.reasoning&&(a.thinking={type:n?.reasoningEffort?`enabled`:`disabled`},n?.reasoningEffort&&r.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)),e.baseUrl.includes(`openrouter.ai`)&&e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.baseUrl.includes(`ai-gateway.vercel.sh`)&&e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),a.providerOptions={gateway:e}}}return a}function qo(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function Jo(e,t){if(!(e.provider!==`openrouter`||!e.id.startsWith(`anthropic/`)))for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.role!==`user`&&n.role!==`assistant`)continue;let r=n.content;if(typeof r==`string`){n.content=[{type:`text`,text:r,cache_control:{type:`ephemeral`}}];return}if(Array.isArray(r))for(let e=r.length-1;e>=0;--e){let t=r[e];if(t?.type===`text`){Object.assign(t,{cache_control:{type:`ephemeral`}});return}}}}function Yo(e,t,n){let r=[],i=t=>{if(t.includes(`|`)){let[e]=t.split(`|`);return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,40)}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},a=Eo(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:So(t.systemPrompt)})}let o=null;for(let t=0;t<a.length;t+=1){let i=a[t];if(n.requiresAssistantAfterToolResult&&o===`toolResult`&&i.role===`user`&&r.push({role:`assistant`,content:`I have processed the tool results.`}),i.role===`user`){if(typeof i.content==`string`)r.push({role:`user`,content:So(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:So(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}),n=e.input.includes(`image`)?t:t.filter(e=>e.type!==`image_url`);if(n.length===0)continue;r.push({role:`user`,content:n})}o=i.role;continue}if(i.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=i.content.filter(e=>e.type===`text`&&e.text?.trim().length>0);a.length>0&&(t.content=e.provider===`github-copilot`?a.map(e=>So(e.text)).join(``):a.map(e=>({type:`text`,text:So(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
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:Vo(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 hs(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function gs(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 _s(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 vs(e){let t=_s(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 ys=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function bs(e){return e instanceof Error?!(e instanceof me)&&!xs(e)&&Ss(e)?new me({message:`LLM network request failed: ${e.message}`,code:`network_error`,retryable:!0,cause:e}):e:Ss(e)?new me({message:`LLM network request failed: ${String(e)}`,code:`network_error`,retryable:!0,cause:e}):Error(typeof e==`string`?e:JSON.stringify(e))}function xs(e){return e instanceof Error&&e.name===`AbortError`?!0:(e&&typeof e==`object`?e.code:void 0)===`aborted`}function Ss(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`&&ys.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 Cs=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),ws=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),Ts=[`llmrequesterror`],Es=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function Ds(e){let t=js(e?.maxAttempts,3),n=Ms(e?.initialDelayMs,250),r=Ms(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Os(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function ks(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 As(e){if(Fs(e))return!1;let t=Ns(e),n=Ps(e),r=t?.message??n;if(Gs(r))return!0;if(t?.statusCode!==void 0)return Hs(t.statusCode);if(t?.providerCode!==void 0)return Vs(t.providerCode);let i=Us(r);if(i!==void 0)return Hs(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Cs.has(e))return!0;if(ws.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(Is(e))return!0;let a=Ws(r);return a===void 0?t?.retryable===!0:a}function js(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function Ms(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Ns(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 Ps(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 Fs(e){return Ns(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function Is(e){let t=new Set;for(let n=e;n!=null&&!t.has(n);){t.add(n);let e=Ls(n);if(e!==void 0&&Es.has(e.toLowerCase()))return!0;let r=Rs(n);if(r!==void 0&&zs(r))return!0;n=Bs(n)}return!1}function Ls(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`&&t.length>0?t:void 0}function Rs(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 zs(e){return e.trim().toLowerCase()===`terminated`}function Bs(e){if(!(!e||typeof e!=`object`))return e.cause}function Vs(e){return/^\d+$/.test(e)?Hs(Number(e)):!1}function Hs(e){return e===408||e===409||e===425||e===429||e>=500}function Us(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function Ws(e){if(!e)return;let t=Ks(e);for(let e of ws)if(t.includes(e))return!1;for(let e of Cs)if(t.includes(e))return!0}function Gs(e){if(!e)return!1;let t=Ks(e);return Ts.some(e=>t.includes(e))}function Ks(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const qs=Symbol(`omit-json-value`);function Js(e,t=new WeakSet){if(e===void 0)return qs;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=Js(r,t);e!==qs&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=Js(i,t);e!==qs&&(n[r]=e)}return n}finally{t.delete(e)}}function Ys(e,t,n){return q.join(q.dirname(C(e,t,n)),`session-tools.json`)}function Xs(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:Js(e.parameters??{})}))}async function Zs(e,t,n){let r=await o(Ys(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 Qs(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:Xs(n.tools)},a=`${JSON.stringify(i,null,2)}\n`;await Promise.all([L(C(e,t,r),n.systemPrompt,r?.encryptSessions),L(Ys(e,t,r),a,r?.encryptSessions)])}async function $s(e,t,n){let[r,i]=await Promise.all([g(e,t,n),Zs(e,t,n)]);return{...r?.trim()?{systemPrompt:r}:{},...i&&i.tools.length>0?{tools:i.tools}:{}}}function ec(e){return Math.ceil(e.length/4*1.2)}function tc(e){if(e.role===`user`)return ec(e.content);if(e.role===`assistant`){let t=ec(e.content),n=e.thinking?.trim();n&&(t+=ec(n)),e.errorMessage&&(t+=ec(e.errorMessage));for(let n of e.toolCalls??[])t+=ec(n.name)+ec(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 ec(e.toolName)+ec(t)}function Y(e){return e.reduce((e,t)=>e+tc(t),0)}function nc(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 rc(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 ic=[`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.`],ac={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function oc(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function sc(e,t,n){return e.map(e=>cc(e,t,n))}function cc(e,t,n){let r=new Date(e.timestamp).getTime();if(lc(e))return{role:`user`,content:e.content,timestamp:r};if(uc(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:ac,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:dc(i)}],isError:i.isError,timestamp:r}}function lc(e){return e.role===`user`}function uc(e){return e.role===`assistant`}function dc(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:`,...ic];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
18
- `)}const fc=[`You are a conversation history summariser. Compress the conversation below into a concise summary.`,``,`MUST PRESERVE:`,`- Active tasks and their current status (including batch progress e.g. '5/17 items done')`,`- The last thing the user requested and what was being done about it`,`- Decisions made and their rationale`,`- TODOs, open questions, and constraints`,`- A list of skill names and their locations/paths mentioned or loaded in the compressed content, especially skill_load names and paths`,`- All opaque identifiers exactly as written: UUIDs, hashes, file paths, URLs, IPs, ports (never shorten or reconstruct them)`,``,`Prioritise recent context over older history.`,`Output only the summary text — no preamble, no headings.`].join(`
19
- `);async function pc(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=hc(t,r,i,a),u=gc(a),d,f=se({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:fc,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 mc(500*e)}throw d}function mc(e){return new Promise(t=>setTimeout(t,e))}function hc(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${bc(t.trim(),_c(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=vc(e,t,n,r),o=yc(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: ${bc(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(`, `)}]`:``} ${bc(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?xc(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}]: ${bc(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
21
- `)}function gc(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function _c(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function vc(e,t,n,r){let i=yc(t,n,r);if(!r||r<=0)return 2e3;let a=gc(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=fc.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 yc(e,t,n){if(!n||n<=0)return 1/0;let r=gc(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=fc.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function bc(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function xc(e){let t=Sc(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 Sc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Cc(t);if(e.name||e.path)return e}return{}}function Cc(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 wc(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=tc(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function Tc(e){return Dc((await se({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:Ac,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 Ec(e){return Oc((await se({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:jc,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 Dc(e){let t=kc(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 Oc(e){let t=kc(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 kc(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 Ac=[`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
- `),jc=[`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 Mc(e){let t=Lc(e);if(t)try{let e=await K.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter($c);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function Nc(e){let t=Lc(e);t&&(await K.mkdir(q.dirname(t),{recursive:!0}),await K.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function Pc(e){let t=Rc(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||zc(t,e)){r.push(e);continue}n.push(Vc(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(Vc(r,n.length+1,!0)),n}function Fc(e,t){let n=Rc(t);if(n.length===0)return[];if(!e||e.length===0)return Pc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return Pc(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&&Bc(t,e)){a[a.length-1]=Kc(t,e);continue}t&&(t.status=`closed`),a.push(Vc([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 Ic(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 Lc(e){if(!(!e.dataDir||!e.sessionId))return q.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function Rc(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 zc(e,t){return Yc(Jc(e.user,e.assistant),Jc(t.user,t.assistant))>0}function Bc(e,t){return Yc(Jc(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),Jc(t.user,t.assistant,t.toolNames.join(` `)))>0}function Vc(e,t,n){return Hc(e,t,n)}function Hc(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=Uc(e,o),c=Qc(r?.summary||s),l=qc(r?.keywords,c,o),u=Qc(r?.compressedSummary||Gc(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:So(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 Xo(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function Zo(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 Qo(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 $o(e){let t=Qo(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 es=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function ts(e){return e instanceof Error?!(e instanceof me)&&!ns(e)&&rs(e)?new me({message:`LLM network request failed: ${e.message}`,code:`network_error`,retryable:!0,cause:e}):e:rs(e)?new me({message:`LLM network request failed: ${String(e)}`,code:`network_error`,retryable:!0,cause:e}):Error(typeof e==`string`?e:JSON.stringify(e))}function ns(e){return e instanceof Error&&e.name===`AbortError`?!0:(e&&typeof e==`object`?e.code:void 0)===`aborted`}function rs(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`&&es.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 is=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),as=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),os=[`llmrequesterror`],ss=new Set([`und_err_socket`,`und_err_terminated`,`und_err_aborted`,`econnreset`,`econnrefused`,`epipe`,`etimedout`,`enotfound`,`eai_again`,`ehostunreach`,`enetunreach`]);function cs(e){let t=fs(e?.maxAttempts,3),n=ps(e?.initialDelayMs,250),r=ps(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function ls(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function us(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 ds(e){if(gs(e))return!1;let t=ms(e),n=hs(e),r=t?.message??n;if(Es(r))return!0;if(t?.statusCode!==void 0)return Cs(t.statusCode);if(t?.providerCode!==void 0)return Ss(t.providerCode);let i=ws(r);if(i!==void 0)return Cs(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(is.has(e))return!0;if(as.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(_s(e))return!0;let a=Ts(r);return a===void 0?t?.retryable===!0:a}function fs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function ps(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function ms(e){if(!e||typeof e!=`object`)return null;let t=e;return t.retryable===void 0&&t.statusCode===void 0&&t.code===void 0&&t.providerCode===void 0&&t.providerType===void 0?null:{message:typeof t.message==`string`?t.message:void 0,code:t.code,statusCode:t.statusCode,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable}}function hs(e){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 gs(e){return ms(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function _s(e){let t=new Set;for(let n=e;n!=null&&!t.has(n);){t.add(n);let e=vs(n);if(e!==void 0&&ss.has(e.toLowerCase()))return!0;let r=ys(n);if(r!==void 0&&bs(r))return!0;n=xs(n)}return!1}function vs(e){if(!e||typeof e!=`object`)return;let t=e.code;return typeof t==`string`&&t.length>0?t:void 0}function ys(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 bs(e){return e.trim().toLowerCase()===`terminated`}function xs(e){if(!(!e||typeof e!=`object`))return e.cause}function Ss(e){return/^\d+$/.test(e)?Cs(Number(e)):!1}function Cs(e){return e===408||e===409||e===425||e===429||e>=500}function ws(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function Ts(e){if(!e)return;let t=Ds(e);for(let e of as)if(t.includes(e))return!1;for(let e of is)if(t.includes(e))return!0}function Es(e){if(!e)return!1;let t=Ds(e);return os.some(e=>t.includes(e))}function Ds(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const Os=Symbol(`omit-json-value`);function ks(e,t=new WeakSet){if(e===void 0)return Os;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=ks(r,t);e!==Os&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=ks(i,t);e!==Os&&(n[r]=e)}return n}finally{t.delete(e)}}function As(e,t,n){return q.join(q.dirname(C(e,t,n)),`session-tools.json`)}function js(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:ks(e.parameters??{})}))}async function Ms(e,t,n){let r=await o(As(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 Ns(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:js(n.tools)},a=`${JSON.stringify(i,null,2)}\n`;await Promise.all([L(C(e,t,r),n.systemPrompt,r?.encryptSessions),L(As(e,t,r),a,r?.encryptSessions)])}async function Ps(e,t,n){let[r,i]=await Promise.all([g(e,t,n),Ms(e,t,n)]);return{...r?.trim()?{systemPrompt:r}:{},...i&&i.tools.length>0?{tools:i.tools}:{}}}function Fs(e){return Math.ceil(e.length/4*1.2)}function Is(e){if(e.role===`user`)return Fs(e.content);if(e.role===`assistant`){let t=Fs(e.content),n=e.thinking?.trim();n&&(t+=Fs(n)),e.errorMessage&&(t+=Fs(e.errorMessage));for(let n of e.toolCalls??[])t+=Fs(n.name)+Fs(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 Fs(e.toolName)+Fs(t)}function X(e){return e.reduce((e,t)=>e+Is(t),0)}function Ls(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 Rs(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 zs=[`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.`],Bs={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Vs(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function Hs(e,t,n){return e.map(e=>Us(e,t,n))}function Us(e,t,n){let r=new Date(e.timestamp).getTime();if(Ws(e))return{role:`user`,content:e.content,timestamp:r};if(Gs(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:Bs,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:Ks(i)}],isError:i.isError,timestamp:r}}function Ws(e){return e.role===`user`}function Gs(e){return e.role===`assistant`}function Ks(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:`,...zs];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 Js(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=Xs(t,r,i,a),u=Zs(a),d,f=se({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 Ys(500*e)}throw d}function Ys(e){return new Promise(t=>setTimeout(t,e))}function Xs(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${tc(t.trim(),Qs(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=$s(e,t,n,r),o=ec(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: ${tc(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(`, `)}]`:``} ${tc(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?nc(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}]: ${tc(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
21
+ `)}function Zs(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function Qs(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function $s(e,t,n,r){let i=ec(t,n,r);if(!r||r<=0)return 2e3;let a=Zs(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 ec(e,t,n){if(!n||n<=0)return 1/0;let r=Zs(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 tc(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function nc(e){let t=rc(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 rc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=ic(t);if(e.name||e.path)return e}return{}}function ic(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 ac(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Is(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function oc(e){return cc((await se({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:dc,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 sc(e){return lc((await se({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:fc,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 cc(e){let t=uc(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 lc(e){let t=uc(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 uc(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 dc=[`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
+ `),fc=[`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 pc(e){let t=vc(e);if(t)try{let e=await K.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(Pc);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function mc(e){let t=vc(e);t&&(await K.mkdir(q.dirname(t),{recursive:!0}),await K.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function hc(e){let t=yc(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||bc(t,e)){r.push(e);continue}n.push(Sc(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(Sc(r,n.length+1,!0)),n}function gc(e,t){let n=yc(t);if(n.length===0)return[];if(!e||e.length===0)return hc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return hc(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&&xc(t,e)){a[a.length-1]=Dc(t,e);continue}t&&(t.status=`closed`),a.push(Sc([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 _c(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 vc(e){if(!(!e.dataDir||!e.sessionId))return q.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function yc(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 bc(e,t){return Ac(kc(e.user,e.assistant),kc(t.user,t.assistant))>0}function xc(e,t){return Ac(kc(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),kc(t.user,t.assistant,t.toolNames.join(` `)))>0}function Sc(e,t,n){return Cc(e,t,n)}function Cc(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=wc(e,o),c=Nc(r?.summary||s),l=Oc(r?.keywords,c,o),u=Nc(r?.compressedSummary||Ec(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 Uc(e,t){return Wc(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 Wc(e,t,n){let r=Zc(e,220),i=t?Zc(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return Qc(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function Gc(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return Qc(`Relevant prior segment: ${Zc(e,280)}${n}`)}function Kc(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=Wc(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:Qc(n?.summary||o),compressedSummary:Qc(n?.compressedSummary||Gc(n?.summary||o,r)),keywords:qc(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function qc(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:Xc(t,n)}function Jc(...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 Yc(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Xc(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 Jc(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 Zc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Qc(e){return e.replace(/\s+/g,` `).trim()}function $c(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 el(e){let t=il(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:al(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 tl(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function nl(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:rl(i.compressedSummary),timestamp:e.timestamp})}return r}function rl(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function il(...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 al(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=il(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 ol=`Xenova/bge-small-zh-v1.5`;let sl,cl;const ll=new Map;async function ul(e,t){if(e.length===0)return G.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=hl(t),i=r.path;G.info(`topic segmentation embedding started`,{provider:`transformers`,model:ol,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await pl({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=ll.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);ll.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return G.info(`topic segmentation embedding completed`,{provider:`transformers`,model:ol,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 G.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:ol,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function dl(e,t){let[n]=await ul([e],t);return n??[]}function fl(){return ol}async function pl(e){let t=hl(e).path;return(!sl||cl!==t)&&(cl=t,sl=ml(t)),sl}async function ml(e){let t=Date.now();G.info(`topic segmentation embedding extractor load started`,{model:ol,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`,ol,{dtype:`q8`});return G.info(`topic segmentation embedding extractor load completed`,{model:ol,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw G.warn(`topic segmentation embedding extractor load failed`,{model:ol,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function hl(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=q.dirname(Qt(import.meta.url)),i=q.resolve(r,`../../../../../model`);if(Ht.existsSync(i))return{path:i,source:`repo_candidate`};let a=q.resolve(process.cwd(),`model`);return Ht.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const gl=`topic_segments_vec`,_l=`topic_segments_meta`,vl=`topic_segment_embedding_cache`;async function yl(e){let t=Date.now(),n=xl(e);if(!n){G.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}G.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await K.mkdir(q.dirname(n),{recursive:!0});let r=Ge(n,{allowExtension:!0});try{let i=await Cl(r);G.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 ${_l}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=fl(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=He(Sl(e));return o.get(e.segmentId)!==t});G.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 ul(l.map(e=>Sl(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=Sl(t),n=He(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:Ol(r,t.segmentId);El(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(Dl(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(Tl(r,i,o.length),r.prepare(`DELETE FROM ${gl} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${gl} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,Pl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${gl} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${_l} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${vl} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${gl} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),G.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 G.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 bl(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return G.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=xl(e);if(!n)return G.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 K.access(n)}catch{return G.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}G.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await jl(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return G.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=Ge(n,{allowExtension:!0});try{let a=await Cl(i),o=fl(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?kl(i,o,r,e.limit):Al(i,o,r,e.limit);return G.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 G.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 xl(e){if(!(!e.dataDir||!e.sessionId))return q.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function Sl(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
29
- `)}async function Cl(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${_l} (\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 ${vl} (\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_${_l}_hash ON ${_l}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${vl}_hash ON ${vl}(content_hash)`),{vectorAvailable:(await Be({db:e})).ok,vectorDims:wl(e)}}function wl(e){let t=e.prepare(`SELECT dims FROM ${vl} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function Tl(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${gl}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${gl} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function El(e,t){e.prepare(`INSERT INTO ${_l} (\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 Dl(e,t){e.prepare(`INSERT INTO ${vl} (\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 Ol(e,t){let n=e.prepare(`SELECT embedding FROM ${vl} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function kl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${gl} v\n JOIN ${_l} 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(Pl(n),t,Pl(n),r)}function Al(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${vl} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:Nl(n,Ml(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function jl(e,t){try{return await dl(e,t)}catch(e){return G.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function Ml(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Nl(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 Pl(e){return Buffer.from(new Float32Array(e).buffer)}const Fl=8e3,Il=new Map;function Ll(e){return{enabled:e?.enabled!==!1,embeddingModelDir:$l(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 Rl(e){let t=Wl(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(Jl(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?nl({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function zl(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=eu(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:nu(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 Bl(e){let t=Ll(e.config),n=()=>au({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){G.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){G.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){G.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=Wl(e.entries),i=Y(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){G.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>Gl(e,t)),o=e.llm.flashModel||e.llm.model,s=await Vl({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();G.info(`topic segmentation classify started`,au({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=ql({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=Rl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=Kl({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:Y(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await Xl(e,g),G.info(`topic segmentation classify succeeded`,{...au({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 Vl(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await Hl({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 bl({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=el({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=su(l,e.config.maxShortlistSegments),d=Ul({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:Fl});if(d&&pu({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await gu({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=tl({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await cu({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:Fl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await Nc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),_u({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=fu(a,l.selectedCandidates),d=zl({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 Hl(e){G.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await Mc(e);if(!t){let t=Pc(e.entries);if(t.length===0){G.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await Nc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),_u({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),G.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}G.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=Fc(t,e.entries);return n.length>0&&(await Nc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),_u({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),G.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function Ul(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 Wl(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 Gl(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}iu(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:Zl(e.user,t.maxCandidateUserChars),assistant:n?Zl((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function Kl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:Zl(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 ql(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=eu(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:nu(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 Jl(e,t){let n=t?.assistant??Yl(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:Ql(t?.user??e.user,50),assistantPreview:n?Ql(n,50):void 0}}function Yl(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 Xl(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await K.mkdir(n,{recursive:!0}),await K.appendFile(q.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function Zl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Ql(e,t){return[...e].slice(0,t).join(``)}function $l(e){return e?.trim()||void 0}function eu(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function tu(e){return[...eu(e)].slice(0,8)}function nu(e,t,n,r){let i=ru(e,eu(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function ru(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function iu(e){return e.role===`tool_result`}function au(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:ou(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 ou(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function su(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 cu(e){if(!lu(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=uu(du(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=Ul({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await Ec({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??tu(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?Ic(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function lu(e){let t=e.selectedSegments.filter(e=>!e.forced);return mu(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:hu(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function uu(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 du(e,t,n){let r=Math.max(n.length,1),i=eu(t);return e.map(e=>({candidate:e,score:nu(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function fu(...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 pu(e){if(e.retrieved.length<2||!mu(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 mu(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function hu(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 gu(e){try{let t=await Tc({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 _u(e){let t=vu(e);if(!t||Il.has(t)){G.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}G.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=yl(e).catch(t=>{G.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(()=>{Il.delete(t)});Il.set(t,n)}function vu(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 yu=[`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 bu(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 Tu(t);for(let e of p.readStates)n.set(xu(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 K.mkdir(q.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=xu(e,t,r),a=n.get(i);if(!a)return null;let o=await Cu(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:wu(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await Cu(e.path)??Date.now()};return n.set(xu(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())Su(i.path)===Su(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=q.join(o,c);await K.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await L(l,t.content,u);let p=q.relative(e.dataDir,l).split(q.sep).join(`/`),h=ku(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:Ou(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 Au(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 xu(e,t,n){return`${Su(e)}::${t??``}::${n??``}`}function Su(e){return q.normalize(e)}async function Cu(e){try{return(await K.stat(e)).mtimeMs}catch{return null}}function wu(e){return Nt(`sha1`).update(e).digest(`hex`)}async function Tu(e){try{let t=await o(e);if(t===null)return Eu();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?Eu():{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:Du(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 Eu()}}function Eu(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Du(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 Ou(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:`,...yu,`Preview:`,e.preview+t].join(`
32
- `)}function ku(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 Au(e,t,n,r){let i=l(e,t,r);await K.mkdir(q.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await L(i,JSON.stringify(n,null,2),a)}const ju=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Mu(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=Ku(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=rc(nc(S,a)),T=[],E=(await Bl({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=>{G.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 Pu({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await Fu({entries:E,contextStore:f,compactionEvents:T});let D=await Iu({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g});if(E=D.entries,b=Ru(b,D.summaries),f&&(b=await Nu({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:sc(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:Y(E),compacted:!1},compactionEvents:T};let O=f?.getSnapshot(),k=Math.max(1e3,Math.floor(r*.7)),A=qu({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:O?.compaction.modelUsage}).projectedInputTokens>=k,j=O?.compaction.consecutiveAutocompactFailures??0;if(!A||j>=3)return{messages:sc(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:Y(E),compacted:!1},compactionEvents:T};let{toKeep:M,toSummarise:N}=wc(E,r);if(N.length===0)return{messages:sc(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:Y(E),compacted:!1},compactionEvents:T};let P=new Date().toISOString();try{let e=O?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await pc({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,Y(N)),affectedEntries:N.length,snapshotVersion:2}),{messages:sc(rc(M),n,y),priorSummary:t,compactionEntry:a,stats:{originalCount:C,keptCount:M.length,estimatedTokens:Y(M),compacted:!0},compactionEvents:T}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:P}),{messages:sc(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:Y(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 Nu(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=Y(t),u=i.getSnapshot().compaction.sessionMemory,d=!u&&l>=8e3,f=!!u&&l>=(u?.tokenEstimate??0)+15e3&&Gu(t)>=3;if(!d&&!f)return zu(n,u?.summary);let p=await pc({entries:t,llm:r,previousSummary:zu(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 Pu(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(Bu).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(!Bu(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=Vu(n)?Hu(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}),rc(l.reverse())}async function Fu(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(!Bu(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=Vu(r)?Hu(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}),Pu({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Iu(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(Bu).filter(e=>ju.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=Lu(r,o),g=new Date().toISOString();f.push(l),m+=r.length,h+=Math.max(0,Math.floor(Y(r)-Math.ceil(l.length/4)));let _={id:Ft(),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 Ju(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 Lu(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 wc(e,t){return Tc(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 Tc(e,t,n){let r=Mc(e,220),i=t?Mc(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return Nc(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function Ec(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return Nc(`Relevant prior segment: ${Mc(e,280)}${n}`)}function Dc(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=Tc(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:Nc(n?.summary||o),compressedSummary:Nc(n?.compressedSummary||Ec(n?.summary||o,r)),keywords:Oc(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Oc(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:jc(t,n)}function kc(...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 Ac(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function jc(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 kc(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 Mc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Nc(e){return e.replace(/\s+/g,` `).trim()}function Pc(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 Fc(e){let t=zc(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Bc(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 Ic(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function Lc(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:Rc(i.compressedSummary),timestamp:e.timestamp})}return r}function Rc(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function zc(...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 Bc(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=zc(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 Vc=`Xenova/bge-small-zh-v1.5`;let Hc,Uc;const Wc=new Map;async function Gc(e,t){if(e.length===0)return G.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=Xc(t),i=r.path;G.info(`topic segmentation embedding started`,{provider:`transformers`,model:Vc,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await Jc({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=Wc.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Wc.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return G.info(`topic segmentation embedding completed`,{provider:`transformers`,model:Vc,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 G.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:Vc,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function Kc(e,t){let[n]=await Gc([e],t);return n??[]}function qc(){return Vc}async function Jc(e){let t=Xc(e).path;return(!Hc||Uc!==t)&&(Uc=t,Hc=Yc(t)),Hc}async function Yc(e){let t=Date.now();G.info(`topic segmentation embedding extractor load started`,{model:Vc,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`,Vc,{dtype:`q8`});return G.info(`topic segmentation embedding extractor load completed`,{model:Vc,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw G.warn(`topic segmentation embedding extractor load failed`,{model:Vc,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function Xc(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=q.dirname(Qt(import.meta.url)),i=q.resolve(r,`../../../../../model`);if(Ht.existsSync(i))return{path:i,source:`repo_candidate`};let a=q.resolve(process.cwd(),`model`);return Ht.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const Zc=`topic_segments_vec`,Qc=`topic_segments_meta`,$c=`topic_segment_embedding_cache`;async function el(e){let t=Date.now(),n=nl(e);if(!n){G.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}G.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await K.mkdir(q.dirname(n),{recursive:!0});let r=Ge(n,{allowExtension:!0});try{let i=await il(r);G.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 ${Qc}`).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=He(rl(e));return o.get(e.segmentId)!==t});G.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 Gc(l.map(e=>rl(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=rl(t),n=He(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:ll(r,t.segmentId);sl(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(cl(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(ol(r,i,o.length),r.prepare(`DELETE FROM ${Zc} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${Zc} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,hl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${Zc} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${Qc} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${$c} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${Zc} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),G.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 G.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 tl(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return G.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=nl(e);if(!n)return G.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 K.access(n)}catch{return G.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}G.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await fl(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return G.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=Ge(n,{allowExtension:!0});try{let a=await il(i),o=qc(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?ul(i,o,r,e.limit):dl(i,o,r,e.limit);return G.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 G.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 nl(e){if(!(!e.dataDir||!e.sessionId))return q.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function rl(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
29
+ `)}async function il(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${Qc} (\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 ${$c} (\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_${Qc}_hash ON ${Qc}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${$c}_hash ON ${$c}(content_hash)`),{vectorAvailable:(await Be({db:e})).ok,vectorDims:al(e)}}function al(e){let t=e.prepare(`SELECT dims FROM ${$c} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function ol(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${Zc}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${Zc} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function sl(e,t){e.prepare(`INSERT INTO ${Qc} (\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 cl(e,t){e.prepare(`INSERT INTO ${$c} (\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 ll(e,t){let n=e.prepare(`SELECT embedding FROM ${$c} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function ul(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${Zc} v\n JOIN ${Qc} 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(hl(n),t,hl(n),r)}function dl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${$c} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:ml(n,pl(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function fl(e,t){try{return await Kc(e,t)}catch(e){return G.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function pl(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function ml(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 hl(e){return Buffer.from(new Float32Array(e).buffer)}const gl=8e3,_l=new Map;function vl(e){return{enabled:e?.enabled!==!1,embeddingModelDir:Pl(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 yl(e){let t=Tl(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(kl(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?Lc({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function bl(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=Fl(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:Ll(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 xl(e){let t=vl(e.config),n=()=>Bl({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){G.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){G.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){G.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=Tl(e.entries),i=X(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){G.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>El(e,t)),o=e.llm.flashModel||e.llm.model,s=await Sl({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();G.info(`topic segmentation classify started`,Bl({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Ol({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=yl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=Dl({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:X(h.entries),selectedSegmentIds:s.selectedSegmentIds});return await jl(e,g),G.info(`topic segmentation classify succeeded`,{...Bl({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 Sl(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await Cl({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 tl({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=Fc({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=Hl(l,e.config.maxShortlistSegments),d=wl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:gl});if(d&&Jl({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await Zl({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=Ic({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Ul({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:gl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await mc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),Ql({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=bl({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 Cl(e){G.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await pc(e);if(!t){let t=hc(e.entries);if(t.length===0){G.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await mc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),Ql({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),G.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}G.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=gc(t,e.entries);return n.length>0&&(await mc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),Ql({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),G.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function wl(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 Tl(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 El(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}zl(t)&&(r.add(t.toolName),t.isError&&(i=!0))}return{turnId:e.turnId,startIndex:e.startIndex,endIndex:n?e.entries.indexOf(n)+e.startIndex:e.endIndex,user:Ml(e.user,t.maxCandidateUserChars),assistant:n?Ml((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function Dl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:Ml(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 Ol(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=Fl(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:Ll(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 kl(e,t){let n=t?.assistant??Al(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:Nl(t?.user??e.user,50),assistantPreview:n?Nl(n,50):void 0}}function Al(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 jl(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await K.mkdir(n,{recursive:!0}),await K.appendFile(q.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function Ml(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Nl(e,t){return[...e].slice(0,t).join(``)}function Pl(e){return e?.trim()||void 0}function Fl(...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 Il(e){return[...Fl(e)].slice(0,8)}function Ll(e,t,n,r){let i=Rl(e,Fl(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Rl(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function zl(e){return e.role===`tool_result`}function Bl(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Vl(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 Vl(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function Hl(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 Ul(e){if(!Wl(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=Gl(Kl(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=wl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await sc({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??Il(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?_c(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Wl(e){let t=e.selectedSegments.filter(e=>!e.forced);return Yl(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:Xl(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Gl(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 Kl(e,t,n){let r=Math.max(n.length,1),i=Fl(t);return e.map(e=>({candidate:e,score:Ll(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 Jl(e){if(e.retrieved.length<2||!Yl(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 Yl(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function Xl(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 Zl(e){try{let t=await oc({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 Ql(e){let t=$l(e);if(!t||_l.has(t)){G.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}G.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=el(e).catch(t=>{G.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(()=>{_l.delete(t)});_l.set(t,n)}function $l(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 eu=[`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 tu(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 ou(t);for(let e of p.readStates)n.set(nu(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 K.mkdir(q.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=nu(e,t,r),a=n.get(i);if(!a)return null;let o=await iu(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:au(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await iu(e.path)??Date.now()};return n.set(nu(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())ru(i.path)===ru(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=q.join(o,c);await K.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await L(l,t.content,u);let p=q.relative(e.dataDir,l).split(q.sep).join(`/`),h=uu(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:lu(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 du(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 nu(e,t,n){return`${ru(e)}::${t??``}::${n??``}`}function ru(e){return q.normalize(e)}async function iu(e){try{return(await K.stat(e)).mtimeMs}catch{return null}}function au(e){return Nt(`sha1`).update(e).digest(`hex`)}async function ou(e){try{let t=await o(e);if(t===null)return su();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?su():{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:cu(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 su()}}function su(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function cu(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 lu(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:`,...eu,`Preview:`,e.preview+t].join(`
32
+ `)}function uu(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 du(e,t,n,r){let i=l(e,t,r);await K.mkdir(q.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await L(i,JSON.stringify(n,null,2),a)}const fu=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function pu(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=Du(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=Rs(Ls(S,a)),T=[],E=(await xl({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=>{G.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 hu({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await gu({entries:E,contextStore:f,compactionEvents:T});let D=await _u({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g});if(E=D.entries,b=yu(b,D.summaries),f&&(b=await mu({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:Hs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let O=f?.getSnapshot(),k=Math.max(1e3,Math.floor(r*.7)),A=Ou({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:O?.compaction.modelUsage}).projectedInputTokens>=k,j=O?.compaction.consecutiveAutocompactFailures??0;if(!A||j>=3)return{messages:Hs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let{toKeep:M,toSummarise:N}=ac(E,r);if(N.length===0)return{messages:Hs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(E),compacted:!1},compactionEvents:T};let P=new Date().toISOString();try{let e=O?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Js({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,X(N)),affectedEntries:N.length,snapshotVersion:2}),{messages:Hs(Rs(M),n,y),priorSummary:t,compactionEntry:a,stats:{originalCount:C,keptCount:M.length,estimatedTokens:X(M),compacted:!0},compactionEvents:T}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:P}),{messages:Hs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:X(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 mu(e){let{entries:t,existingSummary:n,llm:r,contextStore:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=X(t),u=i.getSnapshot().compaction.sessionMemory,d=!u&&l>=8e3,f=!!u&&l>=(u?.tokenEstimate??0)+15e3&&Eu(t)>=3;if(!d&&!f)return bu(n,u?.summary);let p=await Js({entries:t,llm:r,previousSummary:bu(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 hu(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(xu).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(!xu(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=Su(n)?Cu(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}),Rs(l.reverse())}async function gu(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(!xu(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=Su(r)?Cu(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}),hu({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function _u(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(xu).filter(e=>fu.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=vu(r,o),g=new Date().toISOString();f.push(l),m+=r.length,h+=Math.max(0,Math.floor(X(r)-Math.ceil(l.length/4)));let _={id:Ft(),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 ku(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 vu(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 Ru(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 yu(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 zu(...e){return e.map(e=>e?.trim()).filter(Boolean).join(`
43
+ `)}function bu(...e){return e.map(e=>e?.trim()).filter(Boolean).join(`
44
44
 
45
- `)||void 0}function Bu(e){return e.role===`tool_result`}function Vu(e){return e.toolName===`skill_load`}function Hu(e){let t=Uu(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 Uu(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Wu(t);if(e.name||e.path)return e}return{}}function Wu(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 Gu(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Ku(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function qu(e){let t=e.pendingUserMessage?.trim()?Y([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=Y(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=Y(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 Ju(e,t,n,r){let i=j(e,t,r);await K.mkdir(q.dirname(i),{recursive:!0}),await K.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Yu(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await bu({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 Mu({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Xu(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}):Mu({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 Zu=J.Object({command:J.String({description:`Shell command to execute`}),workdir:J.Optional(J.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:J.Optional(J.Record(J.String(),J.String())),timeout:J.Optional(J.Number({description:`Max total runtime in seconds before the process is killed (default: 1800)`})),yieldMs:J.Optional(J.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:J.Optional(J.Boolean({description:`Return immediately with a running session (poll with the process tool)`}))}),Qu=6e4;function $u(e,t,n){return Math.max(t,Math.min(n,e))}function ed(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function td(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?Qu:$u(Math.floor(e),0,12e4)}function nd(e,t){if(!t?.trim())return e;let n=q.isAbsolute(t)?q.normalize(t):q.normalize(q.join(e,t));if(!n.startsWith(e+q.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function rd(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 id(e){return od({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
47
- `)}function ad(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function od(e){let t=ad(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 sd(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:Zu,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=nd(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=ed(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?td(n.yieldMs):Qu,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:rd(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?od({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[id(l)],p=ad(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 cd=J.Object({action:J.String({description:`Process action: list | poll | log | kill`}),sessionId:J.Optional(J.String({description:`Session id for non-list actions`})),offset:J.Optional(J.Number({description:`Log line offset (0-based)`})),limit:J.Optional(J.Number({description:`Maximum lines to return`})),timeout:J.Optional(J.Number({description:`Poll wait time in milliseconds`}))});function ld(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function ud(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function dd(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:cd,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 ud(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,ld(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`}}:ud(`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}}:ud(`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}}:ud(`No session found for ${i}`)}return ud(`Unsupported action: ${n.action}`)}}}function fd(e){return sd({workspaceDir:e,registry:Pn(),scopeKey:e})}const pd=5*1024*1024,md=2e3;async function hd(e,t){e&&await e(t).catch(()=>{})}function gd(e,t){return q.isAbsolute(e)?q.normalize(e):q.normalize(q.join(t,e))}const _d=J.Object({path:J.String({description:`File path (relative to workspace or absolute)`}),offset:J.Optional(J.Number({description:`Line offset (1-based, default: 1)`})),limit:J.Optional(J.Number({description:`Maximum lines to read (default: 2000)`}))});function vd(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:_d,async execute(n,r){let i;try{i=gd(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 K.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 $t(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>pd){let e=o.slice(0,pd).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${pd} 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(md,r.limit??md),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 xu(e){return e.role===`tool_result`}function Su(e){return e.toolName===`skill_load`}function Cu(e){let t=wu(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 wu(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=Tu(t);if(e.name||e.path)return e}return{}}function Tu(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 Eu(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Du(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Ou(e){let t=e.pendingUserMessage?.trim()?X([{role:`user`,content:e.pendingUserMessage,timestamp:new Date(0).toISOString()}]):0;if(!e.checkpoint){let n=X(e.workingEntries)+t;return{projectedInputTokens:n,estimatedIncrementTokens:n}}let n=X(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 ku(e,t,n,r){let i=j(e,t,r);await K.mkdir(q.dirname(i),{recursive:!0}),await K.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Au(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await tu({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 pu({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function ju(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}):pu({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 Mu=J.Object({command:J.String({description:`Shell command to execute`}),workdir:J.Optional(J.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:J.Optional(J.Record(J.String(),J.String())),timeout:J.Optional(J.Number({description:`Max total runtime in seconds before the process is killed (default: 1800)`})),yieldMs:J.Optional(J.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:J.Optional(J.Boolean({description:`Return immediately with a running session (poll with the process tool)`}))}),Nu=6e4;function Pu(e,t,n){return Math.max(t,Math.min(n,e))}function Fu(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function Iu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?Nu:Pu(Math.floor(e),0,12e4)}function Lu(e,t){if(!t?.trim())return e;let n=q.isAbsolute(t)?q.normalize(t):q.normalize(q.join(e,t));if(!n.startsWith(e+q.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Ru(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 zu(e){return Vu({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
47
+ `)}function Bu(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Vu(e){let t=Bu(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 Hu(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:Mu,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=Lu(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Fu(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?Iu(n.yieldMs):Nu,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:Ru(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?Vu({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[zu(l)],p=Bu(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 Uu=J.Object({action:J.String({description:`Process action: list | poll | log | kill`}),sessionId:J.Optional(J.String({description:`Session id for non-list actions`})),offset:J.Optional(J.Number({description:`Log line offset (0-based)`})),limit:J.Optional(J.Number({description:`Maximum lines to return`})),timeout:J.Optional(J.Number({description:`Poll wait time in milliseconds`}))});function Wu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Gu(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Ku(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:Uu,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 Gu(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Wu(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`}}:Gu(`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}}:Gu(`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}}:Gu(`No session found for ${i}`)}return Gu(`Unsupported action: ${n.action}`)}}}function qu(e){return Hu({workspaceDir:e,registry:Pn(),scopeKey:e})}const Ju=5*1024*1024,Yu=2e3;async function Xu(e,t){e&&await e(t).catch(()=>{})}function Zu(e,t){return q.isAbsolute(e)?q.normalize(e):q.normalize(q.join(t,e))}const Qu=J.Object({path:J.String({description:`File path (relative to workspace or absolute)`}),offset:J.Optional(J.Number({description:`Line offset (1-based, default: 1)`})),limit:J.Optional(J.Number({description:`Maximum lines to read (default: 2000)`}))});function $u(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Qu,async execute(n,r){let i;try{i=Zu(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 K.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 $t(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>Ju){let e=o.slice(0,Ju).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Ju} 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(Yu,r.limit??Yu),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 yd=J.Object({path:J.String({description:`File path (relative to workspace or absolute)`}),content:J.String({description:`File content to write`})});function bd(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:yd,async execute(r,i){let a;try{a=gd(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await K.mkdir(q.dirname(a),{recursive:!0}),await K.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await hd(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 xd=J.Object({path:J.String({description:`File path (relative to workspace or absolute)`}),old_string:J.String({description:`Exact text to replace`}),new_string:J.String({description:`Replacement text`})});function Sd(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:xd,async execute(r,i){let a;try{a=gd(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 K.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 K.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await hd(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 Cd=J.Object({path:J.Optional(J.String({description:`Directory path (default: workspace root)`}))});function wd(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:Cd,async execute(t,n){let r=n.path??`.`,i;try{i=gd(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await K.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 Td=J.Object({input:J.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Ed(e,t){let n=q.isAbsolute(e)?q.normalize(e):q.normalize(q.join(t,e));if(!n.startsWith(t+q.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Dd(e,t){let n=q.relative(t,e);return!n||n===``?q.basename(e):n.startsWith(`..`)||q.isAbsolute(n)?e:n}async function Od(e){await K.mkdir(q.dirname(e),{recursive:!0})}async function kd(e,t){e&&await e(t).catch(()=>{})}function Ad(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 jd(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:Td,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=Nd(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=Ed(r.path,e);await Od(i),await K.writeFile(i,r.contents,`utf-8`),await kd(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Md(o,s,`added`,Dd(i,e));continue}if(r.kind===`delete`){let i=Ed(r.path,e);await K.rm(i,{force:!0,recursive:!1}),await kd(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Md(o,s,`deleted`,Dd(i,e));continue}let i=Ed(r.path,e),a=await Ld(i,r.chunks);if(r.movePath){let c=Ed(r.movePath,e);await Od(c),await K.writeFile(c,a,`utf-8`),await K.rm(i,{force:!0,recursive:!1}),await kd(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Md(o,s,`modified`,Dd(c,e))}else await K.writeFile(i,a,`utf-8`),await kd(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Md(o,s,`modified`,Dd(i,e))}return{content:[{type:`text`,text:Ad(o)}],details:{summary:o}}}catch(e){if(Io(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Md(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Nd(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Pd(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Fd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Pd(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 Fd(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}=Id(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 Id(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 Ld(e,t){let n=(await K.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=zd(n,Rd(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
57
- `)}function Rd(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=Bd(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=Bd(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=Bd(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 zd(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 Bd(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(Vd(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Vd(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Vd(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Vd(e,t,n,e=>Hd(e.trim())))return n;return null}function Vd(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 Hd(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}function Ud(e){return q.join(e,`.aimax`)}function Wd(e){return q.join(Ud(e),`MEMORY.md`)}async function Gd(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function Kd(e,t){let n=Ud(e),r=We({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 qd(e){return qe(Ud(e))}async function Jd(e){try{return await K.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Yd(e){return Jd(Wd(e))}async function Xd(e,t,n){let{provider:r}=Kd(e,n);return await r.search(t)}async function Zd(e,t,n,r,i){try{let{provider:a}=Kd(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Qd(e,t,n){let{provider:r,resolvedProviderId:i}=Kd(e,n);await r.append(t),await Gd(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 $d(e,t,n,r){let{provider:i,resolvedProviderId:a}=Kd(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 Gd(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Gd(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 Gd(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 Gd(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Gd(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 ef(e,t,n,r){let{provider:i,resolvedProviderId:a}=Kd(e,r);await i.updateFile(t,n),await Gd(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}=Kd(e,n);await r.deleteFile(t),await Gd(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const nf=J.Object({query:J.String({description:`Search query (case-insensitive substring match)`})});function rf(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:nf,async execute(n,r){let i=(await Xd(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(`
59
- `)}],details:{matches:i}}}}}const af=J.Object({file:J.String({description:`Memory file path (from memory_search results)`}),start_line:J.Number({description:`Start line number (1-based)`}),end_line:J.Number({description:`End line number (1-based)`})});function of(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:af,async execute(n,r){let i=await Zd(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(`
60
- `)||`(empty)`}],details:{lines:i}}}}}const sf=J.Object({content:J.String({description:`Content to write to memory`})});function cf(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:sf,async execute(n,r){try{return await Qd(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 lf=J.Object({section:J.Optional(J.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:J.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:J.Union([J.Literal(`append`),J.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function uf(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:lf,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Qd(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 ef(e,`MEMORY.md`,df(await Yd(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Qd(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 df(e,t,n){let r=e.split(`
53
+ `),lines:d.length,truncated:f}}}}}const ed=J.Object({path:J.String({description:`File path (relative to workspace or absolute)`}),content:J.String({description:`File content to write`})});function td(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:ed,async execute(r,i){let a;try{a=Zu(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await K.mkdir(q.dirname(a),{recursive:!0}),await K.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await Xu(n,{type:`write`,operation:`write_file`,file:a,content:i.content,toolCallId:r,toolName:`write_file`})}catch(e){return{content:[{type:`text`,text:`Error writing file: ${e instanceof Error?e.message:String(e)}`}],details:{path:a}}}return{content:[{type:`text`,text:`File written: ${i.path}`}],details:{path:a}}}}}const nd=J.Object({path:J.String({description:`File path (relative to workspace or absolute)`}),old_string:J.String({description:`Exact text to replace`}),new_string:J.String({description:`Replacement text`})});function rd(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:nd,async execute(r,i){let a;try{a=Zu(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 K.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 K.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await Xu(n,{type:`edit`,operation:`edit_file`,file:a,content:s,toolCallId:r,toolName:`edit_file`}),{content:[{type:`text`,text:`File edited: ${i.path}`}],details:{path:a,occurrences:1}}}}}const id=J.Object({path:J.Optional(J.String({description:`Directory path (default: workspace root)`}))});function ad(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:id,async execute(t,n){let r=n.path??`.`,i;try{i=Zu(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await K.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 od=J.Object({input:J.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function sd(e,t){let n=q.isAbsolute(e)?q.normalize(e):q.normalize(q.join(t,e));if(!n.startsWith(t+q.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function cd(e,t){let n=q.relative(t,e);return!n||n===``?q.basename(e):n.startsWith(`..`)||q.isAbsolute(n)?e:n}async function ld(e){await K.mkdir(q.dirname(e),{recursive:!0})}async function ud(e,t){e&&await e(t).catch(()=>{})}function dd(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 fd(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:od,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=md(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=sd(r.path,e);await ld(i),await K.writeFile(i,r.contents,`utf-8`),await ud(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),pd(o,s,`added`,cd(i,e));continue}if(r.kind===`delete`){let i=sd(r.path,e);await K.rm(i,{force:!0,recursive:!1}),await ud(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),pd(o,s,`deleted`,cd(i,e));continue}let i=sd(r.path,e),a=await vd(i,r.chunks);if(r.movePath){let c=sd(r.movePath,e);await ld(c),await K.writeFile(c,a,`utf-8`),await K.rm(i,{force:!0,recursive:!1}),await ud(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),pd(o,s,`modified`,cd(c,e))}else await K.writeFile(i,a,`utf-8`),await ud(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),pd(o,s,`modified`,cd(i,e))}return{content:[{type:`text`,text:dd(o)}],details:{summary:o}}}catch(e){if(_o(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function pd(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function md(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);hd(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=gd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function hd(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 gd(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}=_d(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 _d(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 vd(e,t){let n=(await K.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=bd(n,yd(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
57
+ `)}function yd(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=xd(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=xd(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=xd(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 bd(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 xd(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(Sd(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(Sd(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(Sd(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(Sd(e,t,n,e=>Cd(e.trim())))return n;return null}function Sd(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 Cd(e){return Array.from(e).map(e=>{switch(e){case`‐`:case`‑`:case`‒`:case`–`:case`—`:case`―`:case`−`:return`-`;case`‘`:case`’`:case`‚`:case`‛`:return`'`;case`“`:case`”`:case`„`:case`‟`:return`"`;case`\xA0`:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:case` `:return` `;default:return e}}).join(``)}function wd(e){return q.join(e,`.aimax`)}function Td(e){return q.join(wd(e),`MEMORY.md`)}async function Ed(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function Dd(e,t){let n=wd(e),r=We({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 Od(e){return qe(wd(e))}async function kd(e){try{return await K.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ad(e){return kd(Td(e))}async function jd(e,t,n){let{provider:r}=Dd(e,n);return await r.search(t)}async function Md(e,t,n,r,i){try{let{provider:a}=Dd(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Nd(e,t,n){let{provider:r,resolvedProviderId:i}=Dd(e,n);await r.append(t),await Ed(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 Pd(e,t,n,r){let{provider:i,resolvedProviderId:a}=Dd(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 Ed(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Ed(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 Ed(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 Ed(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await Ed(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 Fd(e,t,n,r){let{provider:i,resolvedProviderId:a}=Dd(e,r);await i.updateFile(t,n),await Ed(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function Id(e,t,n){let{provider:r,resolvedProviderId:i}=Dd(e,n);await r.deleteFile(t),await Ed(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const Ld=J.Object({query:J.String({description:`Search query (case-insensitive substring match)`})});function Rd(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:Ld,async execute(n,r){let i=(await jd(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(`
59
+ `)}],details:{matches:i}}}}}const zd=J.Object({file:J.String({description:`Memory file path (from memory_search results)`}),start_line:J.Number({description:`Start line number (1-based)`}),end_line:J.Number({description:`End line number (1-based)`})});function Bd(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:zd,async execute(n,r){let i=await Md(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(`
60
+ `)||`(empty)`}],details:{lines:i}}}}}const Vd=J.Object({content:J.String({description:`Content to write to memory`})});function Hd(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:Vd,async execute(n,r){try{return await Nd(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 Ud=J.Object({section:J.Optional(J.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:J.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:J.Union([J.Literal(`append`),J.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Wd(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:Ud,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Nd(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 Fd(e,`MEMORY.md`,Gd(await Ad(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Nd(e,o,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}),{content:[{type:`text`,text:`Memory updated: section "${i}" (${a})`}],details:{section:i,mode:a}}}catch(e){throw Error(`Failed to write memory: ${e instanceof Error?e.message:String(e)}`)}}}}function Gd(e,t,n){let r=e.split(`
61
61
  `),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(`
62
62
  `).trimEnd(),a,r.slice(s).join(`
63
63
  `).trimStart()].filter(e=>e.length>0).join(`
64
- `)}\n`}function ff(e,t){let n=e.split(`
64
+ `)}\n`}function Kd(e,t){let n=e.split(`
65
65
  `),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(`
66
66
  `).trimEnd(),n.slice(a).join(`
67
67
  `).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
68
- `)}\n`:``}function pf(e,t){let n=e.split(`
68
+ `)}\n`:``}function qd(e,t){let n=e.split(`
69
69
  `);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
70
- `)}\n`:``)}function mf(e,t,n){let r=e.split(`
70
+ `)}\n`:``)}function Jd(e,t,n){let r=e.split(`
71
71
  `);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
72
- `)}\n`)}function hf(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 gf(e,t){let n=[],r=t.split(`
73
- `);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 _f=J.Object({content:J.String({description:`Note to append to today's daily log`}),scope:J.Optional(J.Union([J.Literal(`daily`),J.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:_f,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await $d(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 yf=J.Object({scope:J.Optional(J.Union([J.Literal(`long-term`),J.Literal(`recent`),J.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function bf(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:yf,async execute(n,r){try{let n=r.scope??`all`,i=await qd(e),a=[];for(let n of i.slice(0,30)){let r=await Zd(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
74
- `),t=gf(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
72
+ `)}\n`)}function Yd(e){let t=e.indexOf(`#`);if(t===-1)return{filePath:e};let n=e.slice(0,t),r=e.slice(t+1),i=r.match(/^L(\d+)$/);return i?{filePath:n,line:Number(i[1])}:{filePath:n,section:r}}function Xd(e,t){let n=[],r=t.split(`
73
+ `);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 Zd=J.Object({content:J.String({description:`Note to append to today's daily log`}),scope:J.Optional(J.Union([J.Literal(`daily`),J.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Qd(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:Zd,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await Pd(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 $d=J.Object({scope:J.Optional(J.Union([J.Literal(`long-term`),J.Literal(`recent`),J.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function ef(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:$d,async execute(n,r){try{let n=r.scope??`all`,i=await Od(e),a=[];for(let n of i.slice(0,30)){let r=await Md(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
74
+ `),t=Xd(n,e);a.push({file:n,content:e,sections:t})}}return{content:[{type:`text`,text:a.map(e=>{let t=e.sections.length>0?e.sections.map(e=>` [${e.id}] ${e.heading}`).join(`
75
75
  `):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
76
76
 
77
- `)||`(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 xf=J.Object({id:J.Optional(J.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:J.Optional(J.String({description:`Search query used to find memories to delete`})),limit:J.Optional(J.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:J.Optional(J.Union([J.Literal(`long-term`),J.Literal(`recent`),J.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Sf(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:xf,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=hf(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=ff(await Yd(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 ef(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 Zd(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(`
78
- `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await ef(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 Zd(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=pf(n.join(`
79
- `),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 ef(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 Xd(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 Cf=J.Object({id:J.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:J.String({description:`New content to replace the existing memory with`})});function wf(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:Cf,async execute(n,r){try{let n=hf(r.id);if(n.section){let i=df(await Yd(e)??``,n.section,r.content);return await ef(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 Zd(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=mf(i.join(`
80
- `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await ef(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 ef(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 Tf=J.Object({query:J.Optional(J.String({description:`Search query; omit to browse recent sessions.`})),role_filter:J.Optional(J.Union([J.Literal(`user`),J.Literal(`assistant`),J.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:J.Optional(J.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:J.Optional(J.Union([J.Literal(`llm`),J.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Ef(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:Tf,async execute(n,r){let i=Df(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Of(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 kf({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=Hf(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 pc({entries:zf(Rf(await F(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Vf({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 Df(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Of(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 kf(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Nf(e.query),i=(await Uf(n,6,async t=>Af({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(Lf).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 Af(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
81
- `);for(let t of r){let r=t.trim();if(!r||!jf(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!Mf(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Ff(i.content,e.terms,i.role);if(a<=0)continue;let o=If(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(Lf),n.length=20)}return n.sort(Lf),n}function jf(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Mf(e){return e===`user`||e===`assistant`||e===`tool_result`}function Nf(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=>Pf(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 Pf(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 Ff(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 If(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function Lf(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function Rf(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function zf(e,t,n){if(e.length===0)return e;let r=Nf(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 Bf(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 Bf(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 Vf(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(`
82
- `)}function Hf(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(`
83
- `)}`}async function Uf(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 Wf(e){return q.join(e,`.aimax`,`skills`)}function Gf(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Kf(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${Gf(n)}\n`)}function qf(e){let t=zt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
84
- `);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 Jf(e){let t=zt(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 Yf(e){return(await K.stat(e)).mtime.toISOString()}async function Xf(e){return Qf([Wf(e)])}async function Zf(e,t,n=[]){return Qf([...n,...t,Wf(e)])}async function Qf(e){let t=new Map;for(let n of e){let e;try{e=await K.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=q.join(n,e,`SKILL.md`),i;try{i=await K.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=qf(i),o=Jf(i),s=await Yf(r)}catch(t){Kf(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 $f(e,t){let n=t.trim();if(!n)return;let r=(await Qf(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:q.dirname(r.location)}}async function ep(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=q.resolve(r),a=q.basename(i)===`SKILL.md`?i:q.join(i,`SKILL.md`);if(q.basename(a)!==`SKILL.md`)return;let o;try{o=await K.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=qf(o),c=Jf(o),l=await Yf(a)}catch(e){Kf(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:q.dirname(a)}}async function tp(e,t,n){let r=n?.trim()?await ep(t,n):await $f(e,t);if(!r)return;let i=await K.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function np(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(`
77
+ `)||`(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 tf=J.Object({id:J.Optional(J.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:J.Optional(J.String({description:`Search query used to find memories to delete`})),limit:J.Optional(J.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:J.Optional(J.Union([J.Literal(`long-term`),J.Literal(`recent`),J.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function nf(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:tf,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Yd(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Kd(await Ad(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 Fd(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 Md(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=Kd(n.join(`
78
+ `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Fd(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 Md(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=qd(n.join(`
79
+ `),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 Fd(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 Id(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 jd(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await Id(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 rf=J.Object({id:J.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:J.String({description:`New content to replace the existing memory with`})});function af(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:rf,async execute(n,r){try{let n=Yd(r.id);if(n.section){let i=Gd(await Ad(e)??``,n.section,r.content);return await Fd(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 Md(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=Jd(i.join(`
80
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Fd(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 Fd(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 of=J.Object({query:J.Optional(J.String({description:`Search query; omit to browse recent sessions.`})),role_filter:J.Optional(J.Union([J.Literal(`user`),J.Literal(`assistant`),J.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:J.Optional(J.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:J.Optional(J.Union([J.Literal(`llm`),J.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function sf(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:of,async execute(n,r){let i=cf(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await lf(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 uf({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=Cf(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 Js({entries:bf(yf(await F(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:Sf({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 cf(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function lf(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 uf(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=mf(e.query),i=(await wf(n,6,async t=>df({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(vf).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 df(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
81
+ `);for(let t of r){let r=t.trim();if(!r||!ff(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!pf(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=gf(i.content,e.terms,i.role);if(a<=0)continue;let o=_f(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(vf),n.length=20)}return n.sort(vf),n}function ff(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function pf(e){return e===`user`||e===`assistant`||e===`tool_result`}function mf(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=>hf(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 hf(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 gf(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 _f(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function vf(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function yf(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function bf(e,t,n){if(e.length===0)return e;let r=mf(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 xf(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 xf(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 Sf(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(`
82
+ `)}function Cf(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(`
83
+ `)}`}async function wf(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 Tf(e){return q.join(e,`.aimax`,`skills`)}function Ef(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Df(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${Ef(n)}\n`)}function Of(e){let t=zt(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
84
+ `);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 kf(e){let t=zt(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 Af(e){return(await K.stat(e)).mtime.toISOString()}async function jf(e){return Nf([Tf(e)])}async function Mf(e,t,n=[]){return Nf([...n,...t,Tf(e)])}async function Nf(e){let t=new Map;for(let n of e){let e;try{e=await K.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=q.join(n,e,`SKILL.md`),i;try{i=await K.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=Of(i),o=kf(i),s=await Af(r)}catch(t){Df(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 Pf(e,t){let n=t.trim();if(!n)return;let r=(await Nf(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:q.dirname(r.location)}}async function Ff(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=q.resolve(r),a=q.basename(i)===`SKILL.md`?i:q.join(i,`SKILL.md`);if(q.basename(a)!==`SKILL.md`)return;let o;try{o=await K.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=Of(o),c=kf(o),l=await Af(a)}catch(e){Df(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:q.dirname(a)}}async function If(e,t,n){let r=n?.trim()?await Ff(t,n):await Pf(e,t);if(!r)return;let i=await K.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Lf(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(`
85
85
  `)).join(`
86
- `)}\n</available_skills>`}const rp=J.Object({category:J.Optional(J.String({description:`Reserved category filter field. Not used yet.`}))}),ip=J.Object({name:J.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:J.Optional(J.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function ap(e,t,n=[]){return[...n,...t,Wf(e)]}function op(e,t,n=[]){let r=ap(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:rp,async execute(e,t){let n=await Qf(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 sp(e){let t=ap(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:ip,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 cp=J.Object({});function lp(e,t,n){return{name:`get_goal`,label:`Get Goal`,description:"Get the current thread goal, including status, budget, token and time usage, remaining token budget, and V2-lite workflow summary (`goalState`). Returns null when no goal is set.",parameters:cp,async execute(r,i){let a=await U(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null,goalState:null,workflowWarning:null})}],details:{}};let o=await B(e,t,a,{storeName:n}),s=await Zn(e,t,{storeName:n}),c={goal:{...a,objective:o,remainingTokens:a.tokenBudget===null?void 0:Math.max(0,a.tokenBudget-a.tokensUsed)},goalState:s.goalState,workflowWarning:s.workflowWarning};return{content:[{type:`text`,text:JSON.stringify(c,null,2)}],details:{}}}}}J.Object({status:J.String({description:`Status to set. Only 'complete' is allowed.`})});function up(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 dp(e){let t=up(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=q.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 fp(e){let t=e.watchFactory??((e,t,n)=>Ht.watch(e,t,n)),n=q.join(e.dataDir,`.aimax`),r=[{target:q.join(n,`MEMORY.md`),kind:`memory-file`},{target:q.join(n,`memory.md`),kind:`memory-file-lower`},{target:q.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=dp({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 X(e){return{storeName:e.sessionStoreName,encryptSessions:e.encryptSessions,...e.sessionPathScope}}function pp(e){return e.projectDir?.trim()||q.join(e.dataDir,`workspace`)}async function mp(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=pp(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=vp(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:m?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.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=q.join(t.dataDir,`.aimax`),m=Qe({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g,_,v,y,b,x;if(m?.provider)g=m.provider,_=m.registration.id,v=m.registration.pluginId,y=`plugin`,b=!1;else{try{g=Ke({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName},{includeSessions:!0})}catch(e){if(!Ue(e))throw e;x=e instanceof Error?e.message:String(e),g=hp(p,x)}_=g.id,v=void 0,y=`builtin`,b=!0}x&&await n.dispatchDiagnostic(i,{level:`warn`,scope:`memory`,phase:`memory_provider_degraded`,message:`builtin memory provider degraded after sqlite index failure`,details:{providerId:_,requestedProviderId:o,requestedPluginId:s,error:x}}).catch(()=>{}),await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:y,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:b}}).catch(()=>{});let S=fp({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let C=async e=>{await h(t.dataDir,i,e,_p({sessionOptions:X(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,memoryProvider:g,memoryProviderSource:y,memoryFallbackToBuiltin:b,recallState:{recallProvided:!1},compactionRecallState:{recallProvided:!1},appendTranscriptEntry:C,persistInitialUserEntry:async e=>d?!1:(await C({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{S()}}}function hp(e,t){return{id:`builtin-memory`,name:`Builtin Memory Provider (degraded)`,status:()=>({backend:`builtin`,provider:`builtin-memory`,workspaceDir:e,dbPath:q.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 gp(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function _p(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 vp(e){let t=[],n=new Set;for(let r of e){let e=r.replace(/\\/g,`/`).replace(/^\.\//,``).trim();if(!e)continue;let i=e.toLowerCase()===`memory.md`?`MEMORY.md`:e,a=i.toLowerCase();n.has(a)||(n.add(a),t.push(i))}return t}function Z(e){return{storeName:e.sessionStoreName}}function yp(e){return pp({dataDir:e.dataDir,projectDir:e.projectDir})}function bp(e){return pr({dataDir:e.dataDir,workspaceDir:yp(e),projectDir:e.projectDir})}function xp(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function Q(e,t){return xp({ok:!1,error:e,...t})}function Sp(e,t){return Vn(e.dataDir,e.sessionId,Z(e),t)}async function Cp(e){try{return await Jn(e.dataDir,e.sessionId,Z(e))}catch(e){if(e instanceof Rn)return{corrupt:!0};throw e}}function wp(){return Q(`workflow_corrupt`,{repairTool:`goal_repair_workflow_state`})}const Tp={hint:[`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(` `),suggestedTools:[`goal_record_evidence`],example:{registerManualEvidence:{tool:`goal_record_evidence`,args:{kind:`manual`,source:`goal/state.json`,summary:`planning evidence`,content:`Task list and acceptance criteria were added to goal/state.json.`}},registerCommandEvidence:{tool:`goal_record_evidence`,args:{kind:`exec`,command:`npm test`,cwd:`<workspace>`,timeoutMs:12e4}},registerSnapshotEvidence:{tool:`goal_record_evidence`,args:{kind:`snapshot`,path:`<workspace>/artifact.html`,summary:`final deliverable`}},evidenceRefs:[`manual:...`]}},Ep=/goal[/\\]state\.json|\btask\s*list\b|\btask-\d+|\b(plan|planning|planned|added|through|workflow)\b/i,Dp=/[/\\]|\.(?:html|css|js|ts|tsx|jsx|json|md|txt|py|go|rs|yaml|yml|sh)\b|\bexists\b/i,Op=/\b(npm|pnpm|yarn|cargo|go test|pytest|vitest|jest|exit code|stdout|stderr|command output|test pass|tests pass)\b/i;function kp(e,t){let n=`${e}\n${t}`;return Ep.test(n)?`goal/state.json`:/\buser\b/i.test(n)&&/\bconfirm/i.test(n)?`user`:`model`}function Ap(e){let t=e.match(/^(.+?)\s+exists\s*$/i);if(t)return t[1].trim();let n=e.match(/(?:^|\s)((?:[\w.-]+\/)+[\w.-]+\.\w{1,10})(?:\s|$)/);return n?n[1].trim():/^[\w./-]+\.\w{1,10}$/.test(e.trim())?e.trim():null}function jp(e){let t=e.trim();return Ep.test(t)?{reason:`the ref describes planning state`}:Dp.test(t)?{reason:Ap(t)?`the ref describes a file artifact`:`the ref describes a file artifact but no reliable path could be extracted`}:Op.test(t)?{reason:`the ref describes command output`}:{reason:`the ref is natural language and must be registered as evidence`}}function Mp(e){let t=e.trim();if(Ep.test(t))return{kind:`manual`,source:`goal/state.json`,summary:t.slice(0,120),content:t};if(Dp.test(t)){let e=Ap(t);if(e)return{kind:`snapshot`,path:e,summary:t.slice(0,120)}}return Op.test(t)?{kind:`exec`,command:t.includes(`npm test`)?`npm test`:`<command>`,cwd:`<workspace>`,timeoutMs:12e4}:{kind:`manual`,source:kp(t,t),summary:t.slice(0,120),content:t}}function Np(e){let t=new Set,n=[];for(let r of e){if(r.code!==`unregistered_evidence_ref`||!r.ref.trim())continue;let e=r.ref.trim();if(t.has(e))continue;t.add(e);let i=jp(e);n.push({tool:`goal_record_evidence`,reason:i.reason,args:Mp(e)})}return n}function Pp(e){let t=e.errors[0]?.code??`invalid_evidence`;return t===`unregistered_evidence_ref`?Q(t,{errors:e.errors,repairPlan:Np(e.errors),...Tp}):Q(t,{errors:e.errors})}function Fp(e,t){return Q(`manual_source_required`,{hint:`Manual evidence requires a source. Use source='goal/state.json' for plan/workflow facts, source='user' for user confirmation, or another concise origin string.`,retryWith:{kind:`manual`,source:kp(e,t),summary:e,content:t},example:{kind:`manual`,source:`goal/state.json`,summary:`planning evidence`,content:`Task list and acceptance criteria were added to goal/state.json.`}})}function Ip(e){let t=kr(e.length);return e.map((e,n)=>typeof e==`string`?{id:t[n],text:e.trim(),required:!0}:{id:t[n],text:e.text.trim(),required:e.required!==!1}).filter(e=>e.text.length>0)}function Lp(e,t){let n=new Set;for(let t of e??[])t.trim()&&n.add(t.trim());for(let e of t??[])for(let t of e.evidenceRefs??[])t.trim()&&n.add(t.trim());return[...n]}function Rp(e,t){return e.tasks.find(e=>e.id===t)}function zp(e){return e.tasks.some(e=>e.kind===`execution`&&e.required!==!1)}function Bp(e){return e.ok===!1?e.warning:null}async function Vp(e,t){await Sr(e.dataDir,e.sessionId,t,Z(e));let n=Bp(await Er(e.dataDir,e.sessionId,t,Z(e)));return n?{planWarning:n}:{}}function Hp(e){return{name:`goal_plan_update`,label:`Goal Plan Update`,description:`Update controlled sections of goal/plan.md without changing task workflow state.`,parameters:J.Object({interpretation:J.Optional(J.String()),assumptions:J.Optional(J.Array(J.String())),openQuestions:J.Optional(J.Array(J.String())),taskPlanNotes:J.Optional(J.String())}),async execute(t,n){return Sp(e,async()=>{let t=await Cp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return wp();let r=t;await Dr(e.dataDir,e.sessionId,{type:`goal_plan_updated`,goalId:r.goalId,interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Z(e));let i=await Tr(e.dataDir,e.sessionId,{interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Z(e)),a=await Er(e.dataDir,e.sessionId,r,Z(e));return xp({ok:!0,goalId:r.goalId,planMeta:i,warning:Bp(a),hint:`Use goal_add_task to project executable tasks into goal/state.json.`})})}}}function Up(e){return{name:`goal_task_done`,label:`Goal Task Done`,description:`Mark the current doing task done with evidence covering required acceptance criteria.`,parameters:J.Object({taskId:J.String(),summary:J.Optional(J.String()),evidenceRefs:J.Optional(J.Array(J.String())),acceptanceEvidence:J.Optional(J.Array(J.Object({criterionId:J.String(),evidenceRefs:J.Array(J.String())})))}),async execute(t,n){return Sp(e,async()=>{let t=await Cp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return wp();let r=t,i=Rp(r,n.taskId);if(!i)return Q(`task_not_found`);if(i.status!==`doing`)return Q(`task_not_doing`);if(i.acceptanceCriteria.length===0)return Q(`missing_acceptance_criteria`);let a=Lp(n.evidenceRefs,n.acceptanceEvidence);if(a.length===0)return Q(`missing_evidence_refs`);let o=i.acceptanceCriteria.filter(e=>e.required!==!1),s=new Map;for(let e of n.acceptanceEvidence??[])s.set(e.criterionId,e.evidenceRefs??[]);for(let e of o)if((s.get(e.id)??[]).length===0)return Q(`missing_required_acceptance_evidence`,{criterionId:e.id});let c=await br(e.dataDir,e.sessionId,a,Z(e));if(!c.valid)return Pp(c);if(i.kind===`clarify`){if(!zp(r))return Q(`missing_executable_followup_task`);if(!a.some(e=>e.startsWith(`note:`)||e.startsWith(`manual:`)))return Q(`clarify_requires_note_or_manual_evidence`)}let l=new Date().toISOString(),u={};for(let e of n.acceptanceEvidence??[])u[e.criterionId]=e.evidenceRefs??[];let d=r.tasks.map(e=>e.id===i.id?{...e,status:`done`,acceptanceEvidence:Object.keys(u),evidenceRefs:a,updatedAt:l}:e),f=d.find(e=>e.status===`todo`&&e.required!==!1),p=d.map(e=>f&&e.id===f.id?{...e,status:`doing`,updatedAt:l}:e),m={...r,tasks:p,currentTaskId:f?.id??null,status:`active`,blockedReason:null,updatedAt:l};await Dr(e.dataDir,e.sessionId,{type:`goal_task_done`,goalId:r.goalId,taskId:i.id,summary:n.summary,acceptanceEvidence:n.acceptanceEvidence,evidenceRefs:a},Z(e));let h=await Cr(e.dataDir,e.sessionId,Z(e));await Tr(e.dataDir,e.sessionId,{progressLog:[...h.progressLog??[],`${l.slice(0,16).replace(`T`,` `)}: ${n.summary??`Completed ${i.id}`}`],criterionEvidence:{[i.id]:Object.keys(u)},evidence:a},Z(e));let{planWarning:g}=await Vp(e,m);return xp({ok:!0,currentTaskId:m.currentTaskId,hint:m.currentTaskId?null:`All tasks done. Call goal_complete with finalEvidenceRefs.`,warning:g??null})})}}}function Wp(e){return{name:`goal_task_blocked`,label:`Goal Task Blocked`,description:`Mark a task and the workflow as blocked without changing goal/goal.json status.`,parameters:J.Object({taskId:J.String(),reason:J.String(),neededInput:J.Optional(J.String()),evidenceRefs:J.Optional(J.Array(J.String()))}),async execute(t,n){return Sp(e,async()=>{let t=await Cp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return wp();let r=t,i=Rp(r,n.taskId);if(!i)return Q(`task_not_found`);let a=n.evidenceRefs??[];if(a.length>0){let t=await br(e.dataDir,e.sessionId,a,{...Z(e),requireCommandSuccess:!1});if(!t.valid)return Q(t.errors[0]?.code??`invalid_evidence`,{errors:t.errors})}let o=new Date().toISOString(),s=n.neededInput?`${n.reason} (needed: ${n.neededInput})`:n.reason,c=r.tasks.map(e=>e.id===i.id?{...e,status:`blocked`,blockedReason:s,updatedAt:o}:e),l={...r,status:`blocked`,blockedReason:s,currentTaskId:i.id,tasks:c,updatedAt:o};await Dr(e.dataDir,e.sessionId,{type:`goal_task_blocked`,goalId:r.goalId,taskId:i.id,reason:n.reason,neededInput:n.neededInput,evidenceRefs:a},Z(e)),await Tr(e.dataDir,e.sessionId,{risks:[s]},Z(e));let{planWarning:u}=await Vp(e,l);return xp({ok:!0,workflowStatus:`blocked`,warning:u??null})})}}}function Gp(e){return{name:`goal_add_task`,label:`Goal Add Task`,description:`Add a new execution task to goal/state.json. Concurrent calls in the same turn are serialized; add tasks one at a time or rely on the store lock.`,parameters:J.Object({title:J.String(),kind:J.Optional(J.Literal(`execution`)),required:J.Optional(J.Boolean()),acceptanceCriteria:J.Array(J.Union([J.String(),J.Object({text:J.String(),required:J.Optional(J.Boolean())})])),afterTaskId:J.Optional(J.String()),startNow:J.Optional(J.Boolean())}),async execute(t,n){return Sp(e,async()=>{let t=await Cp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return wp();let r=t;if((n.kind??`execution`)!==`execution`)return Q(`invalid_task_kind`);if(n.acceptanceCriteria.length===0)return Q(`missing_acceptance_criteria`);let i=new Date().toISOString(),a=Or(r.tasks),o=Ip(n.acceptanceCriteria),s={id:a,kind:`execution`,title:n.title.trim(),required:n.required!==!1,status:n.startNow?`doing`:`todo`,acceptanceCriteria:o,acceptanceEvidence:[],evidenceRefs:[],blockedReason:null,updatedAt:i},c=[...r.tasks];if(n.afterTaskId){let e=c.findIndex(e=>e.id===n.afterTaskId);if(e<0)return Q(`after_task_not_found`);c.splice(e+1,0,s)}else c.push(s);n.startNow&&(c=c.map(e=>e.id===a?s:e.status===`doing`?{...e,status:`todo`,updatedAt:i}:e));let l={...r,tasks:c,currentTaskId:n.startNow?a:r.currentTaskId,updatedAt:i};await Dr(e.dataDir,e.sessionId,{type:`goal_task_added`,goalId:r.goalId,taskId:a,kind:`execution`,required:s.required,acceptanceCriteria:o},Z(e));let{planWarning:u}=await Vp(e,l);return xp({ok:!0,taskId:a,warning:u??null})})}}}function Kp(e){return{name:`goal_record_evidence`,label:`Goal Record Evidence`,description:`Record note/manual/exec/snapshot evidence and return an evidenceRef for goal_task_done or goal_complete.`,parameters:J.Object({kind:J.Union([J.Literal(`note`),J.Literal(`manual`),J.Literal(`exec`),J.Literal(`snapshot`)]),summary:J.Optional(J.String()),content:J.Optional(J.String()),taskId:J.Optional(J.String()),source:J.Optional(J.String()),command:J.Optional(J.String()),cwd:J.Optional(J.String()),timeoutMs:J.Optional(J.Number()),path:J.Optional(J.String())}),async execute(t,n){let r=await Cp(e);if(r===null)return Q(`workflow_not_initialized`);if(`corrupt`in r)return wp();let i=r;if(n.kind===`note`||n.kind===`manual`){if(!n.summary?.trim())return Q(`missing_summary`);if(!n.content?.trim())return Q(`missing_content`);let t=await Ar(e.dataDir,e.sessionId,{kind:n.kind,summary:n.summary,content:n.content,source:n.source},Z(e));return`error`in t?t.error===`manual evidence requires source`?Fp(n.summary,n.content):Q(t.error):(await Dr(e.dataDir,e.sessionId,{type:`goal_note_recorded`,goalId:i.goalId,taskId:n.taskId,evidenceRef:t.evidenceRef,kind:n.kind,summary:n.summary,source:n.source??`model`},Z(e)),xp({ok:!0,evidenceRef:t.evidenceRef}))}if(n.kind===`exec`){if(!n.command?.trim())return Q(`missing_command`);let t=await jr(e.dataDir,e.sessionId,{command:n.command,cwd:n.cwd,timeoutMs:n.timeoutMs,workspaceDir:yp(e),allowedRoots:bp(e),baseEnv:e.baseEnv},Z(e));return`error`in t?Q(t.error):(await Dr(e.dataDir,e.sessionId,{type:`goal_command_recorded`,goalId:i.goalId,evidenceRef:t.evidenceRef,command:n.command,cwd:n.cwd??yp(e),exitCode:t.exitCode},Z(e)),xp({ok:!0,evidenceRef:t.evidenceRef,exitCode:t.exitCode}))}if(!n.path?.trim())return Q(`missing_path`);let a=await Nr(e.dataDir,e.sessionId,{path:n.path,summary:n.summary,workspaceDir:yp(e),allowedRoots:bp(e)},Z(e));return`error`in a?Q(a.error):(await Dr(e.dataDir,e.sessionId,{type:`goal_snapshot_recorded`,goalId:i.goalId,evidenceRef:a.evidenceRef,path:n.path},Z(e)),xp({ok:!0,evidenceRef:a.evidenceRef}))}}}function qp(e){return{name:`goal_complete`,label:`Goal Complete`,description:`Complete the goal after all required tasks are done and final evidence is recorded.`,parameters:J.Object({summary:J.String(),finalEvidenceRefs:J.Array(J.String()),risks:J.Optional(J.Array(J.String()))}),async execute(t,n){return Sp(e,async()=>{let t=await Cp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return wp();let r=t,i=r.tasks.filter(e=>e.required!==!1),a=i.filter(e=>e.status!==`done`);if(a.length>0)return Q(`required_tasks_not_done`,{pendingTaskIds:a.map(e=>e.id)});if(i.filter(e=>e.status===`blocked`).length>0)return Q(`blocked_tasks_remain`);for(let e of i)if((e.evidenceRefs??[]).length===0)return Q(`done_task_missing_evidence`,{taskId:e.id});if(n.finalEvidenceRefs.length===0)return Q(`missing_final_evidence_refs`);let o=await br(e.dataDir,e.sessionId,n.finalEvidenceRefs,Z(e));if(!o.valid)return Pp(o);let s=new Date().toISOString(),c={...r,status:`complete`,finalEvidenceRefs:n.finalEvidenceRefs,completedAt:s,currentTaskId:null,updatedAt:s};if(!await U(e.dataDir,e.sessionId,Z(e)))return Q(`goal_not_found`);await Sr(e.dataDir,e.sessionId,c,Z(e));try{await H(e.dataDir,e.sessionId,{status:`complete`},{...Z(e),eventSource:`tool`})}catch(t){throw await Sr(e.dataDir,e.sessionId,r,Z(e)),t}return await Dr(e.dataDir,e.sessionId,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:n.finalEvidenceRefs,summary:n.summary,risks:n.risks??[]},Z(e)),await Tr(e.dataDir,e.sessionId,{finalSummary:n.summary,evidence:n.finalEvidenceRefs,risks:n.risks},Z(e)),xp({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,warning:Bp(await Er(e.dataDir,e.sessionId,c,Z(e)))})})}}}function Jp(e){return{name:`goal_repair_workflow_state`,label:`Goal Repair Workflow State`,description:`Reinitialize unreadable goal/state.json from the saved objective. Requires confirm:true.`,parameters:J.Object({confirm:J.Literal(!0)}),async execute(t,n){return xp(await Sp(e,()=>Yn(e.dataDir,e.sessionId,Z(e))))}}}function Yp(e){return[Hp(e),Gp(e),Kp(e),Up(e),Wp(e),Jp(e),qp(e)]}var Xp=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=q.resolve(e.rootDir??Wi(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=Yi(e.path),n=nm(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 la(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:Gi(this.rootDir)}}async createSkill(e){let t=Xi(e.name),n=Yi(e.categoryPath),r=nm(e.description,`auto-skill description`),i=rm(e.body);await this.assertCategoryExists(n);let a=Zi(n,t),o=ea(this.rootDir,n,t);if(await em(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=q.join(o,`SKILL.md`),l=q.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:im(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:am(e.evidence,s)};return await K.mkdir(o,{recursive:!0}),await K.writeFile(c,Zp(t,r,i),`utf-8`),await tm(l,u),await la(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=Qi(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=ea(this.rootDir,t.categoryPath,t.skillName),r=q.join(n,`SKILL.md`),i=q.join(n,`metadata.json`),a=await Qp(r),o=await $p(i),s=e.description===void 0?a.description:nm(e.description,`auto-skill description`),c=e.body===void 0?a.body:rm(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?im(o.tags):im(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:{},...am(e.evidence,l)}};return await K.writeFile(r,Zp(t.skillName,s,c),`utf-8`),await tm(i,u),await la(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=Qi(e.skillId),n=ea(this.rootDir,t.categoryPath,t.skillName),r=q.join(n,`metadata.json`),i=q.join(n,`SKILL.md`);await K.access(i);let a=await $p(r),o=this.now().toISOString();return await tm(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...am(e.evidence,o)}}),await la(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=Gi(this.rootDir),t;try{t=await K.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=Yi(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 K.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await tm(Gi(this.rootDir),t)}};function Zp(e,t,n){return[`---`,`name: ${om(e)}`,`description: ${om(t)}`,`---`,``,n.trim(),``].join(`
87
- `)}async function Qp(e){let t=zt(await K.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function $p(e){let t;try{t=await K.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 em(e){try{return await K.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function tm(e,t){await K.mkdir(q.dirname(e),{recursive:!0}),await K.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function nm(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function rm(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 im(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function am(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function om(e){return JSON.stringify(e)}const sm=[`create`,`update`,`archive`,`create_category`],cm=J.Object({}),lm=J.Object({categoryPath:J.Optional(J.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:J.Optional(J.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),um=J.Object({query:J.String({description:`Search query for learned auto-skills.`}),limit:J.Optional(J.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),dm=J.Object({skillId:J.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:J.Optional(J.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),fm=J.Object({action:J.Union(sm.map(e=>J.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:J.Optional(J.String({description:`Exact auto-skill id for update/archive.`})),name:J.Optional(J.String({description:`Auto-skill slug for create.`})),categoryPath:J.Optional(J.String({description:`Existing single-level category slug for create.`})),newCategory:J.Optional(J.Object({path:J.String({description:`New single-level category slug to create.`}),description:J.String({description:`New category description.`})})),description:J.Optional(J.String({description:`Auto-skill description for create/update.`})),tags:J.Optional(J.Array(J.String({description:`Auto-skill tag.`}))),confidence:J.Optional(J.Number({description:`Optional confidence score from 0 to 1.`})),body:J.Optional(J.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:J.Optional(J.Object({sessionId:J.String({description:`Source session id.`}),reason:J.String({description:`Why this auto-skill write is justified.`}),toolCallCount:J.Optional(J.Number({description:`Tool calls observed in source run.`})),loadedSkills:J.Optional(J.Array(J.String({description:`Skill loaded during source run.`})))}))});function pm(e){let t=new ua({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:cm,async execute(){try{let e=await t.autoSkillCategories();return $({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return $({categories:[],count:0,error:ym(e)})}}}}function mm(e){let t=new ua({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 $({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return $({skills:[],count:0,error:ym(e)})}}}}function hm(e){let t=new ua({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:um,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return $({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return $({skills:[],count:0,error:ym(e)})}}}}function gm(e){let t=new ua({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:dm,async execute(e,n){try{return $({...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 $({skillId:n.skillId,error:ym(e)})}}}}function _m(e){let t=new Xp({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:fm,async execute(e,n){try{return $(await vm(t,n))}catch(e){return $({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:ym(e)})}}}}async function vm(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 $(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 bm=2,xm=5;var Sm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),G.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:Te(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&&G.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`){G.info(`subagent status changed`,t);return}if(e.status===`killed`){G.warn(`subagent status changed`,t);return}G.error(`subagent status changed`,t)}};const Cm=J.Object({task:J.String({description:`The task description for the subagent to execute`}),label:J.Optional(J.String({description:`Optional short label to identify this subagent`})),agent:J.Optional(J.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.`}))}),wm=J.Object({task:J.String({description:`The task description for the subagent to execute`}),label:J.Optional(J.String({description:`Optional short label to identify this subagent`})),agent:J.Optional(J.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.`}))}),Tm=J.Object({tasks:J.Array(Cm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Em(e){let t=e.label?`"${e.label}"`:`task: ${Ot(e.task)}`;return e.status===`done`?`${t}\n\n${Dm(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Dm(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 Om(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(G.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:Te(p)}),!p){let e={status:`error`,error:`task must not be empty`};return G.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 G.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Ft(),v=new AbortController,y=t,b=Ba(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return G.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 G.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}G.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?Ka(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),G.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,G.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=Em({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 G.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 G.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 km(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:wm,async execute(e,t){return Om(u,e,t)}}}function Am(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:Tm,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}}G.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 Om(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${Dm(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
88
-
89
- `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const jm=J.Object({action:J.Union([`list`,`kill`].map(e=>J.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:J.Optional(J.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Mm(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 Nm(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 Pm(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:jm,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} (${Mm(e.runtimeMs)})${n}`})).join(`
90
- `)};return{content:[{type:`text`,text:JSON.stringify(n)}],details:n}}if(i===`kill`){let n=r.target?.trim();if(!n||n===`*`||n===`all`){let n=e.killAll(t),r={action:`kill`,killed:n,text:n>0?`Killed ${n} subagent(s).`:`No running subagents to kill.`};return{content:[{type:`text`,text:JSON.stringify(r)}],details:r}}let i=Nm(o,n);if(!i){let e={action:`kill`,killed:0,error:`No subagent found matching "${n}". Use list to see available subagents.`,text:`Error: no subagent matching "${n}"`};return{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let a=e.kill(i.runId),s=i.label??i.task.slice(0,40),c={action:`kill`,killed:a?1:0,text:a?`Killed subagent "${s}".`:`Subagent "${s}" is already finished.`};return{content:[{type:`text`,text:JSON.stringify(c)}],details:c}}let s={action:i,error:`Unsupported action.`,text:`Error: unsupported action.`};return{content:[{type:`text`,text:JSON.stringify(s)}],details:s}}}}const Fm=J.Object({image:J.String({description:`Image path or URL`}),prompt:J.Optional(J.String({description:`Prompt for image analysis`})),model:J.Optional(J.String({description:`Optional model override`})),maxBytesMb:J.Optional(J.Number({description:`Optional size cap in MB`}))});function Im(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Fm,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}}}}function Lm(e,t){let n=pp({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??Pn(),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=[sd({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),dd({registry:i,scopeKey:n}),vd(n,t?.contextManager),bd(n,t?.contextManager,s),Sd(n,t?.contextManager,s),wd(n),jd(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[lp(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),...Yp({dataDir:e,sessionId:t.sessionId,sessionStoreName:t.inheritedRunParams?.sessionStoreName,projectDir:t.inheritedRunParams?.projectDir,baseEnv:t.baseEnv})]:[],rf(e,r),Ef(e,r),of(e,r),uf(e,r),vf(e,r),bf(e,r),Sf(e,r),wf(e,r),op(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),sp({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(pm(e),mm(e),hm(e),gm(e)),t&&c.push(km(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Am(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Pm(t.registry,t.parentSessionId)),c}function Rm(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(`
86
+ `)}\n</available_skills>`}const Rf=J.Object({category:J.Optional(J.String({description:`Reserved category filter field. Not used yet.`}))}),zf=J.Object({name:J.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:J.Optional(J.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Bf(e,t,n=[]){return[...n,...t,Tf(e)]}function Vf(e,t,n=[]){let r=Bf(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Rf,async execute(e,t){let n=await Nf(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 Hf(e){let t=Bf(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:zf,async execute(r,i){let a=await If(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 Uf=J.Object({status:J.Union([J.Literal(`complete`),J.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:J.Optional(J.String({description:`Required for complete: concise final summary of what was achieved.`})),reason:J.Optional(J.String({description:`Required for blocked: concise reason the goal cannot continue.`})),neededInput:J.Optional(J.String({description:`For blocked: exact user input or external condition needed to proceed.`})),risks:J.Optional(J.Array(J.String({description:`Residual risk or follow-up note.`})))});function Wf(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function Gf(e,t){return Wf({ok:!1,error:e,...t})}function Kf(e){return`warning`in e?e.warning:null}function Z(e){return{storeName:e}}async function qf(e,t,n){try{return await Jn(e,t,Z(n))}catch(e){if(e instanceof Rn)return{corrupt:!0};throw e}}function Jf(e,t,n){return{...e,status:`complete`,currentTaskId:null,blockedReason:null,finalEvidenceRefs:[t],completedAt:n,updatedAt:n,tasks:e.tasks.map(e=>e.required===!1||e.status===`done`?e:{...e,status:`done`,blockedReason:null,acceptanceEvidence:e.acceptanceCriteria.map(e=>e.id),evidenceRefs:[t],updatedAt:n})}}function Yf(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 Xf(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:Uf,async execute(r,i){let a=await U(e,t,Z(n));return a?a.status===`complete`?Wf({ok:!0,goalStatus:`complete`,alreadyComplete:!0}):Vn(e,t,Z(n),async()=>{let r=await qf(e,t,n);if(r===null)return Gf(`workflow_not_initialized`);if(`corrupt`in r)return Gf(`workflow_corrupt`);let o=new Date().toISOString();if(i.status===`blocked`){let s=i.reason?.trim();if(!s)return Gf(`missing_reason`);let c=Yf(r,s,i.neededInput,o);await lr(e,t,c,Z(n)),await mr(e,t,{type:`goal_task_blocked`,goalId:r.goalId,taskId:r.currentTaskId??void 0,reason:s,neededInput:i.neededInput,evidenceRefs:[]},Z(n)),await fr(e,t,{risks:[c.blockedReason??s]},Z(n));let l=await pr(e,t,c,Z(n));return Wf({ok:!0,goalStatus:a.status,workflowStatus:`blocked`,warning:Kf(l)})}let s=i.summary?.trim();if(!s)return Gf(`missing_summary`);let c=await hr(e,t,{kind:`manual`,summary:`Goal completion summary`,content:s,source:`model`},Z(n));if(`error`in c)return Gf(c.error);let l=Jf(r,c.evidenceRef,o);await lr(e,t,l,Z(n));try{await H(e,t,{status:`complete`},{...Z(n),eventSource:`tool`})}catch(i){throw await lr(e,t,r,Z(n)),i}await mr(e,t,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:[c.evidenceRef],summary:s,risks:i.risks??[]},Z(n)),await fr(e,t,{finalSummary:s,evidence:[c.evidenceRef],risks:i.risks},Z(n));let u=await pr(e,t,l,Z(n));return Wf({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,evidenceRef:c.evidenceRef,warning:Kf(u)})}):Gf(`goal_not_found`)}}}J.Object({}),J.Object({status:J.String({description:`Status to set. Only 'complete' is allowed.`})});const Zf=J.Union([J.Literal(`pending`),J.Literal(`in_progress`),J.Literal(`completed`)]),Qf=J.Object({explanation:J.Optional(J.String({description:`Optional short explanation for why the plan is being updated.`})),tasks:J.Array(J.Object({content:J.String({description:`Short user-visible task description.`}),status:Zf}),{description:`Full current task list snapshot in display order.`})}),$f=new Set([`pending`,`in_progress`,`completed`]);function ep(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:e}}function tp(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(!$f.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 np(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
+
88
+ Use this tool when:
89
+ - The user request has multiple meaningful steps or phases.
90
+ - The work spans several files, checks, or decisions.
91
+ - Before starting non-trivial multi-step work, publish an initial plan with the first step \`in_progress\` and later steps \`pending\`.
92
+ - The user explicitly asks for a plan, TODOs, or progress tracking.
93
+ - The user asks to proceed step by step, keep a checklist, or update progress after each step/file/check.
94
+ - The current plan changes in a way the user should see.
95
+ - You finish one planned phase and move to the next.
96
+
97
+ Do not use this tool when:
98
+ - The request is a simple question or conversational reply.
99
+ - The work is a single straightforward command or tiny edit.
100
+ - Tracking would add noise instead of clarity.
101
+ - You are only doing a small mechanical action inside an existing step.
102
+
103
+ Rules:
104
+ - Submit the full current task list on every call.
105
+ - Keep tasks short, concrete, and user-visible.
106
+ - Use at most one \`in_progress\` task at a time.
107
+ - Mark a task \`completed\` only after the work is actually done.
108
+ - Move the next active task to \`in_progress\` when continuing.
109
+ - If the user asks for progress after each named step/file/check, update immediately after each one completes; do not batch several completed steps into one late update.
110
+ - If you skipped an earlier update, publish the current honest state and continue with per-step updates instead of retroactively pretending progress was tracked.
111
+ - Before the final response, publish a final snapshot when an active plan has changed or should be marked complete.
112
+ - Do not update for tiny internal actions inside one planned step.
113
+
114
+ Numbered/Listed Step Protocol:
115
+ - For explicit numbered or bulleted steps from the user, treat each listed item as a user-visible task.
116
+ - The initial \`update_task\` call must include the ordered list with the first task \`in_progress\` and later tasks \`pending\`.
117
+ - 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\`.
118
+ - Never start work for task N+1 while task N is still \`in_progress\`.
119
+ - Do not mark multiple newly completed listed tasks in one update unless they were completed by the same single tool result.`,parameters:Qf,async execute(t,n){let r=tp(n);return r.ok===!1?ep({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()}),ep({ok:!0,updated:!0,taskCount:r.tasks.length}))}}}var rp=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=q.resolve(e.rootDir??Ei(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=Y(e.path),n=lp(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 Wi(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:Di(this.rootDir)}}async createSkill(e){let t=ji(e.name),n=Y(e.categoryPath),r=lp(e.description,`auto-skill description`),i=up(e.body);await this.assertCategoryExists(n);let a=Mi(n,t),o=Fi(this.rootDir,n,t);if(await sp(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=q.join(o,`SKILL.md`),l=q.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:dp(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:fp(e.evidence,s)};return await K.mkdir(o,{recursive:!0}),await K.writeFile(c,ip(t,r,i),`utf-8`),await cp(l,u),await Wi(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=Ni(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Fi(this.rootDir,t.categoryPath,t.skillName),r=q.join(n,`SKILL.md`),i=q.join(n,`metadata.json`),a=await ap(r),o=await op(i),s=e.description===void 0?a.description:lp(e.description,`auto-skill description`),c=e.body===void 0?a.body:up(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?dp(o.tags):dp(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:{},...fp(e.evidence,l)}};return await K.writeFile(r,ip(t.skillName,s,c),`utf-8`),await cp(i,u),await Wi(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=Ni(e.skillId),n=Fi(this.rootDir,t.categoryPath,t.skillName),r=q.join(n,`metadata.json`),i=q.join(n,`SKILL.md`);await K.access(i);let a=await op(r),o=this.now().toISOString();return await cp(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...fp(e.evidence,o)}}),await Wi(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=Di(this.rootDir),t;try{t=await K.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=Y(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await K.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await cp(Di(this.rootDir),t)}};function ip(e,t,n){return[`---`,`name: ${pp(e)}`,`description: ${pp(t)}`,`---`,``,n.trim(),``].join(`
120
+ `)}async function ap(e){let t=zt(await K.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function op(e){let t;try{t=await K.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 sp(e){try{return await K.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function cp(e,t){await K.mkdir(q.dirname(e),{recursive:!0}),await K.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function lp(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function up(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 dp(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function fp(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function pp(e){return JSON.stringify(e)}const mp=[`create`,`update`,`archive`,`create_category`],hp=J.Object({}),gp=J.Object({categoryPath:J.Optional(J.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:J.Optional(J.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),_p=J.Object({query:J.String({description:`Search query for learned auto-skills.`}),limit:J.Optional(J.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),vp=J.Object({skillId:J.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:J.Optional(J.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),yp=J.Object({action:J.Union(mp.map(e=>J.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:J.Optional(J.String({description:`Exact auto-skill id for update/archive.`})),name:J.Optional(J.String({description:`Auto-skill slug for create.`})),categoryPath:J.Optional(J.String({description:`Existing single-level category slug for create.`})),newCategory:J.Optional(J.Object({path:J.String({description:`New single-level category slug to create.`}),description:J.String({description:`New category description.`})})),description:J.Optional(J.String({description:`Auto-skill description for create/update.`})),tags:J.Optional(J.Array(J.String({description:`Auto-skill tag.`}))),confidence:J.Optional(J.Number({description:`Optional confidence score from 0 to 1.`})),body:J.Optional(J.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:J.Optional(J.Object({sessionId:J.String({description:`Source session id.`}),reason:J.String({description:`Why this auto-skill write is justified.`}),toolCallCount:J.Optional(J.Number({description:`Tool calls observed in source run.`})),loadedSkills:J.Optional(J.Array(J.String({description:`Skill loaded during source run.`})))}))});function bp(e){let t=new Gi({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:hp,async execute(){try{let e=await t.autoSkillCategories();return Q({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return Q({categories:[],count:0,error:Ep(e)})}}}}function xp(e){let t=new Gi({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:gp,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return Q({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Q({skills:[],count:0,error:Ep(e)})}}}}function Sp(e){let t=new Gi({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:_p,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return Q({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return Q({skills:[],count:0,error:Ep(e)})}}}}function Cp(e){let t=new Gi({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:vp,async execute(e,n){try{return Q({...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 Q({skillId:n.skillId,error:Ep(e)})}}}}function wp(e){let t=new rp({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:yp,async execute(e,n){try{return Q(await Tp(t,n))}catch(e){return Q({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:Ep(e)})}}}}async function Tp(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 Q(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Ep(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const Dp=2,Op=5;var kp=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),G.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:Te(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&&G.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`){G.info(`subagent status changed`,t);return}if(e.status===`killed`){G.warn(`subagent status changed`,t);return}G.error(`subagent status changed`,t)}};const Ap=J.Object({task:J.String({description:`The task description for the subagent to execute`}),label:J.Optional(J.String({description:`Optional short label to identify this subagent`})),agent:J.Optional(J.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.`}))}),jp=J.Object({task:J.String({description:`The task description for the subagent to execute`}),label:J.Optional(J.String({description:`Optional short label to identify this subagent`})),agent:J.Optional(J.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.`}))}),Mp=J.Object({tasks:J.Array(Ap,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Np(e){let t=e.label?`"${e.label}"`:`task: ${Ot(e.task)}`;return e.status===`done`?`${t}\n\n${Pp(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Pp(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 Fp(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(G.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:Te(p)}),!p){let e={status:`error`,error:`task must not be empty`};return G.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 G.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=Ft(),v=new AbortController,y=t,b=xa(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return G.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 G.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}G.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?Da(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),G.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,G.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=Np({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 G.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 G.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 Ip(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:jp,async execute(e,t){return Fp(u,e,t)}}}function Lp(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:Mp,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}}G.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 Fp(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${Pp(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
121
+
122
+ `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const Rp=J.Object({action:J.Union([`list`,`kill`].map(e=>J.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:J.Optional(J.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function zp(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 Bp(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 Vp(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:Rp,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} (${zp(e.runtimeMs)})${n}`})).join(`
123
+ `)};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=Bp(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 Hp(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 Up(e){let t=Hp(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=q.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 Wp(e){let t=e.watchFactory??((e,t,n)=>Ht.watch(e,t,n)),n=q.join(e.dataDir,`.aimax`),r=[{target:q.join(n,`MEMORY.md`),kind:`memory-file`},{target:q.join(n,`memory.md`),kind:`memory-file-lower`},{target:q.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=Up({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 Gp(e){return e.projectDir?.trim()||q.join(e.dataDir,`workspace`)}async function Kp(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Gp(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Xp(e.files);if(c.length===0)return;let d=e.reason===`external-watch`&&e.source===`memory`?c.filter(e=>t-(l.get(e.toLowerCase())??0)>3e3):c;if(d.length===0)return;if(e.reason!==`external-watch`&&e.source===`memory`)for(let e of d)l.set(e.toLowerCase(),t);let f=`${e.reason}|${e.source}|${d.map(e=>e.toLowerCase()).sort().join(`|`)}`;if(t-(u.get(f)??0)<1e3)return;u.set(f,t);let p={...e,files:d};if(p.reason===`appendRecent_route`||p.reason===`appendRecent_fallback`){let t=p.files.join(`, `),r=p.reason===`appendRecent_fallback`;await n.dispatchDiagnostic(e.sessionId??i,{level:r?`warn`:`info`,scope:`memory`,phase:p.reason,message:r?`memory_log fallback: wrote MEMORY.md instead of daily log (provider=${p.providerId??g.id})`:`memory_log routed to ${t} (provider=${p.providerId??g.id})`,details:{providerId:p.providerId??g.id,resolvedProviderId:m?.registration.id??g.id,requestedProviderId:o,requestedPluginId:s,target:t,supportsAppendRecent:typeof g.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=q.join(t.dataDir,`.aimax`),m=Qe({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g,_,v,y,b,x;if(m?.provider)g=m.provider,_=m.registration.id,v=m.registration.pluginId,y=`plugin`,b=!1;else{try{g=Ke({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName},{includeSessions:!0})}catch(e){if(!Ue(e))throw e;x=e instanceof Error?e.message:String(e),g=qp(p,x)}_=g.id,v=void 0,y=`builtin`,b=!0}x&&await n.dispatchDiagnostic(i,{level:`warn`,scope:`memory`,phase:`memory_provider_degraded`,message:`builtin memory provider degraded after sqlite index failure`,details:{providerId:_,requestedProviderId:o,requestedPluginId:s,error:x}}).catch(()=>{}),await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:y,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:b}}).catch(()=>{});let S=Wp({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let C=async e=>{await h(t.dataDir,i,e,Yp({sessionOptions:$(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,memoryProvider:g,memoryProviderSource:y,memoryFallbackToBuiltin:b,recallState:{recallProvided:!1},compactionRecallState:{recallProvided:!1},appendTranscriptEntry:C,persistInitialUserEntry:async e=>d?!1:(await C({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{S()}}}function qp(e,t){return{id:`builtin-memory`,name:`Builtin Memory Provider (degraded)`,status:()=>({backend:`builtin`,provider:`builtin-memory`,workspaceDir:e,dbPath:q.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 Jp(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Yp(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 Xp(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 Zp=J.Object({image:J.String({description:`Image path or URL`}),prompt:J.Optional(J.String({description:`Prompt for image analysis`})),model:J.Optional(J.String({description:`Optional model override`})),maxBytesMb:J.Optional(J.Number({description:`Optional size cap in MB`}))});function Qp(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Zp,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 $p(e,t){let n=Gp({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??Pn(),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=[Hu({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),Ku({registry:i,scopeKey:n}),$u(n,t?.contextManager),td(n,t?.contextManager,s),rd(n,t?.contextManager,s),ad(n),fd(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),np({reportTaskUpdated:t?.reportTaskUpdated}),...t?.sessionId?[Xf(e,t.sessionId,t.inheritedRunParams?.sessionStoreName)]:[],Rd(e,r),sf(e,r),Bd(e,r),Wd(e,r),Qd(e,r),ef(e,r),nf(e,r),af(e,r),Vf(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Hf({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(bp(e),xp(e),Sp(e),Cp(e)),t&&c.push(Ip(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Lp(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Vp(t.registry,t.parentSessionId)),c}function em(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(`
91
124
  `),`</auto_skill_categories>`,``].join(`
92
- `)}const zm={get_goal:`Get the current thread goal including status, budget, usage, and workflow summary`,goal_plan_update:`Update controlled planning sections without changing workflow task state`,goal_add_task:`Add an execution task with acceptance criteria to the goal workflow`,goal_record_evidence:`Record note/manual/exec/snapshot evidence and return an evidenceRef`,goal_task_done:`Mark the current task done with evidence covering required acceptance criteria`,goal_task_blocked:`Mark the current task and workflow blocked with a clear reason`,goal_repair_workflow_state:`Repair corrupt goal workflow state from the saved objective`,goal_complete:`Complete the goal after required tasks and final evidence are recorded`,read_file:`Read file contents`,write_file:`Create or overwrite files`,edit_file:`Make precise edits to files`,list_dir:`List directory contents`,apply_patch:`Apply multi-file patches`,exec:`Run shell commands`,process:`Manage background exec sessions`,skill_list:`List available skills with compact metadata`,skill_load:`Load a skill's SKILL.md entrypoint`,auto_skill_categories:`List learned auto-skill categories`,auto_skill_list:`List active learned auto-skills by category`,auto_skill_search:`Search active learned auto-skills`,auto_skill_view:`Load an active learned auto-skill by exact skillId`,memory_search:`Search durable Markdown memory (MEMORY.md, memory/ logs) for stable facts and policies; not for cross-session chat timelines (use session_search for transcripts).`,memory_get:`Fetch a specific memory entry's content by its ID`,memory_write:`Write or update a section in long-term memory (MEMORY.md). Omit section for flat append.`,memory_log:`Append a timestamped note to today's daily log`,memory_list:`List all stored memories`,memory_forget:`Delete a specific memory by its ID, or delete matching memories by query`,memory_update:`Update the content of an existing memory by its ID`,session_search:`Search past conversation transcripts across sessions (recent browse or keyword query). For cross-session recall; use memory_search for durable docs and policies.`,subagent_spawn:`Spawn an isolated subagent session`,subagents:`List, steer, or kill subagent runs`},Bm=`read_file.write_file.edit_file.list_dir.apply_patch.exec.process.skill_list.skill_load.get_goal.goal_plan_update.goal_add_task.goal_record_evidence.goal_task_done.goal_task_blocked.goal_repair_workflow_state.goal_complete.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 Vm(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:[...Bm.filter(e=>t.has(e)),...n.filter(e=>!Bm.includes(e)).sort()],displayName:t}}function Hm(e){let{ordered:t,displayName:n}=Vm(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)??zm[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
125
+ `)}const tm={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`,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`,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`},nm=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`update_task`,`skill_list`,`skill_load`,`goal`,`auto_skill_categories`,`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function rm(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:[...nm.filter(e=>t.has(e)),...n.filter(e=>!nm.includes(e)).sort()],displayName:t}}function im(e){let{ordered:t,displayName:n}=rm(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)??tm[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
93
126
  `),``].join(`
94
- `)}function Um(){return[`## Thread Goal`,`This session may have a thread goal set by the user via the CLI. The goal represents the`,`objective the user wants to pursue across multiple turns.`,``,`Rules:`,"- Use `get_goal` to view the current goal, its status, budget, usage, and V2-lite workflow summary (`goalState`).",`- You CANNOT create or edit the goal objective. Only the user can set or change the goal via the CLI.`,"- When V2-lite workflow is active, complete tasks with `goal_task_done` and finish the goal with `goal_complete` (with evidence refs).","- Use `goal_record_evidence` to create evidence refs before filling `evidenceRefs`, `acceptanceEvidence`, or `finalEvidenceRefs`.","- Do NOT call `goal_complete` merely because the budget is nearly exhausted or work is paused.",`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, `get_goal` returns null and goal workflow tools report an error.",``].join(`
95
- `)}function Wm(){return[`## Safety`,`You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.`,`Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards.`,`Do not attempt to bypass approvals, safety rails, or access boundaries.`,`Never print, reveal, or echo environment variable values. If configuration must be shown, use placeholders plus brief meanings instead, such as {{API_KEY}}: model access credential.`,``].join(`
96
- `)}function Gm(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
97
- `)}function Km(e){return e?``:[`## Tool Call Style`,`Default: call routine low-risk tools directly without narrating every step.`,`Narrate briefly when actions are sensitive, long-running, or likely surprising.`,`When approvals are required, keep the command text exact and complete.`,``].join(`
98
- `)}function qm(){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(`
99
- `)}function Jm(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(`
127
+ `)}function am(e,t){let n=t.toLowerCase();return e.some(e=>e.trim().toLowerCase()===n)}function om(e){return am(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(`
128
+ `):``}function sm(){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 })` only when the objective is genuinely achieved.','- 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(`
129
+ `)}function cm(){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(`
130
+ `)}function lm(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
131
+ `)}function um(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(`
132
+ `)}function dm(){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(`
133
+ `)}function fm(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(`
100
134
  `)).join(`
101
135
  `)}\n</available_skills>`,``].join(`
102
- `)}function Ym(e=[]){let t=Rm(e).trim();return t?`${t}\n`:``}function Xm(){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(`
103
- `)}function Zm(){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(`
104
- `)}function Qm(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(`
105
- `)}function $m(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(`
106
- `)}function eh(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(`
107
- `)}function th(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=nh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
108
- `)}function nh(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 rh(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(`
109
- `)}function ih(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(`
110
- `)}function ah(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(`
111
- `)}function oh(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(`
112
- `)}function sh(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(`
113
- `)}function ch(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(`
114
- `):``}function lh(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:[...Bm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,sh(e.subagentDepth??0),Hm({toolNames:i,toolSummaries:e.toolSummaries}),qm(),Km(n),Um(),Wm(),Ga(e.availableAgents??[]),Jm(a),Ym(e.autoSkillCategories),Xm(),Zm(),Qm(e.memoryCitationsMode??`off`),$m({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),eh(e.sandboxInfo),th({currentDate:e.currentDate,timezone:e.timezone}),Gm(),rh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),ah({isMinimal:n}),ih(e.runtimeInfo),oh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),ch(e.priorConversationSummary)].filter(Boolean).join(`
115
- `)}function uh(e,t,n){return e.map(e=>{let r=e,i=Fe(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await ue({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(Io(e))return Bo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function dh(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 fh(e,t){let n=e.content,r=gh(e.details),i=e.isError;for(let e of t)if(e){if(e.content!==void 0&&(n=ph(n,e.content)),e.details!==void 0){let t=gh(e.details);r={...r,...t}}e.isError===!0&&(i=!0)}return{content:n,details:r,isError:i}}function ph(e,t){return t===void 0?e:e===void 0?t:Array.isArray(e)&&Array.isArray(t)?mh(e,t)?t:[...e,...t]:t}function mh(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!hh(e[n],t[n]))return!1;return!0}function hh(e,t){return JSON.stringify(e)===JSON.stringify(t)}function gh(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function _h(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),Io(t))return Bo(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=dh(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(Io(e))return Bo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}let f=fh({content:a.content,details:u,isError:s},d),p=Math.max(0,Date.now()-l),m=f.isError?vh(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 vh(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(`
116
- `):void 0}var yh=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 bh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function xh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Sh(e){let t=xh(e?.warningThreshold,bh.warningThreshold),n=xh(e?.criticalThreshold,bh.criticalThreshold),r=xh(e?.globalCircuitBreakerThreshold,bh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??bh.enabled,historySize:xh(e?.historySize,bh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??bh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??bh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??bh.detectors.pingPong}}}function Ch(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function wh(e,t){return`${e}:${Dh(t)}`}function Th(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Th).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Th(t[e])}`).join(`,`)}}`}function Eh(e){try{return Th(e)}catch{return e==null?`${e}`:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:e instanceof Error?`${e.name}:${e.message}`:Object.prototype.toString.call(e)}}function Dh(e){let t=Eh(e);return Nt(`sha256`).update(t).digest(`hex`)}function Oh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Ch(t))return!1;let n=t.action;return n===`poll`||n===`log`}function kh(e){return!Ch(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Ch(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
117
- `).trim()}function Ah(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Th(e)}function jh(e,t,n,r){if(r!==void 0)return`error:${Dh(Ah(r))}`;if(!Ch(n))return n===void 0?void 0:Dh(n);let i=Ch(n.details)?n.details:{},a=kh(n);if(Oh(e,t)&&e===`process`&&Ch(t)){let e=t.action;if(e===`poll`)return Dh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Dh({action:e,status:i.status,totalLines:i.totalLines??null,totalChars:i.totalChars??null,truncated:i.truncated??null,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,text:a})}return Dh({details:i,text:a})}function Mh(e,t,n){let r=0,i;for(let a=e.length-1;a>=0;--a){let o=e[a];if(!(!o||o.toolName!==t||o.argsHash!==n)&&!(typeof o.resultHash!=`string`||!o.resultHash)){if(!i){i=o.resultHash,r=1;continue}if(o.resultHash!==i)break;r+=1}}return{count:r,latestResultHash:i}}function Nh(e,t){let n=e.at(-1);if(!n)return{count:0,noProgressEvidence:!1};let r,i;for(let t=e.length-2;t>=0;--t){let a=e[t];if(a&&a.argsHash!==n.argsHash){r=a.argsHash,i=a.toolName;break}}if(!r||!i)return{count:0,noProgressEvidence:!1};let a=0;for(let t=e.length-1;t>=0;--t){let i=e[t];if(!i)continue;let o=a%2==0?n.argsHash:r;if(i.argsHash!==o)break;a+=1}if(a<2||t!==r)return{count:0,noProgressEvidence:!1};let o=Math.max(0,e.length-a),s,c,l=!0;for(let t=o;t<e.length;t+=1){let i=e[t];if(i){if(!i.resultHash){l=!1;break}if(i.argsHash===n.argsHash){if(!s)s=i.resultHash;else if(s!==i.resultHash){l=!1;break}continue}if(i.argsHash===r){if(!c)c=i.resultHash;else if(c!==i.resultHash){l=!1;break}continue}l=!1;break}}return(!s||!c)&&(l=!1),{count:a+1,pairedToolName:n.toolName,pairedSignature:n.argsHash,noProgressEvidence:l}}function Ph(e,t){return[e,t].toSorted().join(`|`)}function Fh(e,t,n,r){let i=Sh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=wh(t,n),s=Mh(a,t,o),c=s.count,l=Oh(t,n),u=Nh(a,o);if(c>=i.globalCircuitBreakerThreshold)return{stuck:!0,level:`critical`,detector:`global_circuit_breaker`,count:c,message:`CRITICAL: ${t} has repeated identical no-progress outcomes ${c} times. Session execution blocked by global circuit breaker to prevent runaway loops.`,warningKey:`global:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.criticalThreshold)return{stuck:!0,level:`critical`,detector:`known_poll_no_progress`,count:c,message:`CRITICAL: Called ${t} with identical arguments and no progress ${c} times. This appears to be a stuck polling loop. Session execution blocked to prevent resource waste.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};if(l&&i.detectors.knownPollNoProgress&&c>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`known_poll_no_progress`,count:c,message:`WARNING: You have called ${t} ${c} times with identical arguments and no progress. Stop polling and either (1) increase wait time between checks, or (2) report the task as failed if the process is stuck.`,warningKey:`poll:${t}:${o}:${s.latestResultHash??`none`}`};let d=u.pairedSignature?`pingpong:${Ph(o,u.pairedSignature)}`:`pingpong:${t}:${o}`;if(i.detectors.pingPong&&u.count>=i.criticalThreshold&&u.noProgressEvidence)return{stuck:!0,level:`critical`,detector:`ping_pong`,count:u.count,message:`CRITICAL: You are alternating between repeated tool-call patterns (${u.count} consecutive calls) with no progress. This appears to be a stuck ping-pong loop. Session execution blocked to prevent resource waste.`,pairedToolName:u.pairedToolName,warningKey:d};if(i.detectors.pingPong&&u.count>=i.warningThreshold)return{stuck:!0,level:`warning`,detector:`ping_pong`,count:u.count,message:`WARNING: You are alternating between repeated tool-call patterns (${u.count} consecutive calls). This looks like a ping-pong loop; stop retrying and report the task as failed.`,pairedToolName:u.pairedToolName,warningKey:d};let f=a.filter(e=>e.toolName===t&&e.argsHash===o).length;return!l&&i.detectors.genericRepeat&&f>=i.warningThreshold?{stuck:!0,level:`warning`,detector:`generic_repeat`,count:f,message:`WARNING: You have called ${t} ${f} times with identical arguments. If this is not making progress, stop retrying and report the task as failed.`,warningKey:`generic:${t}:${o}`}:{stuck:!1}}function Ih(e,t,n,r,i){let a=Sh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:wh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Lh(e,t){let n=Sh(t.config),r=jh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=wh(t.toolName,t.toolParams),a=!1;for(let n=e.toolCallHistory.length-1;n>=0;--n){let o=e.toolCallHistory[n];if(o&&!(t.toolCallId&&o.toolCallId!==t.toolCallId)&&!(o.toolName!==t.toolName||o.argsHash!==i)&&o.resultHash===void 0){o.resultHash=r,a=!0;break}}a||e.toolCallHistory.push({toolName:t.toolName,argsHash:i,toolCallId:t.toolCallId,resultHash:r,timestamp:Date.now()}),e.toolCallHistory.length>n.historySize&&e.toolCallHistory.splice(0,e.toolCallHistory.length-n.historySize)}function Rh(e,t,n){e.toolLoopWarningBuckets||=new Map;let r=Math.floor(n/10);if(r<=(e.toolLoopWarningBuckets.get(t)??0))return!1;if(e.toolLoopWarningBuckets.set(t,r),e.toolLoopWarningBuckets.size>256){let t=e.toolLoopWarningBuckets.keys().next().value;t&&e.toolLoopWarningBuckets.delete(t)}return!0}function zh(e){return e&&e.trim()||`tool`}function Bh(e,t,n){if(!e.execute)return e;let r=zh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=Fh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Rh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}Ih(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Lh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Lh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Vh(e,t,n){return e.map(e=>Bh(e,t,n))}const Hh=new Map;function Uh(e){let t=Hh.get(e);return t||(t={},Hh.set(e,t)),t}function Wh(e){Hh.delete(e)}function Gh(e){let t=e.streamFn??Zt;return(e,n,r)=>(e.api===`anthropic-messages`&&Kh(e),t(e,n,{...r,...$h(e,r)}))}function Kh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Yh(Qh(e),n)?(globalThis.fetch=t,qh(await t(e,Xh(e,r)))):t(e,r))}function qh(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(`
118
-
119
- `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Jh))),a.enqueue(r.encode(e+`
120
-
121
- `))}},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 Jh=`event: message_start
136
+ `)}function pm(e=[]){let t=em(e).trim();return t?`${t}\n`:``}function mm(){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(`
137
+ `)}function hm(){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(`
138
+ `)}function gm(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(`
139
+ `)}function _m(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(`
140
+ `)}function vm(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(`
141
+ `)}function ym(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=bm(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
142
+ `)}function bm(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 xm(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(`
143
+ `)}function Sm(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(`
144
+ `)}function Cm(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(`
145
+ `)}function wm(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(`
146
+ `)}function Tm(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(`
147
+ `)}function Em(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(`
148
+ `):``}function Dm(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:[...nm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Tm(e.subagentDepth??0),im({toolNames:i,toolSummaries:e.toolSummaries}),om(i),dm(),um(n),sm(),cm(),Ea(e.availableAgents??[]),fm(a),pm(e.autoSkillCategories),mm(),hm(),gm(e.memoryCitationsMode??`off`),_m({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),vm(e.sandboxInfo),ym({currentDate:e.currentDate,timezone:e.timezone}),lm(),xm({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Cm({isMinimal:n}),Sm(e.runtimeInfo),wm({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Em(e.priorConversationSummary)].filter(Boolean).join(`
149
+ `)}function Om(e,t,n){return e.map(e=>{let r=e,i=Fe(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await ue({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(_o(e))return xo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function km(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 Am(e,t){let n=e.content,r=Pm(e.details),i=e.isError;for(let e of t)if(e){if(e.content!==void 0&&(n=jm(n,e.content)),e.details!==void 0){let t=Pm(e.details);r={...r,...t}}e.isError===!0&&(i=!0)}return{content:n,details:r,isError:i}}function jm(e,t){return t===void 0?e:e===void 0?t:Array.isArray(e)&&Array.isArray(t)?Mm(e,t)?t:[...e,...t]:t}function Mm(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!Nm(e[n],t[n]))return!1;return!0}function Nm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Pm(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function Fm(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),_o(t))return xo(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=km(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(_o(e))return xo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}let f=Am({content:a.content,details:u,isError:s},d),p=Math.max(0,Date.now()-l),m=f.isError?Im(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 Im(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(`
150
+ `):void 0}var Lm=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 Rm={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function zm(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Bm(e){let t=zm(e?.warningThreshold,Rm.warningThreshold),n=zm(e?.criticalThreshold,Rm.criticalThreshold),r=zm(e?.globalCircuitBreakerThreshold,Rm.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Rm.enabled,historySize:zm(e?.historySize,Rm.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Rm.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Rm.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Rm.detectors.pingPong}}}function Vm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Hm(e,t){return`${e}:${Gm(t)}`}function Um(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Um).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Um(t[e])}`).join(`,`)}}`}function Wm(e){try{return Um(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 Gm(e){let t=Wm(e);return Nt(`sha256`).update(t).digest(`hex`)}function Km(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Vm(t))return!1;let n=t.action;return n===`poll`||n===`log`}function qm(e){return!Vm(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Vm(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
151
+ `).trim()}function Jm(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Um(e)}function Ym(e,t,n,r){if(r!==void 0)return`error:${Gm(Jm(r))}`;if(!Vm(n))return n===void 0?void 0:Gm(n);let i=Vm(n.details)?n.details:{},a=qm(n);if(Km(e,t)&&e===`process`&&Vm(t)){let e=t.action;if(e===`poll`)return Gm({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Gm({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 Gm({details:i,text:a})}function Xm(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 Zm(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 Qm(e,t){return[e,t].toSorted().join(`|`)}function $m(e,t,n,r){let i=Bm(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Hm(t,n),s=Xm(a,t,o),c=s.count,l=Km(t,n),u=Zm(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:${Qm(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 eh(e,t,n,r,i){let a=Bm(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Hm(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function th(e,t){let n=Bm(t.config),r=Ym(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Hm(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 nh(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 rh(e){return e&&e.trim()||`tool`}function ih(e,t,n){if(!e.execute)return e;let r=rh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=$m(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);nh(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}eh(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return th(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw th(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function ah(e,t,n){return e.map(e=>ih(e,t,n))}const oh=new Map;function sh(e){let t=oh.get(e);return t||(t={},oh.set(e,t)),t}function ch(e){oh.delete(e)}function lh(e){let t=e.streamFn??Zt;return(e,n,r)=>(e.api===`anthropic-messages`&&uh(e),t(e,n,{...r,..._h(e,r)}))}function uh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>ph(gh(e),n)?(globalThis.fetch=t,dh(await t(e,mh(e,r)))):t(e,r))}function dh(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(`
152
+
153
+ `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(fh))),a.enqueue(r.encode(e+`
154
+
155
+ `))}},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 fh=`event: message_start
122
156
  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}}}
123
157
 
124
- `;function Yh(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Xh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Zh(e)&&n.delete(e);return{...t,headers:n}}function Zh(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 Qh(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function $h(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}function eg(e,t=.3){return e.length===0?!0:e.every(e=>e.score<t)}function tg(e){return Math.ceil(e.length/4)}function ng(e,t){if(tg(e)<=t)return e;let n=t*4;return`${e.slice(0,Math.max(0,n-3)).trimEnd()}...`}async function rg(e){let t=e.query.trim();if(!t)return{};let n=await e.provider.search(t),r=e.coreConfig?.knowledgeController?.scoreThreshold,i=eg(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:ng(o.join(`
125
- `),a),blockId:`core-recall-${Date.now()}`,isWeakLocalRecall:i}}function ig(e,t){return`${t.trim()}\n\n${e}`}function ag(e,t){let n=`${t.trim()}\n\n`;return e.startsWith(n)?e.slice(n.length):e}const og=`<!-- AIMax compaction memory recall -->`;async function sg(e){if(e.coreConfig?.compactionRecall?.enabled!==!0)return;let t=e.query.trim();if(t)try{let n=await rg({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?`${og}\n\n${n.block.replace(`${og}\n\n`,``).trim()}`:void 0}catch{return}}async function cg(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,X(t)),T={model:t.llm.model,api:t.llm.apiFormat??`openai-completions`},E=oc(t.llm),D=await Yu({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 Xu({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 dg({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,X(t)),j=Pn(),M=Wa([...Lm(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,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)},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=lh({dataDir:t.dataDir,projectDir:t.projectDir,skills:Ua(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:It.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});L=await ug({systemPrompt:L,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let R,z=t.memory?.core,B=z?.recall?.enabled===!0,V=!!t.subagentContext,H=o.memoryProviderSource===`plugin`&&z?.recall?.forceWithPluginProvider!==!0;if(B&&!V&&!H&&!o.recallState.recallProvided)try{let e=await rg({provider:o.memoryProvider,query:f,coreConfig:z}),t=z?.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=ag(L,R)),R=e.block,L=ig(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=ig(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 te={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},ne=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:L,systemPromptOptions:te,recallState:o.recallState},a,{eventDispatcher:s}),re=await i.dispatchWithMetadata(`before_prompt_build`,{prompt:f,recallState:o.recallState},a,{eventDispatcher:s});re.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 U=[];for(let e of ne){if(!e)continue;let t=e;if(t.recall?.block?.trim()){R&&=(L=ag(L,R),void 0),L=ig(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&&U.push(t.message)}for(let e of re){if(!e.result)continue;let t=e.result;if(t.recall?.block?.trim()){R&&=(L=ag(L,R),void 0),L=ig(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 ie=Vh(uh(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},Uh),W=S?.model??t.llm.model,ae=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of ae)e&&e.modelOverride&&(W=e.modelOverride);let oe=y({...t.llm,model:W},n,t.messageId,t.channel);try{await Qs(t.dataDir,n,{systemPrompt:L,tools:ie},X(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let G=new Bt({initialState:{systemPrompt:L,model:oe,tools:ie,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:Gh({})}),se={eventDispatcher:s};a.signal=b;let ce=new yh;return a.toolParamOverrides=ce,_h({agent:G,hookRegistry:i,hookContext:a,pluginRuntime:se,overrideStore:ce}),O.messages.length>0&&(G.state.messages=O.messages),U.length>0&&(G.state.messages=[...U,...G.state.messages]),{agent:G,resolvedModelId:W,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function lg(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 ug(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 dg(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=fg(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 sg({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 fg(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(`
158
+ `;function ph(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function mh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))hh(e)&&n.delete(e);return{...t,headers:n}}function hh(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 gh(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function _h(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}function vh(e,t=.3){return e.length===0?!0:e.every(e=>e.score<t)}function yh(e){return Math.ceil(e.length/4)}function bh(e,t){if(yh(e)<=t)return e;let n=t*4;return`${e.slice(0,Math.max(0,n-3)).trimEnd()}...`}async function xh(e){let t=e.query.trim();if(!t)return{};let n=await e.provider.search(t),r=e.coreConfig?.knowledgeController?.scoreThreshold,i=vh(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:bh(o.join(`
159
+ `),a),blockId:`core-recall-${Date.now()}`,isWeakLocalRecall:i}}function Sh(e,t){return`${t.trim()}\n\n${e}`}function Ch(e,t){let n=`${t.trim()}\n\n`;return e.startsWith(n)?e.slice(n.length):e}const wh=`<!-- AIMax compaction memory recall -->`;async function Th(e){if(e.coreConfig?.compactionRecall?.enabled!==!0)return;let t=e.query.trim();if(t)try{let n=await xh({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?`${wh}\n\n${n.block.replace(`${wh}\n\n`,``).trim()}`:void 0}catch{return}}async function Eh(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=Vs(t.llm),D=await Au({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 ju({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 kh({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=Pn(),M=Ta([...$p(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,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=Dm({dataDir:t.dataDir,projectDir:t.projectDir,skills:wa(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:It.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});L=await Oh({systemPrompt:L,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let R,z=t.memory?.core,B=z?.recall?.enabled===!0,V=!!t.subagentContext,H=o.memoryProviderSource===`plugin`&&z?.recall?.forceWithPluginProvider!==!0;if(B&&!V&&!H&&!o.recallState.recallProvided)try{let e=await xh({provider:o.memoryProvider,query:f,coreConfig:z}),t=z?.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=Ch(L,R)),R=e.block,L=Sh(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=Sh(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 te={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},ne=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:L,systemPromptOptions:te,recallState:o.recallState},a,{eventDispatcher:s}),re=await i.dispatchWithMetadata(`before_prompt_build`,{prompt:f,recallState:o.recallState},a,{eventDispatcher:s});re.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 U=[];for(let e of ne){if(!e)continue;let t=e;if(t.recall?.block?.trim()){R&&=(L=Ch(L,R),void 0),L=Sh(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&&U.push(t.message)}for(let e of re){if(!e.result)continue;let t=e.result;if(t.recall?.block?.trim()){R&&=(L=Ch(L,R),void 0),L=Sh(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 ie=ah(Om(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},sh),W=S?.model??t.llm.model,ae=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of ae)e&&e.modelOverride&&(W=e.modelOverride);let oe=y({...t.llm,model:W},n,t.messageId,t.channel);try{await Ns(t.dataDir,n,{systemPrompt:L,tools:ie},$(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let G=new Bt({initialState:{systemPrompt:L,model:oe,tools:ie,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:lh({})}),se={eventDispatcher:s};a.signal=b;let ce=new Lm;return a.toolParamOverrides=ce,Fm({agent:G,hookRegistry:i,hookContext:a,pluginRuntime:se,overrideStore:ce}),O.messages.length>0&&(G.state.messages=O.messages),U.length>0&&(G.state.messages=[...U,...G.state.messages]),{agent:G,resolvedModelId:W,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function Dh(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 Oh(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 kh(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=Ah(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 Th({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 Ah(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(`
126
160
 
127
- `):void 0,pluginRecallProvided:r}}function pg(e){return e.some(e=>gg(e.message)!==null||e.toolResults.length>0)}function mg(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 hg(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 gg(e){let t=Sg(e),n=_g(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 _g(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function vg(e){return e.map(e=>_g(e.message)).filter(e=>e.trim().length>0).join(`
161
+ `):void 0,pluginRecallProvided:r}}function jh(e){return e.some(e=>Ph(e.message)!==null||e.toolResults.length>0)}function Mh(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 Nh(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 Ph(e){let t=Bh(e),n=Fh(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 Fh(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function Ih(e){return e.map(e=>Fh(e.message)).filter(e=>e.trim().length>0).join(`
128
162
 
129
- `)}function yg(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function bg(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 xg(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:Cg(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Sg(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Cg(e){let t=e.indexOf(`
163
+ `)}function Lh(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Rh(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 zh(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:Vh(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Bh(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Vh(e){let t=e.indexOf(`
130
164
  Preview:
131
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function wg(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=Ro(),O=Le(),k=new co,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(()=>z(e));M=t.catch(()=>{}),I(t)});async function z(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=zg(`partial`in t?t.partial:void 0)??zg(`message`in t?t.message:void 0)??zg(`message`in e?e.message:void 0),a=Bg(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=Sg(e);let r=Bg(``,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=Sg(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=Ag(t));let r=to(Sg(t),A);n||(r.artifacts.length>0&&p?.addOwn(r.artifacts),await ae(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:xg(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=yg(gg(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText);let o=n?[]:a.map(bg);(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=Rg(e.result),r=Lg(e.result);p?.addChild(Tg(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:xg(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(uo({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 B=Ds(d),V=B.enabled?B.maxAttempts:1;try{Eg({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=V;e++){let d=C.length;b=void 0,y=void 0,P=0,ee=0;try{await lg({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`);G.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,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 zo(D,async()=>{await pe(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&&(G.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,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=Vg(T),G.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,error:y,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:C.length-d,...$o(T,`providerError`)}),await te(T,y,e,d))continue;await ne(y,T),await s.dispatchProgress(i,{type:`error`,message:y})}y||G.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await L(),Io(t)||Ie(t))throw t;if(y=Vg(t),G.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,error:y}),await te(t,y,e,d))continue;await ne(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{R()}function H(){m=``,h=``,g=``}async function te(e,n,r,a){let o=kg({error:e,attempt:r,maxAttempts:V,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g});if(!o.retry)return G.warn(`llm turn retry skipped`,{sessionId:i,attempt:r,maxAttempts:V,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=Os(r,B);return G.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:V,delayMs:c,error:n}),await Ng({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:V,message:n,delayMs:c}),C.length=a,H(),Pg(t),await ks(c,u),!0}async function ne(e,t){f&&await f(mg(e,t),[])}let re=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:re,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let U=O.signal?``:C.length>0?to(Sg(C[C.length-1].message),A).cleanedText:``,ie=to(m,A).cleanedText,W=U||ie||hg(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;if(f&&!pg(C)&&!y&&m.trim().length>0){let e=to(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await ae(e.warnings);let t=vg(C);await f({role:`assistant`,content:e.cleanedText,...t?{thinking:t}:{},timestamp:new Date().toISOString()},[])}return{text:W,inputTokens:_,outputTokens:v,error:y,turnRecords:C};async function ae(e){for(let t of e)await s.dispatchDiagnostic(i,{level:`warn`,scope:`runner`,phase:`artifact_parse`,message:t})}}function Tg(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 Eg(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:Dg(a,e.message),s=Og(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=ls(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 Dg(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function Og(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 kg(e){let t=e.turnRecords.slice(e.attemptTurnRecordStart),n=t.filter(e=>e.toolResults.length>0).length,r=t.filter(e=>Sg(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=As(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 Ag(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:jg(t.errorCode),statusCode:Mg(t.statusCode),providerCode:jg(t.providerCode),providerType:jg(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function jg(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Mg(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Ng(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 Pg(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&Fg(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function Fg(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`?t.stopReason===`error`||t.stopReason===`aborted`?!0:Ig(t.content):!1}function Ig(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 Lg(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return Rg(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):Rg(e)}function Rg(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function zg(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 Bg(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function Vg(e){let t=Hg(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 Hg(e){if(e instanceof me)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:jg(t.code),statusCode:Mg(t.statusCode),statusText:jg(t.statusText),providerMessage:jg(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 Ug(e){let t=Yg(e.toolResultPreviewChars),n=Xg(e.systemPrompt,e.agentDefinition),r=Qg(e.model,e.agentDefinition),i=Wa(e.tools??[],e.agentDefinition),a=Zg(e.message,e.agentDefinition),o=await wg({agent:new Bt({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:Wg({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new we,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:Kg(o.turnRecords),toolResults:qg(o.turnRecords,t)}}function Wg(e){let t=e.phasePrefix??`silent_agent`;return new Qa({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await Gg(e.diagnosticDispatcher,t,n)}})}async function Gg(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 Kg(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 qg(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Jg(e.content,t)})))}function Jg(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function Yg(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 Xg(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
165
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function Hh(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=yo(),O=Le(),k=new Ua,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(()=>z(e));M=t.catch(()=>{}),I(t)});async function z(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=rg(`partial`in t?t.partial:void 0)??rg(`message`in t?t.message:void 0)??rg(`message`in e?e.message:void 0),a=ig(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=Bh(e);let r=ig(``,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=Bh(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=Jh(t));let r=Ia(Bh(t),A);n||(r.artifacts.length>0&&p?.addOwn(r.artifacts),await ae(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:zh(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=Lh(Ph(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText);let o=n?[]:a.map(Rh);(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=ng(e.result),r=tg(e.result);p?.addChild(Uh(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:zh(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(Ga({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 B=cs(d),V=B.enabled?B.maxAttempts:1;try{Wh({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=V;e++){let d=C.length;b=void 0,y=void 0,P=0,ee=0;try{await Dh({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`);G.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,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 bo(D,async()=>{await pe(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&&(G.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,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=ag(T),G.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,error:y,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:C.length-d,...Po(T,`providerError`)}),await te(T,y,e,d))continue;await ne(y,T),await s.dispatchProgress(i,{type:`error`,message:y})}y||G.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await L(),_o(t)||Ie(t))throw t;if(y=ag(t),G.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:V,error:y}),await te(t,y,e,d))continue;await ne(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{R()}function H(){m=``,h=``,g=``}async function te(e,n,r,a){let o=qh({error:e,attempt:r,maxAttempts:V,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g});if(!o.retry)return G.warn(`llm turn retry skipped`,{sessionId:i,attempt:r,maxAttempts:V,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=ls(r,B);return G.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:V,delayMs:c,error:n}),await Zh({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:V,message:n,delayMs:c}),C.length=a,H(),Qh(t),await us(c,u),!0}async function ne(e,t){f&&await f(Mh(e,t),[])}let re=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:re,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let U=O.signal?``:C.length>0?Ia(Bh(C[C.length-1].message),A).cleanedText:``,ie=Ia(m,A).cleanedText,W=U||ie||Nh(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;if(f&&!jh(C)&&!y&&m.trim().length>0){let e=Ia(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await ae(e.warnings);let t=Ih(C);await f({role:`assistant`,content:e.cleanedText,...t?{thinking:t}:{},timestamp:new Date().toISOString()},[])}return{text:W,inputTokens:_,outputTokens:v,error:y,turnRecords:C};async function ae(e){for(let t of e)await s.dispatchDiagnostic(i,{level:`warn`,scope:`runner`,phase:`artifact_parse`,message:t})}}function Uh(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 Wh(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:Gh(a,e.message),s=Kh(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=Wo(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 Gh(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function Kh(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 qh(e){let t=e.turnRecords.slice(e.attemptTurnRecordStart),n=t.filter(e=>e.toolResults.length>0).length,r=t.filter(e=>Bh(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=ds(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 Jh(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:Yh(t.errorCode),statusCode:Xh(t.statusCode),providerCode:Yh(t.providerCode),providerType:Yh(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function Yh(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Xh(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function Zh(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 Qh(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&$h(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function $h(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`?t.stopReason===`error`||t.stopReason===`aborted`?!0:eg(t.content):!1}function eg(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 tg(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return ng(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):ng(e)}function ng(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function rg(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 ig(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function ag(e){let t=og(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 og(e){if(e instanceof me)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:Yh(t.code),statusCode:Xh(t.statusCode),statusText:Yh(t.statusText),providerMessage:Yh(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 sg(e){let t=pg(e.toolResultPreviewChars),n=mg(e.systemPrompt,e.agentDefinition),r=gg(e.model,e.agentDefinition),i=Ta(e.tools??[],e.agentDefinition),a=hg(e.message,e.agentDefinition),o=await Hh({agent:new Bt({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:cg({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new we,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:ug(o.turnRecords),toolResults:dg(o.turnRecords,t)}}function cg(e){let t=e.phasePrefix??`silent_agent`;return new Na({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await lg(e.diagnosticDispatcher,t,n)}})}async function lg(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 ug(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 dg(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:fg(e.content,t)})))}function fg(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function pg(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 mg(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
132
166
 
133
- `)}function Zg(e,t){return!t?.initPrompt||typeof e!=`string`?e:Ka(t,e)}function Qg(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const $g=J.Object({kind:J.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>J.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:J.Optional(J.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:J.Optional(J.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:J.Optional(J.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:J.Optional(J.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function e_(e){let t=wi({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??yi}),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:$g,async execute(r,i){try{return i.kind===`tool_result`?n_(await Ci({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?n_(await bi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?n_(await xi({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?n_({...await Si({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):n_(await Si({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:t_(i),limits:t}))}catch(r){return n_({kind:i.kind,error:r_(r),limits:t,contextFiles:Ei(e.dataDir,e.sessionId,n)})}}}}function t_(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 n_(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function r_(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function i_(e){let t=[mm(e.dataDir),hm(e.dataDir),gm(e.dataDir),e_({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(_m(e.dataDir)),t}const a_=`auto-skill-reviewer`;async function o_(e){let t=e.createModel??Aa,n=e.tools??i_({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 Ug({sessionId:e.sessionId,systemPrompt:s_(e.mode),message:c_(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=l_(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 s_(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(`
134
- `)}function c_(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(`
135
- `)}function l_(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=u_(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 u_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const d_=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],f_=d_,p_={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}},m_=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function h_(e){let t=__(e.gates),n={session:y_(`session`,e.sessionTranscript,t.session),currentRun:y_(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:y_(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=C_(e.reviewState?.reviewCount,0),i=C_(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return T_(n,a,r,i,o,`run_error`);if(e.result?.paused)return T_(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return T_(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return T_(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 g_(e,t={}){let n=li(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??d_),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(E_(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}D_(t)&&O_(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 __(e){return{session:v_(e?e.session:p_.session),currentRun:v_(e?e.currentRun:p_.currentRun),reviewWindow:v_(e?e.reviewWindow:p_.reviewWindow)}}function v_(e){let t={};for(let n of m_){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?f_:void 0;if(typeof r==`number`){let e=S_(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=S_(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:w_(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:w_(r.toolNames,i)})}return t}function y_(e,t,n){let r=g_(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=m_.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];b_(t,o,r)?i.push({code:t,description:x_(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 b_(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 x_(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 S_(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function C_(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function w_(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function T_(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 E_(e){return e.role===`assistant`}function D_(e){return e.role===`tool_result`}function O_(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:k_(e.content)?.success===!1}function k_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function A_(e){let t=di(e.transcript.length,e.transcriptStartIndex),n=fi(e.transcript.length,e.recentEntryLimit),r=di(e.transcript.length,e.reviewWindowStartIndex??void 0),i=di(e.transcript.length,0),a=pi(e.transcript,t),o=pi(e.transcript,r),s=g_(e.transcript),c=g_(a),l=g_(o),u=ci(e.transcript),d=ci(a),f=ci(o),p=a.filter(M_),m=a.filter(N_);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:j_(p[0]?.content??``,800),finalResponse:j_(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:ui(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 j_(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function M_(e){return e.role===`user`}function N_(e){return e.role===`assistant`}function P_(e,t,n){return q.join(r(e,t,n),`auto-skill-review-state.json`)}function F_(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function I_(e,t,n){let r=P_(e,t,n),i;try{i=await K.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return F_(t);throw e}return V_(JSON.parse(i),t)}async function L_(e,t,n){let r=P_(e,t.sessionId,n);await K.mkdir(q.dirname(r),{recursive:!0}),await K.writeFile(r,`${JSON.stringify(V_(t,t.sessionId),null,2)}\n`,`utf-8`)}async function R_(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await L_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function z_(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 L_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function B_(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await L_(e.dataDir,t,{storeName:e.sessionStoreName}),t}function V_(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:W_(n.reviewCount,0),lastAttemptedReviewAt:H_(n.lastAttemptedReviewAt),lastCompletedReviewAt:H_(n.lastCompletedReviewAt),lastFailedReviewAt:H_(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:U_(n.lastReviewedTranscriptEndIndex)}}function H_(e){return typeof e==`string`&&e.trim()?e:null}function U_(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function W_(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function G_(e){return q.join(Wi(e),`.reviews`,`run-log.jsonl`)}async function K_(e,t){let n=G_(e);await K.mkdir(q.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await K.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const q_=`write`,J_=new Set([`off`,`gate`,`dry_run`,`write`]);async function Y_(e){let t=X_(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=Q_(e);if(n){await nv(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=$_(n,e.transcriptStartIndex),o=await I_(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=ev(o.lastReviewedTranscriptEndIndex,n.length),c=$_(n,s);await rv(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=h_({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await rv(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 iv(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await rv(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new ua({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=A_({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:Ei(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await rv(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await iv(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(a_);if(!p){G.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:a_}),await nv(e,t,`reviewer_agent_missing`,{reviewerAgentName:a_});return}i={mode:f,decision:l,packet:d},r=await R_({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??o_,h=i_({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 B_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await av(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await tv(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:ov(g.toolCalls),toolResults:pv(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await z_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await av(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:fv(g.text,2e3),toolCalls:ov(g.toolCalls),toolResults:pv(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 B_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await av(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await tv(e,n,a?{reviewRunLogPath:a}:void 0)}}function X_(e){return{mode:Z_(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function Z_(e){if(e==null)return q_;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?J_.has(t)?t:`off`:q_}function Q_(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 $_(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function ev(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function tv(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 nv(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 rv(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function iv(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:dv(n),...i.packet?{packet:i.packet}:{}}})}async function av(e,t,n){return K_(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?cv(n.curatorResult.text):void 0,conclusionText:n.curatorResult?lv(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?ov(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?pv(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 ov(e){return e.map(e=>({...e,arguments:sv(e.name,e.arguments)}))}function sv(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 cv(e){let t=uv(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function lv(e){return cv(e)?void 0:fv(e,8e3)}function uv(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 dv(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 fv(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function pv(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let mv=!1;function hv(){mv||=(Xt(),Yt({api:`openai-completions`,stream:ss,streamSimple:cs}),!0)}const gv=[`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(`
136
- `);async function _v(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 Sv(l);let u=Sv(l),d=r.flashModel,f=se({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=yv(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await f.chat({system:gv,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(bv(t)){if(m.didTimeout())return s?.(`timeout`),u;throw t}e<3&&await vv(500*e,m.signal)}}catch(e){if(bv(e)&&m.didTimeout())return s?.(`timeout`),u;throw e}finally{m.clear()}return s?.(`error`),u}function vv(e,t){return t?t.aborted?Promise.reject(xv()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(xv())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function yv(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 bv(e){return e instanceof Error&&e.name===`AbortError`}function xv(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function Sv(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 Cv(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 wv(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await Dv(await F(r.dataDir,t,{...X(r)}),r);await i.dispatch(`agent_end`,{success:!n.error,error:n.error,durationMs:n.durationMs,messages:o},a,{eventDispatcher:e.eventDispatcher})}async function Tv(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await F(r.dataDir,t,{...X(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 Ev(e){await wv(e),await Tv(e)}async function Dv(e,t){return e.map(e=>({...e}))}function Ov(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(`
167
+ `)}function hg(e,t){return!t?.initPrompt||typeof e!=`string`?e:Da(t,e)}function gg(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const _g=J.Object({kind:J.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>J.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:J.Optional(J.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:J.Optional(J.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:J.Optional(J.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:J.Optional(J.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function vg(e){let t=oi({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??ti}),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:_g,async execute(r,i){try{return i.kind===`tool_result`?bg(await ai({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?bg(await ni({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?bg(await ri({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?bg({...await ii({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):bg(await ii({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:yg(i),limits:t}))}catch(r){return bg({kind:i.kind,error:xg(r),limits:t,contextFiles:ci(e.dataDir,e.sessionId,n)})}}}}function yg(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 bg(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function xg(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Sg(e){let t=[xp(e.dataDir),Sp(e.dataDir),Cp(e.dataDir),vg({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(wp(e.dataDir)),t}const Cg=`auto-skill-reviewer`;async function wg(e){let t=e.createModel??da,n=e.tools??Sg({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 sg({sessionId:e.sessionId,systemPrompt:Tg(e.mode),message:Eg(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=Dg(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 Tg(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(`
168
+ `)}function Eg(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(`
169
+ `)}function Dg(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=Og(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 Og(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const kg=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Ag=kg,jg={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}},Mg=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Ng(e){let t=Fg(e.gates),n={session:Lg(`session`,e.sessionTranscript,t.session),currentRun:Lg(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:Lg(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Vg(e.reviewState?.reviewCount,0),i=Vg(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return Ug(n,a,r,i,o,`run_error`);if(e.result?.paused)return Ug(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return Ug(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return Ug(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 Pg(e,t={}){let n=Gr(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??kg),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(Wg(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}Gg(t)&&Kg(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 Fg(e){return{session:Ig(e?e.session:jg.session),currentRun:Ig(e?e.currentRun:jg.currentRun),reviewWindow:Ig(e?e.reviewWindow:jg.reviewWindow)}}function Ig(e){let t={};for(let n of Mg){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Ag:void 0;if(typeof r==`number`){let e=Bg(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Bg(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:Hg(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:Hg(r.toolNames,i)})}return t}function Lg(e,t,n){let r=Pg(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=Mg.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];Rg(t,o,r)?i.push({code:t,description:zg(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 Rg(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 zg(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 Bg(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Vg(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Hg(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function Ug(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 Wg(e){return e.role===`assistant`}function Gg(e){return e.role===`tool_result`}function Kg(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:qg(e.content)?.success===!1}function qg(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function Jg(e){let t=qr(e.transcript.length,e.transcriptStartIndex),n=Jr(e.transcript.length,e.recentEntryLimit),r=qr(e.transcript.length,e.reviewWindowStartIndex??void 0),i=qr(e.transcript.length,0),a=Yr(e.transcript,t),o=Yr(e.transcript,r),s=Pg(e.transcript),c=Pg(a),l=Pg(o),u=Wr(e.transcript),d=Wr(a),f=Wr(o),p=a.filter(Xg),m=a.filter(Zg);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:Yg(p[0]?.content??``,800),finalResponse:Yg(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:Kr(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 Yg(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Xg(e){return e.role===`user`}function Zg(e){return e.role===`assistant`}function Qg(e,t,n){return q.join(r(e,t,n),`auto-skill-review-state.json`)}function $g(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function e_(e,t,n){let r=Qg(e,t,n),i;try{i=await K.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return $g(t);throw e}return a_(JSON.parse(i),t)}async function t_(e,t,n){let r=Qg(e,t.sessionId,n);await K.mkdir(q.dirname(r),{recursive:!0}),await K.writeFile(r,`${JSON.stringify(a_(t,t.sessionId),null,2)}\n`,`utf-8`)}async function n_(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await t_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function r_(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 t_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function i_(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await t_(e.dataDir,t,{storeName:e.sessionStoreName}),t}function a_(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:c_(n.reviewCount,0),lastAttemptedReviewAt:o_(n.lastAttemptedReviewAt),lastCompletedReviewAt:o_(n.lastCompletedReviewAt),lastFailedReviewAt:o_(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:s_(n.lastReviewedTranscriptEndIndex)}}function o_(e){return typeof e==`string`&&e.trim()?e:null}function s_(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function c_(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function l_(e){return q.join(Ei(e),`.reviews`,`run-log.jsonl`)}async function u_(e,t){let n=l_(e);await K.mkdir(q.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await K.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const d_=`write`,f_=new Set([`off`,`gate`,`dry_run`,`write`]);async function p_(e){let t=m_(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=g_(e);if(n){await b_(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=__(n,e.transcriptStartIndex),o=await e_(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=v_(o.lastReviewedTranscriptEndIndex,n.length),c=__(n,s);await x_(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=Ng({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await x_(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 S_(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await x_(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new Gi({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=Jg({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:ci(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await x_(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await S_(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(Cg);if(!p){G.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:Cg}),await b_(e,t,`reviewer_agent_missing`,{reviewerAgentName:Cg});return}i={mode:f,decision:l,packet:d},r=await n_({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??wg,h=Sg({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 i_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await C_(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await y_(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:w_(g.toolCalls),toolResults:j_(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await r_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await C_(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:A_(g.text,2e3),toolCalls:w_(g.toolCalls),toolResults:j_(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 i_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await C_(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await y_(e,n,a?{reviewRunLogPath:a}:void 0)}}function m_(e){return{mode:h_(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function h_(e){if(e==null)return d_;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?f_.has(t)?t:`off`:d_}function g_(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 __(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function v_(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function y_(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 b_(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 x_(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function S_(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:k_(n),...i.packet?{packet:i.packet}:{}}})}async function C_(e,t,n){return u_(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?E_(n.curatorResult.text):void 0,conclusionText:n.curatorResult?D_(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?w_(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?j_(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 w_(e){return e.map(e=>({...e,arguments:T_(e.name,e.arguments)}))}function T_(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 E_(e){let t=O_(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function D_(e){return E_(e)?void 0:A_(e,8e3)}function O_(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 k_(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 A_(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function j_(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let M_=!1;function N_(){M_||=(Xt(),Yt({api:`openai-completions`,stream:Ho,streamSimple:Uo}),!0)}const P_=[`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(`
170
+ `);async function F_(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 B_(l);let u=B_(l),d=r.flashModel,f=se({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=L_(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await f.chat({system:P_,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(R_(t)){if(m.didTimeout())return s?.(`timeout`),u;throw t}e<3&&await I_(500*e,m.signal)}}catch(e){if(R_(e)&&m.didTimeout())return s?.(`timeout`),u;throw e}finally{m.clear()}return s?.(`error`),u}function I_(e,t){return t?t.aborted?Promise.reject(z_()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(z_())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function L_(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 R_(e){return e instanceof Error&&e.name===`AbortError`}function z_(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function B_(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 V_(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 H_(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await G_(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 U_(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 W_(e){await H_(e),await U_(e)}async function G_(e,t){return e.map(e=>({...e}))}function K_(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(`
137
171
 
138
- `).slice(0,4e3)}async function kv(e){if(e.coreConfig?.capture?.enabled!==!0)return;let t=Ov(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 Av(e){if(!(!e.runContext||e.runParams.memory?.core?.capture?.enabled!==!0||e.runParams.subagentContext))try{let t=await F(e.runParams.dataDir,e.sessionId,X(e.runParams));await kv({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 jv(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=X(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 Pv({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,X(o)),toolResultsDir:s(o.dataDir,n,X(o))}};return G.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 Av({sessionId:n,runParams:o,runContext:e.runContext,eventDispatcher:p}),await Ev({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function Mv(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=X(i),s=await Pv({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,X(i)),toolResultsDir:s(i.dataDir,t,X(i))}};h&&h.length>0&&e.transcriptStartIndex!==void 0&&!p&&!m&&await Nv({dataDir:i.dataDir,sessionId:t,pathOptions:X(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?G.warn(`agent run finalized with error`,b):G.info(`agent run finalized`,b),await Av({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 Tv(x):await Ev(x),y}async function Nv(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 Pv(e){let t=Sv(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&G.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await _v({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?G.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&G.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return G.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const Fv=new Set([`pause`,`resume`,`clear`,`help`]),Iv=`/goal
172
+ `).slice(0,4e3)}async function q_(e){if(e.coreConfig?.capture?.enabled!==!0)return;let t=K_(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 J_(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 q_({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 Q_({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 G.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 J_({sessionId:n,runParams:o,runContext:e.runContext,eventDispatcher:p}),await W_({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function X_(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 Q_({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 Z_({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?G.warn(`agent run finalized with error`,b):G.info(`agent run finalized`,b),await J_({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 U_(x):await W_(x),y}async function Z_(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 Q_(e){let t=B_(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&G.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await F_({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?G.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&G.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return G.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const $_=new Set([`pause`,`resume`,`clear`,`help`]),ev=`/goal
139
173
  【目标】:把 src/auth 目录下重复的参数校验逻辑抽离成公共函数。
140
174
  【范围】:只处理 src/auth 目录,不扩散到用户模块或订单模块。
141
175
  【约束】:保持现有 API 兼容,不引入新依赖,不要改变数据库结构。
142
176
  【验证】:每次改动后请自主运行 npm test auth 以及 npm run typecheck。如果测试失败,请定位原因并修复。
143
- 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function Lv(){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 发送):`,Iv].join(`
144
- `)}function Rv(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,Iv,``,`正文(写入 objective.txt 供 --goal-file):`,Iv.replace(/^\/goal\s+/,``)].join(`
145
- `)}async function zv(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await U(e.dataDir,e.sessionId,t);if(!r){let r=await W(e.dataDir,e.sessionId,{goalId:Ft(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await $n(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`created`,goal:r}}if((await B(e.dataDir,e.sessionId,r,t)).trim()!==n){let r=await W(e.dataDir,e.sessionId,{goalId:Ft(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await $n(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 H(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function Bv(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(Fv.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 Vv(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function Hv(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function Uv(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${Vv(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:`,` 状态:${Hv(n.workflowStatus)}`,n.currentTaskTitle?` 当前任务:${n.currentTaskTitle}(${n.currentTaskStatus??`unknown`})`:` 当前任务:(无)`),n.blockedReason&&a.push(` 阻塞原因:${n.blockedReason}`),a.push(` 待完成必需任务:${n.openRequiredTasks}`)),a.push(``,Gv(e.status)),a.join(`
146
- `)}async function Wv(e,t,n){let r=await Zn(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return Uv(t,n,r.goalState,r.workflowWarning)}function Gv(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 Kv(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:Lv()};if(e.action===`get`){let e=await U(t.dataDir,t.sessionId,n);return e?{replyText:await Wv(t,e,await B(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
147
- `)}}if(e.action===`set`){let r=await zv({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await B(t.dataDir,t.sessionId,r.goal,n);if(r.action===`unchanged`){let e=await Wv(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 Wv(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await U(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 H(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await Wv(t,r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await U(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 Wv(t,e,await B(t.dataDir,t.sessionId,e,n))}`};let r=await H(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${await Wv(t,r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ie(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const qv=[{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 Jv(){return qv.map(e=>({...e}))}function Yv(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function Xv(e){let t=new Set,n=[];for(let r of e){let e=Yv(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Zv(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function Qv(e,t){let n=Jv(),r=Xv(e),i=t?Zv(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function $v(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 ey(e){let t=$v(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 ty(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 ny(e,t){let n=ey(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=Bv(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:Yv(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(Xv(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 ry=new Set([`/new`,`/reset`,`/compact`]),iy=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),ay=new Set([`/help`]);function oy(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function sy(e){if(e.length===0)return[];let t=e.map(oy),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function cy(e){let t=Qv(e.skills),n=t.builtin.filter(e=>ry.has(e.name)),r=t.builtin.filter(e=>iy.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>ay.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...sy(n)),s.push(``),s.push(`目标命令`),s.push(...sy(r)),s.push(``),s.push(`技能命令`),s.push(...sy(i)),o.length>0?(s.push(...sy(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...sy(a)),{kind:`reply`,text:s.join(`
148
- `)}}function ly(e,t){let n=t.trim().toLowerCase();return n&&Xv(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function uy(e){let t=ly(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(`
177
+ 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function tv(){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 发送):`,ev].join(`
178
+ `)}function nv(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,ev,``,`正文(写入 objective.txt 供 --goal-file):`,ev.replace(/^\/goal\s+/,``)].join(`
179
+ `)}async function rv(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await U(e.dataDir,e.sessionId,t);if(!r){let r=await W(e.dataDir,e.sessionId,{goalId:Ft(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await $n(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`created`,goal:r}}if((await B(e.dataDir,e.sessionId,r,t)).trim()!==n){let r=await W(e.dataDir,e.sessionId,{goalId:Ft(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await $n(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 H(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function iv(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if($_.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 av(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function ov(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function sv(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${av(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:`,` 状态:${ov(n.workflowStatus)}`,n.currentTaskTitle?` 当前任务:${n.currentTaskTitle}(${n.currentTaskStatus??`unknown`})`:` 当前任务:(无)`),n.blockedReason&&a.push(` 阻塞原因:${n.blockedReason}`),a.push(` 待完成必需任务:${n.openRequiredTasks}`)),a.push(``,lv(e.status)),a.join(`
180
+ `)}async function cv(e,t,n){let r=await Zn(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return sv(t,n,r.goalState,r.workflowWarning)}function lv(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 uv(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:tv()};if(e.action===`get`){let e=await U(t.dataDir,t.sessionId,n);return e?{replyText:await cv(t,e,await B(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
181
+ `)}}if(e.action===`set`){let r=await rv({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await B(t.dataDir,t.sessionId,r.goal,n);if(r.action===`unchanged`){let e=await cv(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 cv(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await U(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 H(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await cv(t,r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await U(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 cv(t,e,await B(t.dataDir,t.sessionId,e,n))}`};let r=await H(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${await cv(t,r,await B(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ie(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const dv=[{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 fv(){return dv.map(e=>({...e}))}function pv(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function mv(e){let t=new Set,n=[];for(let r of e){let e=pv(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function hv(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function gv(e,t){let n=fv(),r=mv(e),i=t?hv(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function _v(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 vv(e){let t=_v(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 yv(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 bv(e,t){let n=vv(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=iv(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:pv(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(mv(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 xv=new Set([`/new`,`/reset`,`/compact`]),Sv=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),Cv=new Set([`/help`]);function wv(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function Tv(e){if(e.length===0)return[];let t=e.map(wv),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Ev(e){let t=gv(e.skills),n=t.builtin.filter(e=>xv.has(e.name)),r=t.builtin.filter(e=>Sv.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>Cv.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...Tv(n)),s.push(``),s.push(`目标命令`),s.push(...Tv(r)),s.push(``),s.push(`技能命令`),s.push(...Tv(i)),o.length>0?(s.push(...Tv(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...Tv(a)),{kind:`reply`,text:s.join(`
182
+ `)}}function Dv(e,t){let n=t.trim().toLowerCase();return n&&mv(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function Ov(e){let t=Dv(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(`
149
183
 
150
- `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function dy(e){let t=ny(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?cy(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?uy({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 fy(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=py(t),l=c>=0?t[c].content:void 0,u=rc(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}=wc(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:Y(u)}:{status:`compacted`,entry:{role:`compaction`,content:await pc({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:Y(d)}}function py(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const my=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
151
- `),hy=[`.aimax/new.txt`];async function gy(e){try{return(await jt(e,`utf-8`)).trim()||null}catch{return null}}async function _y(e){for(let t of hy){let n=await gy(Mt(e,t));if(n)return n}return await gy(`/aimax_pvc/new.txt`)||my}async function vy(e){return{kind:`reply`,text:await _y(e)}}function yy(){return{kind:`reply`,text:`✅ Session reset.`}}async function by(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function xy(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 by(e,t,{action:n.action,goal:n.after??null})}function Sy(e){let t=Ty(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Ey(r):null,a=n??i?.text,o=a?ty(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Dy(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Oy(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Cy(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=ny(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=dy({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:Dy(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Oy(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function wy(e){let t=Cy(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 jv({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 jv({replyText:(t.action===`reset`?yy():await vy(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 jv({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 Kv({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 by(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),ky(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await B(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await jv({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 fy({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,X(e.runParams)),contextWindowTokens:e.runParams.llm.contextWindow??2e5,llm:{baseUrl:e.runParams.llm.baseUrl,apiKey:e.runParams.llm.apiKey,model:e.runParams.llm.model},instructions:t.instructions,signal:e.runParams.abortSignal,hooks:e.hookRegistry,hookCtx:e.hookContext});return{kind:`completed`,result:await jv({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 Ty(e){return typeof e.message==`string`}function Ey(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 Dy(e,t){let n=Ey(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 Oy(e){return typeof e==`string`?e:JSON.stringify(e)}function ky(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function Ay(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++,G.info(`subagent announce round started`,{sessionId:r,announceRound:f,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){G.info(`subagent announce round skipped`,{sessionId:r,announceRound:f,reason:`no_completed_subagents`});break}G.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 _=jy(e);await d({role:`assistant`,content:_,timestamp:new Date().toISOString()});let v=await wg({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?G.warn(`subagent announce round completed with error`,y):G.info(`subagent announce round completed`,y)}return f>=10&&n.needsAnnounce(r)&&G.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:f,maxRounds:10}),{text:p,inputTokens:m,outputTokens:h,error:g}}function jy(e){if(e.length===1){let t=e[0];return Em({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Em({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
184
+ `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function kv(e){let t=bv(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Ev(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?Ov({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 Av(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=jv(t),l=c>=0?t[c].content:void 0,u=Rs(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}=ac(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:X(u)}:{status:`compacted`,entry:{role:`compaction`,content:await Js({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:X(d)}}function jv(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const Mv=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
185
+ `),Nv=[`.aimax/new.txt`];async function Pv(e){try{return(await jt(e,`utf-8`)).trim()||null}catch{return null}}async function Fv(e){for(let t of Nv){let n=await Pv(Mt(e,t));if(n)return n}return await Pv(`/aimax_pvc/new.txt`)||Mv}async function Iv(e){return{kind:`reply`,text:await Fv(e)}}function Lv(){return{kind:`reply`,text:`✅ Session reset.`}}async function Rv(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function zv(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 Rv(e,t,{action:n.action,goal:n.after??null})}function Bv(e){let t=Uv(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Wv(r):null,a=n??i?.text,o=a?yv(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Gv(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Kv(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Vv(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=bv(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=kv({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:Gv(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Kv(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Hv(e){let t=Vv(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`?Lv():await Iv(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 uv({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 Rv(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),qv(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await B(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await 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 Av({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 Uv(e){return typeof e.message==`string`}function Wv(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 Gv(e,t){let n=Wv(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 Kv(e){return typeof e==`string`?e:JSON.stringify(e)}function qv(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function Jv(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++,G.info(`subagent announce round started`,{sessionId:r,announceRound:f,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){G.info(`subagent announce round skipped`,{sessionId:r,announceRound:f,reason:`no_completed_subagents`});break}G.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 _=Yv(e);await d({role:`assistant`,content:_,timestamp:new Date().toISOString()});let v=await Hh({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?G.warn(`subagent announce round completed with error`,y):G.info(`subagent announce round completed`,y)}return f>=10&&n.needsAnnounce(r)&&G.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:f,maxRounds:10}),{text:p,inputTokens:m,outputTokens:h,error:g}}function Yv(e){if(e.length===1){let t=e[0];return Np({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Np({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
152
186
 
153
187
  ---
154
188
 
155
- `)}`}async function My(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?Ce({...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 we,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=ke(c.normalizedConfig),d;if(u.length>0){let e=await Oe(c.normalizedConfig);if(e.length>0){d=new et(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 Ny=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 Py(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=pp(t),o=n,s=!o,c=X(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,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>F(t.dataDir,o,c)}},u=new Ny,d=await My({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await mp({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=>Cv({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function Fy(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function Iy(e){if(!(e instanceof Error))return{errorValue:Fy(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]=Fy(n[e]));return t}async function Ly(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...Iy(e.error)}})}function Ry(e,t,n){return q.join(r(e,t,n),`pending-ui-tool.json`)}async function zy(e,t,n,i){let a=r(e,t,i);await K.mkdir(a,{recursive:!0}),await L(Ry(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function By(e,t,n){let r=await o(Ry(e,t,n));return r===null?null:JSON.parse(r)}async function Vy(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await zy(e,t,a,r),a}async function Hy(e,t,n,r,i){let a=await By(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 zy(e,t,o,i),o}async function Uy(e,t,n){try{await K.unlink(Ry(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function Wy(e,t,n,r){let i=await U(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 Gy(e,t,n,r,i,a){let o=await U(e,t,{storeName:a?.storeName});await Wy(e,t,n,a);let s=await tn(e,t,n,r,a);return s.goal&&await xy(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function Ky(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!At(t))}async function qy(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=Ro();if(i=await zo(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(Io(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Jy(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 Jy(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 Yy=2e4,Xy=15e4,Zy=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Qy(e){return q.join(e,`.aimax`)}async function $y(e){let t=Qy(e),n=[];for(let e of Zy){let r=q.join(t,e);try{let t=await K.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await K.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 eb(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(`
189
+ `)}`}async function Xv(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?Ce({...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 we,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=ke(c.normalizedConfig),d;if(u.length>0){let e=await Oe(c.normalizedConfig);if(e.length>0){d=new et(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 Zv=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 Qv(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Gp(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,workspaceDir:a,channel:t.channel,session:{getSessionId:()=>o,getSessionDir:()=>r(t.dataDir,o,c),getEntries:()=>F(t.dataDir,o,c)}},u=new Zv,d=await Xv({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await Kp({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=>V_({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function $v(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ey(e){if(!(e instanceof Error))return{errorValue:$v(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]=$v(n[e]));return t}async function ty(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ey(e.error)}})}function ny(e,t,n){return q.join(r(e,t,n),`pending-ui-tool.json`)}async function ry(e,t,n,i){let a=r(e,t,i);await K.mkdir(a,{recursive:!0}),await L(ny(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function iy(e,t,n){let r=await o(ny(e,t,n));return r===null?null:JSON.parse(r)}async function ay(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await ry(e,t,a,r),a}async function oy(e,t,n,r,i){let a=await iy(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 ry(e,t,o,i),o}async function sy(e,t,n){try{await K.unlink(ny(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function cy(e,t,n,r){let i=await U(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 ly(e,t,n,r,i,a){let o=await U(e,t,{storeName:a?.storeName});await cy(e,t,n,a);let s=await tn(e,t,n,r,a);return s.goal&&await zv(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function uy(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!At(t))}async function dy(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=yo();if(i=await bo(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(_o(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=fy(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 fy(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 py=2e4,my=15e4,hy=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function gy(e){return q.join(e,`.aimax`)}async function _y(e){let t=gy(e),n=[];for(let e of hy){let r=q.join(t,e);try{let t=await K.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await K.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 vy(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(`
156
190
  `),s].join(`
157
- `),truncated:!0,originalLength:r.length}}function tb(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function nb(e,t){let n=t?.maxChars??Yy,r=Math.max(1,t?.totalMaxChars??Math.max(n,Xy)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=tb(`[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}=eb(a.content??``,a.name,e),l=tb(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 rb=`You are a personal assistant running inside AiMax.`;async function ib(e){try{return{presetSystemPrompt:zt(await K.readFile(e,`utf-8`)).content.trim()||rb}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:rb};throw e}}async function ab(){return ib(`/aimax_pvc/system_prompt.md`)}async function ob(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await $y(t.dataDir),o=[],s=nb(a,{warn:e=>o.push(e)}),c=await ab();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}}),G.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await Zf(t.dataDir,r.pluginSkillDirs,l),d=await La({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}))}}),G.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}))}}),G.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 sb({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function sb(e){if(!e.enabled)return[];try{let t=await new ua({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 cb=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 lb={Inferred:1,Child:2,Own:3};var ub=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=fb(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,lb.Own)}addInferred(e){this.add(e,lb.Inferred)}addChild(e){e&&e.length>0&&this.add(e,lb.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=db(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=pb(e.url);return t?this.urlWhitelist.has(t):!1}};function db(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function fb(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function pb(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const mb=`crons`;function hb(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:Te(e.message)}}async function gb(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 wg({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 Ay({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 fy({entries:e.runParams.channel===`CRON`?[]:await F(e.runParams.dataDir,e.sessionId,X(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 _b(e,t){hv();let n=Date.now(),i=new Qa(e),a=new ub({urlWhitelist:e.artifactsUrlWhitelist}),o=Sy(e);G.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 Py({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;de(e.dataDir,{messageId:e.messageId,sessionId:d,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,d,X(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,{storeName:e.sessionStoreName})).length;if(G.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}}),G.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,gp({sessionId:d,title:Sv(s),channel:e.channel}),X(e)),e.pendingGoal){let t=await W(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await $n(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 ob({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await wy({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 G.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}}),G.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await cg({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=>_b(e,new Sm),createModel:Aa,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}}),G.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=Cb(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}}),G.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let I=new cb,L=``,R,z=!1,B=new en;await Wy(e.dataDir,d,B,{storeName:e.sessionStoreName}),w.signal;try{if(Ky(e)){let t=await qy({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return L=t.text,S(),Mv({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);z=t,c=t||c;try{await Vn(e.dataDir,d,{storeName:e.sessionStoreName},()=>$r(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof Rn))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await U(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await qr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof Rn)o=!0;else throw e}let u=!!(o||l&&ii(l)),p=si({hookRegistry:g,isGateActive:()=>u}),m=await ti(e.dataDir,d,O,{storeName:e.sessionStoreName}),_;if(o){let e=[`<goal_context>`,`Goal workflow state (goal/state.json) is corrupt and unreadable.`,`Call goal_repair_workflow_state with confirm:true to reinitialize from the saved objective before other goal workflow tools.`,`</goal_context>`,``].join(`
158
- `);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await ei(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});G.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await wg({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 ni(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?G.warn(`first agent turn completed with error`,C):G.info(`first agent turn completed`,C);let T=await Gy(e.dataDir,d,B,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`}),G.info(`announce loop started`,{sessionId:d});let D=await Ay({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 Gy(e.dataDir,d,B,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`}),Jr()){let n=new Kr;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=Dt;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Zr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:B,abortSignal:w.signal,executeTurn:async t=>{let n=await wg({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 Qr(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 Gy(e.dataDir,d,B,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 Ay({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 wv({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 gb({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?G.warn(`announce loop completed with error`,k):G.info(`announce loop completed`,k)}catch(t){if(Io(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await it(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}}),G.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 vb({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:z}),S(),Mv({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(Ie(t)){let r=t,o=r.request.outputSchema.properties??{};await Vy(e.dataDir,d,r.request,X(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}}),G.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 vb({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:z}),S(),Mv({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&&wb(t))R=`Run timed out after ${N}ms`;else throw await Ly({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),G.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 Gy(e.dataDir,d,B,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}B.clearActiveGoal(),Wh(d);try{A.processRegistry.disposeAll()}catch{}try{ze.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let V=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:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!R,error:R}});let H={sessionId:d,durationMs:Date.now()-n,inputTokens:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!R,error:R};return R?G.warn(`agent run completed with error`,H):G.info(`agent run completed`,H),await vb({runtime:A,resolvedModelId:M,usage:V,currentUserEntryCoveredByUsage:z}),await Y_({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:L,usage:V,durationMs:Date.now()-n,error:R}}),Mv({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:V,error:R,sessionEndOnly:b>0})}async function vb(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 yb(e){let t=Date.now(),i=new Qa(e),a=Sy(e),o=a.transcriptMessage.trim()||`CRON task`,c=e.sessionStoreName;G.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...hb(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,gp({sessionId:l,title:Sv(o),channel:e.channel}),{storeName:c});let f=await T(e.dataDir,e.channel,{storeName:mb});de(e.dataDir,{messageId:e.messageId,sessionId:f,sessionStoreName:mb,sessionDir:r(e.dataDir,f,{storeName:mb})}),await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:f,task:o}),G.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:f,taskLength:o.length,taskPreview:Te(o)});let m={...e,sessionId:f,sessionStoreName:mb,subagentContext:{depth:1,parentSessionId:l}},g,y=`done`;try{g=await _b(m,new Sm),g.error&&(y=`error`)}catch(n){let r=n instanceof Error?n.message:String(n);g={sessionId:f,text:``,usage:{input:0,output:0,total:0},durationMs:Date.now()-t,error:r,context:{snapshotPath:_(e.dataDir,f,{storeName:mb}),toolResultsDir:s(e.dataDir,f,{storeName:mb})}},y=`error`,G.error(`cron child run failed`,{parentSessionId:l,childSessionId:f,error:r})}await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:f,task:o,status:y}),G.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:f,status:y,durationMs:Date.now()-t,hasError:!!g.error});let b=Em({task:o,status:y,result:g.text,error:g.error}),x=new Date().toISOString();await h(e.dataDir,l,{role:`assistant`,content:b,timestamp:x,source:`cron`},{storeName:c});let C={task:o,status:y,content:b,childSessionId:f,createdAt:x};return await S(e.dataDir,l,C,{storeName:c}),await ee(e.dataDir,l,e=>bb(e,8),{storeName:c}),await u(e.dataDir,l,{},{storeName:c}),{...g,sessionId:l,context:{snapshotPath:_(e.dataDir,l,{storeName:c}),toolResultsDir:s(e.dataDir,l,{storeName:c})}}}function bb(e,t){if(t<=0)return e.filter(e=>!xb(e));let n=e.reduce((e,t,n)=>(xb(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!xb(e)||r.has(t))}function xb(e){return`source`in e&&e.source===`cron`}async function Sb(e,t){let n=async()=>{if(G.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,...hb(e)}),e.channel===`CRON`&&!e.subagentContext)return yb(e);let n=t??new Sm;try{return await _b(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:Iy(t)}),G.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};return e.onLog?ae(e.onLog,n):n()}function Cb(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function wb(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 Tb={"AGENTS.md":`---
191
+ `),truncated:!0,originalLength:r.length}}function yy(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function by(e,t){let n=t?.maxChars??py,r=Math.max(1,t?.totalMaxChars??Math.max(n,my)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=yy(`[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}=vy(a.content??``,a.name,e),l=yy(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 xy=`You are a personal assistant running inside AiMax.`;async function Sy(e){try{return{presetSystemPrompt:zt(await K.readFile(e,`utf-8`)).content.trim()||xy}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:xy};throw e}}async function Cy(){return Sy(`/aimax_pvc/system_prompt.md`)}async function wy(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await _y(t.dataDir),o=[],s=by(a,{warn:e=>o.push(e)}),c=await Cy();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}}),G.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await Mf(t.dataDir,r.pluginSkillDirs,l),d=await va({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}))}}),G.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}))}}),G.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 Ty({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function Ty(e){if(!e.enabled)return[];try{let t=await new Gi({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 Ey=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 Dy={Inferred:1,Child:2,Own:3};var Oy=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=Ay(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,Dy.Own)}addInferred(e){this.add(e,Dy.Inferred)}addChild(e){e&&e.length>0&&this.add(e,Dy.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=ky(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=jy(e.url);return t?this.urlWhitelist.has(t):!1}};function ky(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function Ay(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function jy(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const My=`crons`;function Ny(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:Te(e.message)}}async function Py(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 Hh({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 Jv({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 Av({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 Fy(e,t){N_();let n=Date.now(),i=new Na(e),a=new Oy({urlWhitelist:e.artifactsUrlWhitelist}),o=Bv(e);G.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 Qv({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;de(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(G.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}}),G.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,Jp({sessionId:d,title:B_(s),channel:e.channel}),$(e)),e.pendingGoal){let t=await W(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await $n(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 wy({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await Hv({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 G.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}}),G.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await Eh({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=>Fy(e,new kp),createModel:da,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}}),G.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=Vy(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}}),G.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let I=new Ey,L=``,R,z=!1,B=new en;await cy(e.dataDir,d,B,{storeName:e.sessionStoreName}),w.signal;try{if(uy(e)){let t=await dy({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return L=t.text,S(),X_({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);z=t,c=t||c;try{await Vn(e.dataDir,d,{storeName:e.sessionStoreName},()=>Fr(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof Rn))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await U(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await kr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof Rn)o=!0;else throw e}let u=!!(o||l&&Br(l)),p=Ur({hookRegistry:g,isGateActive:()=>u}),m=await Lr(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(`
192
+ `);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await Ir(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});G.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await Hh({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 Rr(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?G.warn(`first agent turn completed with error`,C):G.info(`first agent turn completed`,C);let T=await ly(e.dataDir,d,B,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`}),G.info(`announce loop started`,{sessionId:d});let D=await Jv({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 ly(e.dataDir,d,B,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`}),Ar()){let n=new Or;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=Dt;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Nr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:B,abortSignal:w.signal,executeTurn:async t=>{let n=await Hh({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 Pr(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 ly(e.dataDir,d,B,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 Jv({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 H_({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 Py({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?G.warn(`announce loop completed with error`,k):G.info(`announce loop completed`,k)}catch(t){if(_o(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await it(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}}),G.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 Iy({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:z}),S(),X_({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(Ie(t)){let r=t,o=r.request.outputSchema.properties??{};await ay(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}}),G.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 Iy({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:z}),S(),X_({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&&Hy(t))R=`Run timed out after ${N}ms`;else throw await ty({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),G.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 ly(e.dataDir,d,B,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}B.clearActiveGoal(),ch(d);try{A.processRegistry.disposeAll()}catch{}try{ze.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let V=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:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!R,error:R}});let H={sessionId:d,durationMs:Date.now()-n,inputTokens:V.input,outputTokens:V.output,totalTokens:V.total,hasError:!!R,error:R};return R?G.warn(`agent run completed with error`,H):G.info(`agent run completed`,H),await Iy({runtime:A,resolvedModelId:M,usage:V,currentUserEntryCoveredByUsage:z}),await p_({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:L,usage:V,durationMs:Date.now()-n,error:R}}),X_({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:V,error:R,sessionEndOnly:b>0})}async function Iy(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 Ly(e){let t=Date.now(),i=new Na(e),a=Bv(e),o=a.transcriptMessage.trim()||`CRON task`,c=My;G.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...Ny(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,Jp({sessionId:l,title:B_(o),channel:e.channel}),{storeName:c});let f=r(e.dataDir,l,{storeName:c});de(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:My,subagent:m});await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:g,task:o}),G.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:g,taskLength:o.length,taskPreview:Te(o)});let y={...e,sessionId:g,sessionStoreName:My,sessionPathScope:{subagent:m},subagentContext:{depth:1,parentSessionId:l}},b,x=`done`;try{b=await Fy(y,new kp),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:My,subagent:m}),toolResultsDir:s(e.dataDir,g,{storeName:My,subagent:m})}},x=`error`,G.error(`cron child run failed`,{parentSessionId:l,childSessionId:g,error:r})}de(e.dataDir,{messageId:e.messageId,sessionId:l,sessionStoreName:c,sessionDir:f}),await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:g,task:o,status:x}),G.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:g,status:x,durationMs:Date.now()-t,hasError:!!b.error});let C=Np({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=>Ry(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 Ry(e,t){if(t<=0)return e.filter(e=>!zy(e));let n=e.reduce((e,t,n)=>(zy(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!zy(e)||r.has(t))}function zy(e){return`source`in e&&e.source===`cron`}async function By(e,t){let n=async()=>{if(G.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,...Ny(e)}),e.channel===`CRON`&&!e.subagentContext)return Ly(e);let n=t??new kp;try{return await Fy(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:ey(t)}),G.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};return e.onLog?ae(e.onLog,n):n()}function Vy(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Hy(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 Uy={"AGENTS.md":`---
159
193
  title: "AGENTS.md Template"
160
194
  summary: ".aimax template for AGENTS.md"
161
195
  read_when:
@@ -448,7 +482,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
448
482
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
449
483
 
450
484
  Add whatever helps you do your job. This is your cheat sheet.
451
- `},Eb=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Db(e,t){try{if(!(await K.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 K.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Ob(e,t,n){try{if(!(await K.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 K.mkdir(q.dirname(e),{recursive:!0});try{await K.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 kb(e){let t=Qy(e);return[e,t,q.join(t,`skills`),q.join(t,`sessions`),q.join(t,`memory`),q.join(e,`workspace`)]}function Ab(e){let t=Qy(e);return[...Eb.filter(e=>e!==`BOOTSTRAP.md`).map(e=>q.join(t,e)),q.join(t,`MEMORY.md`)]}function jb(e){return q.join(Qy(e),`.bootstrapped`)}async function Mb(e){try{return(await K.stat(jb(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Nb(e){let t=jb(e);await K.mkdir(q.dirname(t),{recursive:!0}),await K.writeFile(t,``,{encoding:`utf-8`})}async function Pb(e){let t=[],n=[];for(let n of kb(e))try{(await K.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Ab(e))try{(await K.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 Fb(e){return(await Pb(e)).ready}async function Ib(e){if(await Mb(e))return{ready:!0,performedBootstrap:!1};if((await Pb(e)).ready)return await Nb(e),{ready:!0,performedBootstrap:!1};let t=await Lb(e);return await Nb(e),{ready:!0,performedBootstrap:!0,result:t}}async function Lb(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=Qy(e),r=q.join(e,`workspace`),i=q.join(n,`skills`),a=q.join(n,`sessions`),o=q.join(n,`memory`);await Db(e,t),await Db(n,t),await Db(i,t),await Db(a,t),await Db(o,t),await Db(r,t);for(let e of Eb){let r=Tb[e]??``;await Ob(q.join(n,e),r,t)}return await Ob(q.join(n,`MEMORY.md`),``,t),t}async function Rb(e){let t=q.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await K.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 zb(e,t){let n=q.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 K.mkdir(q.dirname(n),{recursive:!0}),await K.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function Bb(e,t){let n=await Rb(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 Vb(e,t=7){let n=await Rb(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 zb(e,n),i}var Hb=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function Ub(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function Wb(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 U(t,n,s);if(!l){let e=await W(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await $n(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`created`,goal:e}}let u=(await B(t,n,l,s)).trim();if(u!==c){if(!a)throw new Hb(`A different goal already exists for this session. Use --force to replace it.`,Ub(u));let e=await W(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await $n(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new Hb(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,Ub(u));if(a){let e=await W(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await $n(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 H(t,n,d,{storeName:o,eventSource:`cli`})}}async function Gb(e,t,n,r){let i=await st(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?kt(i.request)?(await rt(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 Kb(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ot(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 Gb(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await rt(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 qb={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 Jb(e){return e.action===`timeout`?qb.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?qb.approval.summary.approved:qb.approval.summary.denied}function Yb(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:Jb(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function Xb(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 Zb(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 Qb(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
485
+ `},Wy=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Gy(e,t){try{if(!(await K.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 K.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Ky(e,t,n){try{if(!(await K.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 K.mkdir(q.dirname(e),{recursive:!0});try{await K.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 qy(e){let t=gy(e);return[e,t,q.join(t,`skills`),q.join(t,`sessions`),q.join(t,`memory`),q.join(e,`workspace`)]}function Jy(e){let t=gy(e);return[...Wy.filter(e=>e!==`BOOTSTRAP.md`).map(e=>q.join(t,e)),q.join(t,`MEMORY.md`)]}function Yy(e){return q.join(gy(e),`.bootstrapped`)}async function Xy(e){try{return(await K.stat(Yy(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Zy(e){let t=Yy(e);await K.mkdir(q.dirname(t),{recursive:!0}),await K.writeFile(t,``,{encoding:`utf-8`})}async function Qy(e){let t=[],n=[];for(let n of qy(e))try{(await K.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of Jy(e))try{(await K.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 $y(e){return(await Qy(e)).ready}async function eb(e){if(await Xy(e))return{ready:!0,performedBootstrap:!1};if((await Qy(e)).ready)return await Zy(e),{ready:!0,performedBootstrap:!1};let t=await tb(e);return await Zy(e),{ready:!0,performedBootstrap:!0,result:t}}async function tb(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=gy(e),r=q.join(e,`workspace`),i=q.join(n,`skills`),a=q.join(n,`sessions`),o=q.join(n,`memory`);await Gy(e,t),await Gy(n,t),await Gy(i,t),await Gy(a,t),await Gy(o,t),await Gy(r,t);for(let e of Wy){let r=Uy[e]??``;await Ky(q.join(n,e),r,t)}return await Ky(q.join(n,`MEMORY.md`),``,t),t}async function nb(e){let t=q.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await K.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 rb(e,t){let n=q.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 K.mkdir(q.dirname(n),{recursive:!0}),await K.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function ib(e,t){let n=await nb(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 ab(e,t=7){let n=await nb(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 rb(e,n),i}var ob=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function sb(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function cb(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 U(t,n,s);if(!l){let e=await W(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await $n(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`created`,goal:e}}let u=(await B(t,n,l,s)).trim();if(u!==c){if(!a)throw new ob(`A different goal already exists for this session. Use --force to replace it.`,sb(u));let e=await W(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await $n(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new ob(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,sb(u));if(a){let e=await W(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await $n(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 H(t,n,d,{storeName:o,eventSource:`cli`})}}async function lb(e,t,n,r){let i=await st(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?kt(i.request)?(await rt(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 ub(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await ot(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 lb(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await rt(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 db={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 fb(e){return e.action===`timeout`?db.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?db.approval.summary.approved:db.approval.summary.denied}function pb(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:fb(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function mb(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 hb(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 gb(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
452
486
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
453
487
  `)):(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(`
454
- `))}export{ua as AutoSkillsLoader,Zy as BOOTSTRAP_FILE_NAMES,Yy as BOOTSTRAP_MAX_CHARS,Xy as BOOTSTRAP_TOTAL_MAX_CHARS,rn as CLARIFY_ACCEPTANCE_TEXT,ri as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,nn as CLARIFY_TASK_TITLE,Kr as ContinuationState,Rn as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,Gr as ENV_GOAL_CONTINUATION,Rr as FIRST_TURN_GOAL_WORKFLOW_INTRO,Iv as GOAL_MULTILINE_TEMPLATE_EXAMPLE,Fn as GOAL_WORKFLOW_STATE_VERSION,en as GoalAccounting,Hb as GoalConflictError,qb as HITL_MESSAGES,Fo as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,xm as MAX_CHILDREN_PER_SESSION,bm as MAX_SUBAGENT_DEPTH,ze as MemoryIndexManager,Pe as PLUGIN_MANIFEST_FILENAME,ye as PLUGIN_MANIFEST_FILENAMES,we as PluginHookRegistry,he as PluginToolRegistry,ja as SYSTEM_AGENTS_DIR,Sm as SubagentRegistry,oe as UiToolPauseSignal,Ct as addAgent,yt as addBinding,Na as agentDirCandidates,Va as agentVisibility,Qy as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,z as appendGoalEvent,$d as appendRecentToMemory,i as appendSessionFile,Qd as appendToMemory,h as appendTranscriptEntry,Wb as applyCliGoalBeforeRun,Jb as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,Wi as autoSkillsDir,Lb as bootstrapMountLayout,Ga as buildAgentDelegationPrompt,Ka as buildAgentTaskPrompt,Rv as buildAimaxGoalCliHelpExtra,nb as buildBootstrapContextFiles,Vr as buildBudgetLimitPrompt,Br as buildContinuationPrompt,zr as buildFirstTurnGoalWorkflowPrompt,Ur as buildGoalContextItem,Lv as buildGoalSlashHelpText,Hr as buildObjectiveUpdatedPrompt,Qb as buildResumeNarration,np as buildSkillsPrompt,Em as buildSubagentAnnounceMessage,lh as buildSystemPrompt,Vb as cleanupOldSubagentRecords,ct as clearPendingHitl,Uy as clearPendingUiTool,j as collapseLogPath,ni as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,Xr as continuationTurnHadMeaningfulOutput,Fa as createAgentDefinitionsContext,Lm as createAgentTools,jd as createApplyPatchTool,pm as createAutoSkillCategoriesTool,mm as createAutoSkillListTool,hm as createAutoSkillSearchTool,gm as createAutoSkillViewTool,ca as createAutoSkillsLoader,fd as createBashTool,Am as createBatchSubagentSpawnTool,Ve as createBuiltinMemoryProvider,Yu as createContextManager,Ke as createDefaultMemoryProvider,Sd as createEditFileTool,sd as createExecTool,Im as createImageTool,wd as createListDirTool,cf as createMemoryAppendTool,Sf as createMemoryForgetTool,of as createMemoryGetTool,bf as createMemoryListTool,vf as createMemoryLogTool,rf as createMemorySearchTool,wf as createMemoryUpdateTool,uf as createMemoryWriteTool,it as createPendingHitl,Vy as createPendingUiTool,le as createPluginProgressEmitter,ve as createPluginRuntime,dd as createProcessTool,vd as createReadFileTool,T as createSession,bu as createSessionContextStore,Ef as createSessionSearchTool,op as createSkillListTool,sp as createSkillLoadTool,km as createSubagentSpawnTool,Pm as createSubagentsTool,Re as createUiTool,bd as createWriteFileTool,N as cronExecutionsPath,_e as defaultUiToolInputSchema,ie as deleteGoal,Qn as deleteGoalWorkflow,tf as deleteMemoryFile,De as discoverAIMaxPlugins,by as emitGoalUpdatedProgress,Ib as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,_n as extractWorkflowPlanFromObjective,Ua as filterSkillsForAgent,Wa as filterToolsForAgent,Ba as findAgentDefinition,$f as findSkillByName,tn as flushAccounting,Yb as formatApprovalResolution,Xb as formatClarifyResolution,Zb as formatReviewResolution,_v as generateSessionTitle,gt as getAgentConfig,Zd as getMemoryLines,je as getPluginSystem,Wn as goalArtifactsDir,te as goalDir,R as goalEventsPath,re as goalObjectiveMdPath,V as goalPath,Un as goalWorkflowPlanPath,Hn as goalWorkflowStatePath,Mb as hasBootstrapSentinel,nt as hitlHistoryPath,$n as initializeGoalWorkflow,Ce as initializePluginSystem,Pb as inspectBootstrapMountLayout,k as inspectSession,si as installClarifyFirstTurnGate,Fb as isBootstrapMountLayoutReady,ai as isClarifyFirstTurnBlockedTool,ii as isClarifyWorkflowTask,Jr as isContinuationEnabled,Wr as isGoalContext,Io as isHitlPauseSignal,Ie as isUiToolPauseSignal,ut as listAgents,Qv as listAvailableSlashCommands,bt as listBindings,qd as listMemoryFiles,E as listSessionSummaries,x as listSessions,Bb as listSubagentRunsFromDisk,Ra as loadAgentDefinitionsFromDir,St as loadAgentsConfig,b as loadArtifactOperations,$y as loadBootstrapFiles,m as loadCronExecutionRecords,st as loadPendingHitl,st as readPendingHitl,By as loadPendingUiTool,By as readPendingUiTool,be as loadPluginManifest,Ee as loadPluginManifestRegistry,Me as loadPlugins,P as loadSessionContextSnapshot,$s as loadSessionExportSnapshots,I as loadSessionMetadata,tp as loadSkillView,Xf as loadSkills,Qf as loadSkillsFromDirs,Zf as loadSkillsWithPluginDirs,Rb as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,F as loadTranscript,qr as loadWorkflowPromptContext,Zr as maybeContinueGoalIfIdle,Ud as memoryDir,f as metadataPath,ne as mirrorGoalStatusToSession,dt as normalizeAgentId,Se as normalizePluginsConfig,t as normalizeSessionStoreName,za as parseAgentDefinition,tt as pendingHitlPath,Ry as pendingUiToolPath,Qs as persistSessionExportSnapshots,ge as preloadPluginSystem,Ne as prepareSystemRuntime,ei as prependFirstGoalWorkflowSteeringIfNeeded,ti as prependObjectiveUpdatedSteeringIfNeeded,Wd as primaryMemoryPath,Ha as publicAgentDefinitions,U as readGoal,Jn as readGoalWorkflowState,Xn as readGoalWorkflowSummary,at as readHitlHistory,Jd as readMemoryFile,Yd as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,$r as recoverBlockedWorkflowOnUserTurn,Ye as registerEmbeddingProvider,$e as registerMemoryProvider,_t as removeAgent,wt as removeBindings,bn as renderGoalPlanMarkdown,Yn as repairGoalWorkflowState,ef as replaceMemoryFile,Je as resetEmbeddingProviderRegistryForTests,Xe as resetMemoryProviderRegistryForTests,La as resolveAgentDefinitionsContext,ft as resolveAgentDir,pt as resolveAgentIdByBinding,xt as resolveAgentsConfigPath,vt as resolveDefaultAgentId,Ze as resolveEmbeddingProvider,B as resolveGoalObjective,Zn as resolveGoalToolWorkflowView,Kb as resolveHitlRequest,Kb as resolvePendingHitl,Qe as resolveMemoryProvider,We as resolveMemoryProviderOrDefault,ht as resolveModelFallbacks,mt as resolveModelString,Hy as resolvePendingUiTool,Ae as resolvePluginManifestPath,ee as rewriteTranscript,Sb as runAgent,lt as saveAgentsConfig,p as saveSessionMetadata,zb as saveSubagentRegistryToDisk,Pa as scanAgentDefinitions,Xd as searchMemory,Xs as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,Ys as sessionToolsSnapshotPath,e as sessionsDir,Yr as shouldContinueGoal,Wf as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,rt as transitionHitlStatus,Tt as updateAgent,Et as updateAgentIdentity,H as updateGoal,u as updateSessionMetadata,xe as validatePluginsConfig,Gb as validateResume,Vn as withGoalWorkflowLock,uh as wrapToolsWithHooks,W as writeGoal,L as writeSessionFile};
488
+ `))}export{Gi as AutoSkillsLoader,hy as BOOTSTRAP_FILE_NAMES,py as BOOTSTRAP_MAX_CHARS,my as BOOTSTRAP_TOTAL_MAX_CHARS,rn as CLARIFY_ACCEPTANCE_TEXT,zr as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,nn as CLARIFY_TASK_TITLE,Or as ContinuationState,Rn as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,Dr as ENV_GOAL_CONTINUATION,br as FIRST_TURN_GOAL_WORKFLOW_INTRO,ev as GOAL_MULTILINE_TEMPLATE_EXAMPLE,Fn as GOAL_WORKFLOW_STATE_VERSION,en as GoalAccounting,ob as GoalConflictError,db as HITL_MESSAGES,go as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,Op as MAX_CHILDREN_PER_SESSION,Dp as MAX_SUBAGENT_DEPTH,ze as MemoryIndexManager,Pe as PLUGIN_MANIFEST_FILENAME,ye as PLUGIN_MANIFEST_FILENAMES,we as PluginHookRegistry,he as PluginToolRegistry,fa as SYSTEM_AGENTS_DIR,kp as SubagentRegistry,oe as UiToolPauseSignal,Ct as addAgent,yt as addBinding,ma as agentDirCandidates,Sa as agentVisibility,gy as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,z as appendGoalEvent,Pd as appendRecentToMemory,i as appendSessionFile,Nd as appendToMemory,h as appendTranscriptEntry,cb as applyCliGoalBeforeRun,fb as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,Ei as autoSkillsDir,tb as bootstrapMountLayout,Ea as buildAgentDelegationPrompt,Da as buildAgentTaskPrompt,nv as buildAimaxGoalCliHelpExtra,by as buildBootstrapContextFiles,Cr as buildBudgetLimitPrompt,Sr as buildContinuationPrompt,xr as buildFirstTurnGoalWorkflowPrompt,Tr as buildGoalContextItem,tv as buildGoalSlashHelpText,wr as buildObjectiveUpdatedPrompt,gb as buildResumeNarration,Lf as buildSkillsPrompt,Np as buildSubagentAnnounceMessage,Dm as buildSystemPrompt,ab as cleanupOldSubagentRecords,ct as clearPendingHitl,sy as clearPendingUiTool,j as collapseLogPath,Rr as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,Mr as continuationTurnHadMeaningfulOutput,ga as createAgentDefinitionsContext,$p as createAgentTools,fd as createApplyPatchTool,bp as createAutoSkillCategoriesTool,xp as createAutoSkillListTool,Sp as createAutoSkillSearchTool,Cp as createAutoSkillViewTool,Ui as createAutoSkillsLoader,qu as createBashTool,Lp as createBatchSubagentSpawnTool,Ve as createBuiltinMemoryProvider,Au as createContextManager,Ke as createDefaultMemoryProvider,rd as createEditFileTool,Hu as createExecTool,Qp as createImageTool,ad as createListDirTool,Hd as createMemoryAppendTool,nf as createMemoryForgetTool,Bd as createMemoryGetTool,ef as createMemoryListTool,Qd as createMemoryLogTool,Rd as createMemorySearchTool,af as createMemoryUpdateTool,Wd as createMemoryWriteTool,it as createPendingHitl,ay as createPendingUiTool,le as createPluginProgressEmitter,ve as createPluginRuntime,Ku as createProcessTool,$u as createReadFileTool,T as createSession,tu as createSessionContextStore,sf as createSessionSearchTool,Vf as createSkillListTool,Hf as createSkillLoadTool,Ip as createSubagentSpawnTool,Vp as createSubagentsTool,Re as createUiTool,td as createWriteFileTool,N as cronExecutionsPath,_e as defaultUiToolInputSchema,ie as deleteGoal,Qn as deleteGoalWorkflow,Id as deleteMemoryFile,De as discoverAIMaxPlugins,Rv as emitGoalUpdatedProgress,eb as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,_n as extractWorkflowPlanFromObjective,wa as filterSkillsForAgent,Ta as filterToolsForAgent,xa as findAgentDefinition,Pf as findSkillByName,tn as flushAccounting,pb as formatApprovalResolution,mb as formatClarifyResolution,hb as formatReviewResolution,F_ as generateSessionTitle,gt as getAgentConfig,Md as getMemoryLines,je as getPluginSystem,Wn as goalArtifactsDir,te as goalDir,R as goalEventsPath,re as goalObjectiveMdPath,V as goalPath,Un as goalWorkflowPlanPath,Hn as goalWorkflowStatePath,Xy as hasBootstrapSentinel,nt as hitlHistoryPath,$n as initializeGoalWorkflow,Ce as initializePluginSystem,Qy as inspectBootstrapMountLayout,k as inspectSession,Ur as installClarifyFirstTurnGate,$y as isBootstrapMountLayoutReady,Vr as isClarifyFirstTurnBlockedTool,Br as isClarifyWorkflowTask,Ar as isContinuationEnabled,Er as isGoalContext,_o as isHitlPauseSignal,Ie as isUiToolPauseSignal,ut as listAgents,gv as listAvailableSlashCommands,bt as listBindings,Od as listMemoryFiles,E as listSessionSummaries,x as listSessions,ib as listSubagentRunsFromDisk,ya as loadAgentDefinitionsFromDir,St as loadAgentsConfig,b as loadArtifactOperations,_y as loadBootstrapFiles,m as loadCronExecutionRecords,st as loadPendingHitl,st as readPendingHitl,iy as loadPendingUiTool,iy as readPendingUiTool,be as loadPluginManifest,Ee as loadPluginManifestRegistry,Me as loadPlugins,P as loadSessionContextSnapshot,Ps as loadSessionExportSnapshots,I as loadSessionMetadata,If as loadSkillView,jf as loadSkills,Nf as loadSkillsFromDirs,Mf as loadSkillsWithPluginDirs,nb as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,F as loadTranscript,kr as loadWorkflowPromptContext,Nr as maybeContinueGoalIfIdle,wd as memoryDir,f as metadataPath,ne as mirrorGoalStatusToSession,dt as normalizeAgentId,Se as normalizePluginsConfig,t as normalizeSessionStoreName,ba as parseAgentDefinition,tt as pendingHitlPath,ny as pendingUiToolPath,Ns as persistSessionExportSnapshots,ge as preloadPluginSystem,Ne as prepareSystemRuntime,Ir as prependFirstGoalWorkflowSteeringIfNeeded,Lr as prependObjectiveUpdatedSteeringIfNeeded,Td as primaryMemoryPath,Ca as publicAgentDefinitions,U as readGoal,Jn as readGoalWorkflowState,Xn as readGoalWorkflowSummary,at as readHitlHistory,kd as readMemoryFile,Ad as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,Fr as recoverBlockedWorkflowOnUserTurn,Ye as registerEmbeddingProvider,$e as registerMemoryProvider,_t as removeAgent,wt as removeBindings,bn as renderGoalPlanMarkdown,Yn as repairGoalWorkflowState,Fd as replaceMemoryFile,Je as resetEmbeddingProviderRegistryForTests,Xe as resetMemoryProviderRegistryForTests,va as resolveAgentDefinitionsContext,ft as resolveAgentDir,pt as resolveAgentIdByBinding,xt as resolveAgentsConfigPath,vt as resolveDefaultAgentId,Ze as resolveEmbeddingProvider,B as resolveGoalObjective,Zn as resolveGoalToolWorkflowView,ub as resolveHitlRequest,ub as resolvePendingHitl,Qe as resolveMemoryProvider,We as resolveMemoryProviderOrDefault,ht as resolveModelFallbacks,mt as resolveModelString,oy as resolvePendingUiTool,Ae as resolvePluginManifestPath,ee as rewriteTranscript,By as runAgent,lt as saveAgentsConfig,p as saveSessionMetadata,rb as saveSubagentRegistryToDisk,ha as scanAgentDefinitions,jd as searchMemory,js as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,As as sessionToolsSnapshotPath,e as sessionsDir,jr as shouldContinueGoal,Tf as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,rt as transitionHitlStatus,Tt as updateAgent,Et as updateAgentIdentity,H as updateGoal,u as updateSessionMetadata,xe as validatePluginsConfig,lb as validateResume,Vn as withGoalWorkflowLock,Om as wrapToolsWithHooks,W as writeGoal,L as writeSessionFile};