@gencode/agents 0.12.0 → 0.13.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,152 +1,164 @@
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 ee,w as P,x as F,y as I,z as L}from"./session-DbQpczup.js";import{n as R,t as te}from"./goal-events-DvF1LRBK.js";import{c as z,i as ne,l as B,n as V,o as re,r as ie,s as H,t as ae,u as oe}from"./goal-store-DKeFVjM4.js";import{a as se,c as ce,i as le,l as ue,n as de,o as fe,r as pe,s as me,u as he}from"./builtin-provider-Bv6TuIMf.js";import{i as ge,n as _e,r as ve}from"./provider-registry-Kh5nNG84.js";import{i as ye,t as be}from"./host-CQ2BhNzZ.js";import{a as xe,i as Se,l as Ce,n as we,o as Te,r as Ee,s as De,t as Oe}from"./session-store-Ddm_lIaP.js";import{_ as ke,a as Ae,c as je,d as Me,f as Ne,g as Pe,h as Fe,i as Ie,l as Le,m as Re,n as ze,o as Be,p as Ve,s as He,t as Ue,u as We,v as Ge,y as Ke}from"./config-BRWO3tCu.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as qe,formatTaskForDisplay as Je,isHitlExpired as Ye,isHitlTool as Xe,validateUiToolResult as Ze}from"@gencode/shared";import U,{readFile as Qe}from"node:fs/promises";import W,{join as $e}from"node:path";import{createHash as et,randomBytes as tt,randomUUID as nt}from"node:crypto";import rt from"node:os";import{spawn as it}from"node:child_process";import{TextDecoder as at}from"node:util";import ot from"gray-matter";import{Agent as st}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as ct}from"node:async_hooks";import G from"node:fs";import lt from"log4js";import ut from"openai";import{Type as K,calculateCost as dt,clampThinkingLevel as ft,createAssistantMessageEventStream as pt,getEnvApiKey as mt,parseStreamingJson as ht,registerApiProvider as gt,registerBuiltInApiProviders as _t,streamSimple as vt}from"@earendil-works/pi-ai";import{fileURLToPath as yt}from"node:url";import{isBinaryFile as bt}from"isbinaryfile";import xt from"ajv";import{createJiti as St}from"jiti";var Ct=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 wt(e,t,n,r,i){let a=await H(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await B(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const Tt=`clarify plan and acceptance`,Et=`补齐后续 task list、每个 task 的验收项和当前下一步`,Dt={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},Ot=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function kt(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function At(e,t){let n=kt(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function jt(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 Mt(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(Dt))At(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?jt(t.steps):[],acceptance:t.acceptance?jt(t.acceptance):[],raw:e.trim()}}function Nt(e){let t=e.toLowerCase();return Ot.some(e=>t.includes(e.toLowerCase()))}function Pt(e){return e.some(Nt)}function Ft(e,t){return{id:e,text:t,required:!0}}function It(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 Lt(e){return It({id:`task-1`,kind:`clarify`,title:Tt,status:`doing`,acceptanceCriteria:[Ft(`ac-1`,Et)],updatedAt:e})}function Rt(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>Ft(`ac-${t+1}`,e)):[Ft(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>It({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[Ft(`ac-1`,`完成:${e}`)],updatedAt:n}))}function zt(e){let t=new Date().toISOString(),n=Mt(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:Rt(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&Pt(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:Rt([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&Pt(jt(n.raw))){let e=jt(n.raw).filter(Nt);return{interpretation:r,assumptions:i,openQuestions:a,tasks:Rt([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[Lt(t)]}}function Bt(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function Vt(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>Bt(n.has(e.id),e)),``].join(`
2
- `)}function Ht(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[Vt(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
- `)}const Ut=process.platform===`win32`;function Wt(e){return Ut?{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 Gt(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(Ut&&typeof e.pid==`number`){let n=[`/pid`,String(e.pid),`/T`];t===`SIGKILL`&&n.push(`/F`);try{it(`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 Kt=2e5;function qt(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Jt(e,t){let n=e+t;return n.length<=Kt?{text:n,truncated:!1}:{text:n.slice(-Kt),truncated:!0}}function Yt(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Jt(e.output,r);e.output=i.text;let a=Jt(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Xt(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:qt(e.output),stdoutTail:qt(e.stdout),stderrTail:qt(e.stderr),outputTruncated:e.outputTruncated}}function Zt(e,t){return t?e.scopeKey===t:!0}function Qt(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function $t(e){return e?e.split(/\r?\n/):[]}function en(e){let t=$t(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=Qt(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 tn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function nn(){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),tn(e))};return{start(t){let{file:n,args:r,shell:a}=Wt(t.command),o=it(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!Ut}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:nt(),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=>Yt(l,`stdout`,e)),o.stderr.on(`data`,e=>Yt(l,`stderr`,e));let u=e=>t=>{Yt(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=Qt(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,Yt(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),Gt(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&Gt(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),Yt(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`)})}),Xt(l)},get(e,t){let n=r(e);return!n||!Zt(n,t)?null:Xt(n)},list(n){return[...e.values(),...t.values()].filter(e=>Zt(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Xt(e))},async wait(e,t,n){let i=r(e);if(!i||!Zt(i,t))return null;if(i.status!==`running`)return Xt(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||!Zt(a,t)?null:Xt(a)},readLog(e){let t=r(e.sessionId);return!t||!Zt(t,e.scopeKey)?null:en({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!Zt(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||!Zt(n,t))return null;if(n.status!==`running`)return Xt(n);n.status=`killed`,Gt(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&Gt(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?Xt(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,Gt(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&Gt(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const rn=1;var an=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},on=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},sn=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 cn=new Map;function ln(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function un(e,t,n,r){let i=ln(e,t,n),a=cn.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});cn.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function dn(e,t,n){return W.join(V(e,t,n),`state.json`)}function fn(e,t,n){return W.join(V(e,t,n),`plan.md`)}function pn(e,t,n){return W.join(V(e,t,n),`artifacts`)}async function mn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${tt(4).toString(`hex`)}.tmp`;try{await U.writeFile(n,t,`utf-8`),await U.rename(n,e)}finally{await U.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function hn(e){if(e.version!==1)throw new an(e.version)}function gn(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 _n(e,t,n){let r=dn(e,t,n);try{let e=await U.readFile(r,`utf-8`);try{let t=JSON.parse(e);return hn(t),t}catch(t){throw t instanceof an?t:new sn(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof sn||e instanceof an?e:new sn(`corrupt_goal_workflow_state`,{cause:e})}}async function vn(e,t,n){let r=dn(e,t,n),i;try{i=await U.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return hn(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof an)throw e}let a=await H(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await z(e,t,a,n)).trim();if(!o)throw Error(`repairGoalWorkflowState requires a non-empty objective`);let s=`${r}.corrupt.${new Date().toISOString().replace(/[:.]/g,`-`)}.bak`,c=null;try{await U.writeFile(s,i,`utf-8`),c=s}catch{}return await Sn(e,t,{goalId:a.goalId,objective:o},n),await q(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 yn(e,t,n){let r=await _n(e,t,n);return r?gn(r):null}async function bn(e,t,n){let r=await _n(e,t,n);return r?{goalState:gn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function xn(e,t,n){let r=dn(e,t,n),i=fn(e,t,n),a=pn(e,t,n);await Promise.all([U.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),U.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),U.rm(a,{recursive:!0,force:!0})])}async function Sn(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await xn(e,t,r);let a=zt(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=V(e,t,r);await U.mkdir(l,{recursive:!0}),await mn(dn(e,t,r),JSON.stringify(c,null,2));let u=Ht(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await mn(fn(e,t,r),u),c}const Cn=1048576,wn=/KEY|TOKEN|SECRET|PASSWORD|COOKIE|AUTH/i,Tn=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g],En=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.pdf`]);function Dn(e,t,n){return W.join(pn(e,t,n),`registry.jsonl`)}function On(e,t,n){return W.join(pn(e,t,n),`notes`)}function kn(e,t,n){return W.join(pn(e,t,n),`commands`)}function An(e,t,n){return W.join(pn(e,t,n),`snapshots`)}function jn(e,t,n){return W.join(V(e,t,n),`plan-meta.json`)}function Mn(e){let t=e,n=!1;for(let e of Tn)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function Nn(e){return`sha256:${et(`sha256`).update(e).digest(`hex`)}`}async function Pn(e){return Nn(await U.readFile(e))}function Fn(e,t){let n=W.normalize(e);return t.some(e=>{let t=W.normalize(e);return n===t||n.startsWith(t+W.sep)})}function In(e){let t=[W.normalize(e.workspaceDir),W.normalize(rt.tmpdir())],n=e.projectDir?.trim();n&&t.push(W.normalize(n));let r=W.join(e.dataDir,`workspace`);return t.includes(W.normalize(r))||t.push(W.normalize(r)),t}function Ln(e,t){return t?.trim()?W.isAbsolute(t)?W.normalize(t):W.normalize(W.join(e,t)):e}function Rn(e,t){return e.byteLength<=t?{data:e,truncated:!1,originalBytes:e.byteLength}:{data:e.subarray(0,t),truncated:!0,originalBytes:e.byteLength}}function zn(e){return`${e}-${Date.now().toString(36)}-${tt(3).toString(`hex`)}`}async function Bn(e,t,n,r){let i=await Vn(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${zn(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function Vn(e,t,n){let r=Dn(e,t,n);try{let e=await U.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 on(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Hn(e,t,n,r){let i=Dn(e,t,r);await U.mkdir(W.dirname(i),{recursive:!0}),await U.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Un(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 Vn(e,t,r),o=new Map(a.map(e=>[e.id,e])),s=[],c=Wn(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?W.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 U.readFile(n);if(t.hash&&Nn(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?W.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 U.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 Pn(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?W.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 U.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 Wn(e,t,n){return W.dirname(V(e,t,n))}async function Gn(e,t,n,r){hn(n),await mn(dn(e,t,r),JSON.stringify(n,null,2))}async function Kn(e,t,n){let r=jn(e,t,n);try{let e=await U.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function qn(e,t,n,r){await mn(jn(e,t,r),JSON.stringify(n,null,2))}async function Jn(e,t,n,r){let i=await Kn(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 qn(e,t,a,r),a}async function Yn(e,t,n,r){try{let i=Ht(n,await Kn(e,t,r));return await mn(fn(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 q(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 U.mkdir(W.dirname(s),{recursive:!0}),await U.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}function Xn(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 Zn(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 Qn(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 Bn(e,t,n.kind,r),a=i.split(`:`)[1]??zn(n.kind),o=On(e,t,r);await U.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=W.join(On(e,t,r),`${a}.md`),l=Mn(n.content);await U.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 Hn(e,t,u,r)}catch{return await U.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}async function $n(e,t,n,r){let i=Ln(n.workspaceDir,n.cwd);if(!Fn(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=nn(),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=Rn(d,Cn),m=Rn(f,Cn),h=Mn(p.data.toString(`utf-8`)),g=Mn(m.data.toString(`utf-8`)),_=h.redactionIncomplete||g.redactionIncomplete,v=await Bn(e,t,`command`,r),y=v.split(`:`)[1]??zn(`command`),b=kn(e,t,r);await U.mkdir(b,{recursive:!0});let x=`goal/artifacts/commands/${y}.out.txt`,S=`goal/artifacts/commands/${y}.err.txt`,C=W.join(b,`${y}.out.txt`),w=W.join(b,`${y}.err.txt`);await U.writeFile(C,h.text,`utf-8`),await U.writeFile(w,g.text,`utf-8`);let T=Object.keys({...process.env,...n.baseEnv}).filter(e=>wn.test(e)),E={id:v,kind:`command`,command:Mn(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:Nn(h.text),createdAt:new Date().toISOString()};try{await Hn(e,t,E,r)}catch{return await Promise.all([U.unlink(C).catch(()=>{}),U.unlink(w).catch(()=>{})]),{error:`registry_write_failed`}}return{evidenceRef:v,exitCode:l.exitCode??1}}function er(e,t){let n=W.normalize(e),r=n.split(W.sep).filter(Boolean);if(r.includes(`.aimax`)||r.includes(`.ssh`)||r.includes(`.gnupg`))return!0;let i=W.normalize(t);return n.startsWith(W.join(i,`.aimax`)+W.sep)||n===W.join(i,`.aimax`)}async function tr(e,t,n,r){let i=W.isAbsolute(n.path)?W.normalize(n.path):W.normalize(W.join(n.workspaceDir,n.path));if(!Fn(i,n.allowedRoots))return{error:`snapshot_path_outside_allowed_roots`};if(er(i,e))return{error:`snapshot_sensitive_path_not_allowed`};let a;try{a=await U.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=W.extname(i).toLowerCase(),s=o.length>0&&En.has(o),c;try{c=await U.readFile(i)}catch{return{error:`snapshot_read_failed`}}if(!s){let e=Mn(c.toString(`utf-8`));c=Buffer.from(e.text,`utf-8`)}else if(!En.has(o))return{error:`snapshot_binary_type_not_allowed`};let l=await Bn(e,t,`snapshot`,r),u=l.split(`:`)[1]??zn(`snapshot`),d=An(e,t,r);await U.mkdir(d,{recursive:!0});let f=`${u}${o||W.extname(i)}`,p=`goal/artifacts/snapshots/${f}`,m=W.join(d,f);await U.writeFile(m,c);let h={id:l,kind:`snapshot`,summary:n.summary,path:i,hash:Nn(c),sizeBytes:c.byteLength,snapshotPath:p,createdAt:new Date().toISOString()};try{await Hn(e,t,h,r)}catch{return await U.unlink(m).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:l}}function nr(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function rr(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${nr(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${nr(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${nr(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}: ${nr(n.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${nr(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 or goal_task_start.`,`- Do not claim task completion in prose; use goal_task_done with evidence refs.`,`- Use only evidenceRef values returned by goal_record_note, goal_record_exec, or goal_record_snapshot 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_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===Tt)&&t.unshift(`- Current task is "${Tt}": 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 ar(){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 or=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function sr(e,t,n){return cr(e,t,n,{introLine:or})}function cr(e,t,n,r){let i=nr(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>`,...rr(n),`</workflow>`,``,`Rules:`,...ir(n)):l.push(`Rules:`,...ar()),l.push(``,`</goal_context>`),l.join(`
5
- `)}function lr(e,t){let n=nr(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 ur(e,t){let n=nr(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 dr(e){return{role:`user`,content:e}}function fr(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const pr=`AIMAX_GOAL_CONTINUATION`;var mr=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function hr(e,t,n){let r=await _n(e,t,{storeName:n?.storeName});if(!r)return null;let i=await Kn(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 gr(){let e=process.env[pr];return e===void 0||e===``||e!==`0`}async function _r(e,t,n,r){if(!gr()||n.continuationCount>=qe)return!1;let i=await H(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-Ddm_lIaP.js`).then(e=>e.c),s=await o(e,t,{storeName:r?.storeName});return!(s&&s.status===`pending`||!n.lastTurnHadOutput)}function vr(e){return e.text.trim().length>0?!0:(e.toolResultCount??0)>0}async function yr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await _r(n,r,a,{storeName:i}))return!1;let u=await H(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await z(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await hr(n,r,{storeName:i}),h=dr(p?lr(u,f):cr(u,f,m));a.continuationCount++;let g=await c(h.content);if(a.lastTurnHadOutput=vr(g),p&&(a.budgetWrapUpDone=!0),l&&await l({input:g.inputTokens,output:g.outputTokens,total:g.inputTokens+g.outputTokens}),a.continuationCount>=qe){let e=await H(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-DKeFVjM4.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-DvF1LRBK.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 (${qe}), goal paused`)}}return!0}async function br(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function xr(e,t,n){let r=await _n(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 Gn(e,t,c,{storeName:n?.storeName}),await q(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await Kn(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await Jn(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await Yn(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Sr(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await hr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=dr(sr(i,await z(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Cr(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=dr(ur(i,await z(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function wr(e,t,n){(await H(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await B(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const Tr=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function Er(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===Tt}function Dr(e){return Tr.has(e)}function Or(e){return e===`exec`||e===`process`?[`Tool "${e}" is blocked during the clarify-first-turn workflow.`,`Use goal_record_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_exec, goal_record_note, goal_record_snapshot, or goal_repair_workflow_state to refine, record evidence, or recover before executing deliverables directly.`].join(` `)}function kr(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())&&Dr(n.toolName))return{block:!0,blockReason:Or(n.toolName)}}}),()=>{t=!1}}function Ar(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 jr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(zr(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}Br(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 Mr(e,t={}){let n=Lr(t.limit,`limit`),r=Rr(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!Br(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:Ir(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Nr(e,t){let n=Rr(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 Pr(e,t=80){let n=Rr(e,`totalEntryCount`),r=Rr(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Fr(e,t){return e.slice(t.startIndex,t.endIndex)}function Ir(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Lr(e,t){return e===void 0?1/0:Rr(e,t)}function Rr(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function zr(e){return e.role===`assistant`}function Br(e){return e.role===`tool_result`}const Vr=24e3;async function Hr(e){return Xr({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Ur(e){return Xr({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Wr(e){return Xr({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Gr(e){let t=ii(e),n=await qr(e),r=await ei(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:Jr(e.dataDir,e.sessionId,e.sessionOptions)}}function Kr(e){return{maxEntries:ai(e?.maxEntries??80,`limits.maxEntries`),maxBytes:ai(e?.maxBytes??Vr,`limits.maxBytes`)}}async function qr(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=Zr(await Qr(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 $r({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Jr(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function Yr(e,t,n){let r=oi(e.startIndex,`startIndex`),i=oi(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 Xr(e){let t=ii(e.params),n=Yr(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=ti(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:Jr(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function Zr(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 Qr(e,t,n){let[r,i]=await Promise.all([F(e,t,n),ee(e,t,n)]),a=new Map;for(let e of r)li(e)&&e.toolResultRef?.sessionId===t&&a.set(ui(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(ui(e),e);return Array.from(a.values())}async function $r(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(W.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=W.resolve(e.dataDir,e.reference.storagePath);if(!ci(W.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!ci(W.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([si(t),si(n),si(i)]);if(!ci(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!ci(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function ei(e,t){let n=await U.stat(e),r=await U.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:ri(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function ti(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=ni(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 ni(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:ri(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function ri(e){let t=new at(`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 Kr(e.limits)}function ai(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function oi(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function si(e){try{return await U.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${di(e)}`)}}function ci(e,t){let n=W.relative(e,t);return n===``||!n.startsWith(`..`)&&!W.isAbsolute(n)}function li(e){return e.role===`tool_result`}function ui(e){return`${e.toolCallId}\n${e.storagePath}`}function di(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function fi(e){return W.join(e,`.aimax`,`auto-skills`)}function pi(e){return W.join(e,`categories.json`)}function mi(e){return W.join(e,`.auto_skills_prompt_snapshot.json`)}const hi=/^[a-z0-9][a-z0-9-]*$/,gi=/^[a-z0-9][a-z0-9-]*$/;function _i(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(`\\`)||W.win32.isAbsolute(t)||W.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(!hi.test(t))throw Error(`Invalid auto-skill category path segment: ${t}`)}return n.join(`/`)}function vi(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(`.`)||!gi.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function yi(e,t){return`auto:${_i(e)}/${vi(t)}`}function bi(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=_i(n.slice(0,r)),a=vi(n.slice(r+1));return{skillId:yi(i,a),categoryPath:i,skillName:a}}function xi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Si(e,t,n){let r=W.resolve(e),i=W.resolve(r,..._i(t).split(`/`),vi(n));return wi(r,i),i}function Ci(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||W.win32.isAbsolute(n)||W.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=W.resolve(e),a=W.resolve(i,...r);return wi(i,a),a}function wi(e,t){let n=W.resolve(e),r=W.resolve(t),i=W.relative(n,r);if(i.startsWith(`..`)||W.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Ti(e){let t=pi(e),n;try{n=await U.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=_i(e),r=Di(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 Ei(e){return new Map(e.map(e=>[e.path,e]))}function Di(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 Oi=32*1024,ki=new Map;function Ai(e){return new Mi(e)}async function ji(e){let t=W.resolve(e);for(let e of Array.from(ki.keys()))e.startsWith(`${t}|`)&&ki.delete(e);await U.rm(mi(t),{force:!0}).catch(()=>{})}var Mi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=W.resolve(e.rootDir??fi(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Pi(Ei((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?_i(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Fi(e.categoryPath,t)).map(Ni)}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:Ii(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})=>({...Ni(e),score:t}))}async autoSkillView(e){let t=bi(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=Ci(n.skillDir,e.filePath),r=await Gi(t,this.maxResourceBytes);return{...Ni(n),status:n.status,content:r,path:Ji(W.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Ji(W.relative(n.skillDir,t))}}let r=await Gi(n.skillFile,this.maxSkillBytes);return{...Ni(n),status:n.status,content:r,path:Ji(W.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 Li(this.rootDir),i=ki.get(n);if(!e&&i&&Hi(i.manifest,r))return i;let a=e?void 0:await Bi(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return ki.set(n,e),e}let o=await Ti(this.rootDir),s=Ei(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return ki.set(n,c),await Vi(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 Zi({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:Oi})}async loadEntry(e){try{let t=W.dirname(e),n=vi(W.basename(t)),r=Ji(W.relative(this.rootDir,t)),i=_i(W.posix.dirname(r)),a=yi(i,n),o=W.join(t,`metadata.json`),s=await Ui(o);if(s?.skillId&&bi(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&_i(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=xi(s?.status);return{skillId:a,name:n,description:Ki(await Wi(e,Oi)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:qi(s?.tags),relatedSkills:qi(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}: ${Yi(t)}\n`);return}}};function Ni(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Pi(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Fi(e,t){return t?e===t:!0}function Ii(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 Li(e){let t;try{t=await U.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await zi(W.join(e,`categories.json`),`categories`,n),await Ri(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Ri(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=W.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await zi(t,`skill`,n),await zi(W.join(e,`metadata.json`),`metadata`,n),await zi(W.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await U.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Ri(t,i,n)}}async function zi(e,t,n){try{let r=await U.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 Bi(e,t,n){let r;try{r=await U.readFile(mi(e),`utf-8`)}catch(e){if(e.code===`ENOENT`)return;throw e}try{let e=JSON.parse(r);return e.version!==1||e.optionsHash!==t||!Array.isArray(e.entries)||!Array.isArray(e.categories)||!Array.isArray(e.manifest)||!Hi(e.manifest,n)?void 0:e}catch{return}}async function Vi(e,t){if(!await Xi(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await U.writeFile(mi(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function Hi(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 Ui(e){try{let t=await U.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 Wi(e,t){let n=await U.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 Gi(e,t){if((await U.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return U.readFile(e,`utf-8`)}function Ki(e){let t=ot(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 qi(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Ji(e){return e.split(W.sep).join(`/`)}function Yi(e){return e instanceof Error?e.message:String(e)}async function Xi(e){try{return await U.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function Zi(e){return et(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Qi(e){return e??`openai-completions`}function $i(e,t,n){let r={"Client-Code":`AIMax`,"X-Session-Id":e};return t&&(r[`X-Message-Id`]=t),n&&(r[`X-Channel`]=n),r}function ea(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}const ta={apiFormat:`anthropic-messages`,createModel:na,buildRequest:ia,normalizeResponse:aa};function na(e,t,n,r){return{id:e.model,name:e.model,api:`anthropic-messages`,provider:`anthropic`,baseUrl:ra(e.baseUrl),reasoning:!1,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:$i(t,n,r)}}function ra(e){return e.replace(/\/+$/,``).replace(/\/v1$/,``)}function ia(e,t,n,r){let i=e.baseUrl.replace(/\/+$/,``),a=[],o=[];for(let e of n){if(e.role===`system`){e.content.trim()&&o.push(e.content);continue}a.push({role:e.role,content:e.content})}let s={model:t,messages:a.length>0?a:[{role:`user`,content:``}],max_tokens:r.maxTokens??2048,stream:!1};return o.length>0&&(s.system=o.join(`
9
-
10
- `)),typeof r.temperature==`number`&&(s.temperature=r.temperature),{url:i.endsWith(`/v1`)?`${i}/messages`:`${i}/v1/messages`,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`,"Client-Code":`AIMax`},body:s}}function aa(e){let t=e,n=t.content?.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``)??``,r=(t.usage?.input_tokens??0)+(t.usage?.cache_read_input_tokens??0)+(t.usage?.cache_creation_input_tokens??0),i=t.usage?.output_tokens??0;return{text:n,usage:{input:r,output:i,total:r+i},raw:e}}const oa={apiFormat:`openai-completions`,createModel:sa,buildRequest:ca,normalizeResponse:la};function sa(e,t,n,r){let i=e.baseUrl.includes(`deepseek.com`),a=e.thinking;return{id:e.model,name:e.model,api:`openai-completions`,provider:i?`deepseek`:`openai`,baseUrl:e.baseUrl,reasoning:i||!!a,...i&&{thinkingLevelMap:{high:`high`,xhigh:`max`}},...a&&!i&&{thinkingLevelMap:{high:`high`,xhigh:`high`}},input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:$i(t,n,r),compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!!(a&&!i),supportsUsageInStreaming:!0,...a&&!i&&{thinkingFormat:`deepseek`}}}}function ca(e,t,n,r){let i={model:t,messages:n,stream:!1};return typeof r.temperature==`number`&&(i.temperature=r.temperature),typeof r.maxTokens==`number`&&(i.max_tokens=r.maxTokens),{url:`${e.baseUrl.replace(/\/+$/,``)}/chat/completions`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:i}}function la(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:ea(t.usage),raw:e}}const ua={"openai-completions":oa,"anthropic-messages":ta};function da(e){return ua[e]}function fa(e,t,n,r){return da(Qi(e.apiFormat)).createModel(e,t,n,r)}const pa=`/aimax/agents`,ma=/^[a-z]+(?:-[a-z]+)*$/;function ha(e){let t=[{dir:e.systemAgentsDir??pa,source:`system`},{dir:W.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:W.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function ga(e){let t=new Map;for(let n of ha(e)){let e=await ba(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function _a(e={}){let t=e.allAgents??e.availableAgents??[],n=wa(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Sa(n,e),findAny:e=>Sa(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function va(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 ya(e){return va(e.agentPolicy)?e.agentPolicy:_a({allAgents:await ga(e)})}async function ba(e,t){let n;try{n=await U.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=W.join(e,i.name),a=xa(await U.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function xa(e,t){let n=ot(e),r=ka(n.data.name)?.trim(),i=ka(n.data.description)?.trim();if(!r||!ma.test(r)||!i)return;let a=ka(n.data.model)?.trim(),o=ka(n.data.initPrompt)?.trim()??ka(n.data.initialPrompt)?.trim(),s=Aa(n.data.maxTurns),c=ja(n.data.tools),l=ja(n.data.disallowedTools),u=ja(n.data.skills),d=Ma(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 Sa(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Ca(e)===`public`))}function Ca(e){return e.visibility??`public`}function wa(e){return e.filter(e=>Ca(e)===`public`)}function Ta(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function Ea(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Na)):void 0,r=new Set((t.disallowedTools??[]).map(Na));return e.filter(e=>{let t=typeof e.name==`string`?Na(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Da(e){let t=wa(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(`
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-DIkujhuw.js";import{n as R,t as te}from"./goal-events-vnNkQVzi.js";import{c as z,i as B,l as V,n as ne,o as re,r as ie,s as H,t as ae,u as U}from"./goal-store-Clnnb4f2.js";import{a as oe,c as se,d as ce,f as le,g as ue,h as de,i as fe,l as pe,m as me,o as he,p as ge,r as _e,s as ve,t as ye,u as be}from"./default-provider-QJ5I3qOU.js";import{i as xe,t as Se}from"./host-CFCi5RZa.js";import{a as Ce,i as we,l as Te,n as Ee,o as De,r as Oe,s as ke,t as Ae}from"./session-store-D8wJoo7a.js";import{_ as je,a as Me,c as Ne,d as Pe,f as Fe,g as Ie,h as Le,i as Re,l as ze,m as Be,n as Ve,o as He,p as Ue,s as We,t as Ge,u as Ke,v as qe,y as Je}from"./config-DYv0xUdi.js";import{MAX_GOAL_CONTINUATIONS_PER_RUN as Ye,formatTaskForDisplay as Xe,isHitlExpired as Ze,isHitlTool as Qe,validateUiToolResult as $e}from"@gencode/shared";import W,{readFile as et}from"node:fs/promises";import G,{join as tt}from"node:path";import{createHash as nt,randomBytes as rt,randomUUID as it}from"node:crypto";import at from"node:os";import{spawn as ot}from"node:child_process";import{TextDecoder as st}from"node:util";import ct from"gray-matter";import{Agent as lt}from"@earendil-works/pi-agent-core";import{AsyncLocalStorage as ut}from"node:async_hooks";import K from"node:fs";import dt from"log4js";import ft from"openai";import{Type as q,calculateCost as pt,clampThinkingLevel as mt,createAssistantMessageEventStream as ht,getEnvApiKey as gt,parseStreamingJson as _t,registerApiProvider as vt,registerBuiltInApiProviders as yt,streamSimple as bt}from"@earendil-works/pi-ai";import{fileURLToPath as xt}from"node:url";import{isBinaryFile as St}from"isbinaryfile";import Ct from"ajv";import{createJiti as wt}from"jiti";var Tt=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 Et(e,t,n,r,i){let a=await H(e,t,{storeName:i?.storeName});if(!a)return{goal:null,budgetLimited:!1};let o=n.turn?.activeGoalId??n.wallClock.activeGoalId;if(o&&o!==a.goalId)return{goal:a,budgetLimited:!1};let s=n.tokenDeltaSinceLastAccounting(r),c=n.timeDeltaSecondsSinceLastAccounting();if(s<=0&&c<=0)return{goal:a,budgetLimited:!1};let l=a.tokensUsed+s,u=a.timeUsedSeconds+c,d=a.status,f=!1;a.tokenBudget!==null&&l>=a.tokenBudget&&a.status===`active`&&(d=`budget_limited`,f=!0);let p=await V(e,t,{tokensUsed:l,timeUsedSeconds:u,status:d},{storeName:i?.storeName,eventSource:i?.eventSource});return n.markAccounted(r,c),{goal:p,budgetLimited:f}}const Dt=`clarify plan and acceptance`,Ot=`补齐后续 task list、每个 task 的验收项和当前下一步`,kt={goal:[`目标`,`goal`,`objective`],scope:[`范围`,`scope`,`约束`,`constraints`],steps:[`步骤`,`阶段`,`steps`,`phases`],acceptance:[`完成标准`,`验收`,`验证`,`输出`,`acceptance`,`verification`,`output`,`deliverables`]},At=[`test`,`verify`,`validation`,`pass`,`run `,`npm `,`pnpm `,`pytest`,`通过`,`验证`,`测试`,`输出`,`证明`,`截图`,`日志`,`覆盖`,`回归`];function jt(e){return e.trim().toLowerCase().replace(/[【】\[\]]/g,``)}function Mt(e,t){let n=jt(e);return t.some(e=>n===e.toLowerCase()||n.includes(e.toLowerCase()))}function Nt(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 Pt(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(kt))Mt(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?Nt(t.steps):[],acceptance:t.acceptance?Nt(t.acceptance):[],raw:e.trim()}}function Ft(e){let t=e.toLowerCase();return At.some(e=>t.includes(e.toLowerCase()))}function It(e){return e.some(Ft)}function Lt(e,t){return{id:e,text:t,required:!0}}function Rt(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 zt(e){return Rt({id:`task-1`,kind:`clarify`,title:Dt,status:`doing`,acceptanceCriteria:[Lt(`ac-1`,Ot)],updatedAt:e})}function Bt(e,t,n){let r=e.slice(0,5),i=t.length>0?t.map((e,t)=>Lt(`ac-${t+1}`,e)):[Lt(`ac-1`,`完成:${r[0]}`)];return r.map((e,t)=>Rt({id:`task-${t+1}`,kind:`execution`,title:e,status:t===0?`doing`:`todo`,acceptanceCriteria:t===0?i:[Lt(`ac-1`,`完成:${e}`)],updatedAt:n}))}function Vt(e){let t=new Date().toISOString(),n=Pt(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:Bt(n.steps,n.acceptance,t)};let o=n.acceptance;if(o.length>0&&It(o))return{interpretation:r,assumptions:i,openQuestions:a,tasks:Bt([n.steps[0]??n.goal],o,t)};if(n.raw.length>=40&&It(Nt(n.raw))){let e=Nt(n.raw).filter(Ft);return{interpretation:r,assumptions:i,openQuestions:a,tasks:Bt([n.goal],e,t)}}return{interpretation:r,assumptions:i,openQuestions:a,tasks:[zt(t)]}}function Ht(e,t){return`- [${e?`x`:` `}] ${t.id}: ${t.text}`}function Ut(e,t){let n=t??new Set(e.acceptanceEvidence);return[`### ${e.id}: ${e.title}`,``,`Status: ${e.status}`,``,`Acceptance Criteria:`,...e.acceptanceCriteria.map(e=>Ht(n.has(e.id),e)),``].join(`
2
+ `)}function Wt(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[Ut(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
+ `)}const Gt=process.platform===`win32`;function Kt(e){return Gt?{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 qt(e,t){if(!(e.exitCode!==null||e.signalCode!==null)){if(Gt&&typeof e.pid==`number`){let n=[`/pid`,String(e.pid),`/T`];t===`SIGKILL`&&n.push(`/F`);try{ot(`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 Jt=2e5;function Yt(e,t=4e3){return e?e.length>t?e.slice(-t):e:``}function Xt(e,t){let n=e+t;return n.length<=Jt?{text:n,truncated:!1}:{text:n.slice(-Jt),truncated:!0}}function Zt(e,t,n){if(n.length===0)return;let r=n.toString(`utf-8`),i=Xt(e.output,r);e.output=i.text;let a=Xt(e[t],r);e[t]=a.text,(i.truncated||a.truncated)&&(e.outputTruncated=!0)}function Qt(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:Yt(e.output),stdoutTail:Yt(e.stdout),stderrTail:Yt(e.stderr),outputTruncated:e.outputTruncated}}function $t(e,t){return t?e.scopeKey===t:!0}function en(e,t){return typeof e!=`number`||!Number.isFinite(e)||e<=0?t:Math.floor(e)}function tn(e){return e?e.split(/\r?\n/):[]}function nn(e){let t=tn(e.record.output),n=e.offset===void 0&&e.limit===void 0,r=Math.max(0,(e.offset??0)|0),i=en(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 rn(e){e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.killTimer&&=(clearTimeout(e.killTimer),void 0),e.resolveDone()}function an(){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),rn(e))};return{start(t){let{file:n,args:r,shell:a}=Kt(t.command),o=ot(n,r,{cwd:t.cwd,env:{...process.env,...t.baseEnv??{},...t.env??{}},stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0,shell:a,detached:!Gt}),s=()=>{},c=new Promise(e=>{s=e}),l={sessionId:it(),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=>Zt(l,`stdout`,e)),o.stderr.on(`data`,e=>Zt(l,`stderr`,e));let u=e=>t=>{Zt(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=en(t.timeoutSec,1800);return l.timeoutTimer=setTimeout(()=>{l.status===`running`&&(l.status=`timeout`,Zt(l,`stderr`,Buffer.from(`\n[Timed out after ${d}s]\n`)),qt(l.child,`SIGTERM`),l.killTimer=setTimeout(()=>{(l.status===`running`||l.status===`timeout`)&&qt(l.child,`SIGKILL`)},1e3))},d*1e3),o.on(`error`,e=>{i(l,()=>{l.status===`running`&&(l.status=`failed`),Zt(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`)})}),Qt(l)},get(e,t){let n=r(e);return!n||!$t(n,t)?null:Qt(n)},list(n){return[...e.values(),...t.values()].filter(e=>$t(e,n)).sort((e,t)=>t.startedAt-e.startedAt).map(e=>Qt(e))},async wait(e,t,n){let i=r(e);if(!i||!$t(i,t))return null;if(i.status!==`running`)return Qt(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||!$t(a,t)?null:Qt(a)},readLog(e){let t=r(e.sessionId);return!t||!$t(t,e.scopeKey)?null:nn({record:t,offset:e.offset,limit:e.limit})},readOutput(e,t){let n=r(e);return!n||!$t(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||!$t(n,t))return null;if(n.status!==`running`)return Qt(n);n.status=`killed`,qt(n.child,`SIGTERM`),n.killTimer=setTimeout(()=>{(n.status===`running`||n.status===`killed`)&&qt(n.child,`SIGKILL`)},1e3),await Promise.race([n.donePromise,new Promise(e=>{setTimeout(e,1500)})]);let i=r(e);return i?Qt(i):null},disposeAll(){for(let t of e.values()){if(t.status!==`running`)continue;t.status=`killed`,qt(t.child,`SIGTERM`);let e=setTimeout(()=>{(t.status===`running`||t.status===`killed`)&&qt(t.child,`SIGKILL`)},1e3);typeof e.unref==`function`&&e.unref(),t.killTimer=e}}}}const on=1;var sn=class extends Error{constructor(e){super(`unsupported_goal_state_version:${e}`),this.name=`UnsupportedGoalStateVersionError`}},cn=class extends Error{constructor(e){super(e),this.name=`CorruptEvidenceRegistryError`}},ln=class extends Error{rawContentPreview;constructor(e,t){super(e),this.name=`CorruptGoalWorkflowStateError`,t?.cause!==void 0&&(this.cause=t.cause),this.rawContentPreview=t?.rawContentPreview}};const un=new Map;function dn(e,t,n){return`${e}\x00${t}\x00${n?.storeName??``}`}async function fn(e,t,n,r){let i=dn(e,t,n),a=un.get(i)??Promise.resolve(),o,s=new Promise(e=>{o=e});un.set(i,a.then(()=>s)),await a;try{return await r()}finally{o()}}function pn(e,t,n){return G.join(ne(e,t,n),`state.json`)}function mn(e,t,n){return G.join(ne(e,t,n),`plan.md`)}function hn(e,t,n){return G.join(ne(e,t,n),`artifacts`)}async function gn(e,t){let n=`${e}.${process.pid}.${Date.now()}.${rt(4).toString(`hex`)}.tmp`;try{await W.writeFile(n,t,`utf-8`),await W.rename(n,e)}finally{await W.unlink(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}}function _n(e){if(e.version!==1)throw new sn(e.version)}function vn(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 yn(e,t,n){let r=pn(e,t,n);try{let e=await W.readFile(r,`utf-8`);try{let t=JSON.parse(e);return _n(t),t}catch(t){throw t instanceof sn?t:new ln(`corrupt_goal_workflow_state`,{cause:t,rawContentPreview:e.slice(0,200)})}}catch(e){if(e.code===`ENOENT`)return null;throw e instanceof ln||e instanceof sn?e:new ln(`corrupt_goal_workflow_state`,{cause:e})}}async function bn(e,t,n){let r=pn(e,t,n),i;try{i=await W.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{ok:!0,healthy:!0,mode:`absent`};throw e}try{return _n(JSON.parse(i)),{ok:!0,healthy:!0,mode:`healthy`}}catch(e){if(e instanceof sn)throw e}let a=await H(e,t,n);if(!a)throw Error(`repairGoalWorkflowState requires an existing goal record`);let o=(await z(e,t,a,n)).trim();if(!o)throw Error(`repairGoalWorkflowState requires a non-empty objective`);let s=`${r}.corrupt.${new Date().toISOString().replace(/[:.]/g,`-`)}.bak`,c=null;try{await W.writeFile(s,i,`utf-8`),c=s}catch{}return await wn(e,t,{goalId:a.goalId,objective:o},n),await Qn(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 yn(e,t,n);return r?vn(r):null}async function Sn(e,t,n){let r=await yn(e,t,n);return r?{goalState:vn(r),workflowWarning:null}:{goalState:null,workflowWarning:`workflow_not_initialized`}}async function Cn(e,t,n){let r=pn(e,t,n),i=mn(e,t,n),a=hn(e,t,n);await Promise.all([W.unlink(r).catch(e=>{if(e.code!==`ENOENT`)throw e}),W.unlink(i).catch(e=>{if(e.code!==`ENOENT`)throw e}),W.rm(a,{recursive:!0,force:!0})])}async function wn(e,t,n,r){let i=n.objective.trim();if(!i)throw Error(`initializeGoalWorkflow requires a non-empty objective`);await Cn(e,t,r);let a=Vt(i),o=new Date().toISOString(),s=a.tasks.find(e=>e.status===`doing`)?.id??a.tasks[0]?.id??null,c={version:1,goalId:n.goalId,status:`active`,objective:i,currentTaskId:s,tasks:a.tasks,blockedReason:null,finalEvidenceRefs:[],completedAt:null,updatedAt:o},l=ne(e,t,r);await W.mkdir(l,{recursive:!0}),await gn(pn(e,t,r),JSON.stringify(c,null,2));let u=Wt(c,{interpretation:a.interpretation,assumptions:a.assumptions,openQuestions:a.openQuestions});return await gn(mn(e,t,r),u),c}const Tn=1048576,En=/KEY|TOKEN|SECRET|PASSWORD|COOKIE|AUTH/i,Dn=[/(?:api[_-]?key|token|secret|password|authorization)\s*[:=]\s*\S+/gi,/Bearer\s+[A-Za-z0-9._~+/=-]+/gi,/sk-[A-Za-z0-9]{16,}/g],On=new Set([`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.pdf`]);function kn(e,t,n){return G.join(hn(e,t,n),`registry.jsonl`)}function An(e,t,n){return G.join(hn(e,t,n),`notes`)}function jn(e,t,n){return G.join(hn(e,t,n),`commands`)}function Mn(e,t,n){return G.join(hn(e,t,n),`snapshots`)}function Nn(e,t,n){return G.join(ne(e,t,n),`plan-meta.json`)}function Pn(e){let t=e,n=!1;for(let e of Dn)t=t.replace(e,e=>e.length<=8?(n=!0,`[REDACTED]`):`${e.slice(0,4)}[REDACTED]`);return{text:t,redactionIncomplete:n}}function Fn(e){return`sha256:${nt(`sha256`).update(e).digest(`hex`)}`}async function In(e){return Fn(await W.readFile(e))}function Ln(e,t){let n=G.normalize(e);return t.some(e=>{let t=G.normalize(e);return n===t||n.startsWith(t+G.sep)})}function Rn(e){let t=[G.normalize(e.workspaceDir),G.normalize(at.tmpdir())],n=e.projectDir?.trim();n&&t.push(G.normalize(n));let r=G.join(e.dataDir,`workspace`);return t.includes(G.normalize(r))||t.push(G.normalize(r)),t}function zn(e,t){return t?.trim()?G.isAbsolute(t)?G.normalize(t):G.normalize(G.join(e,t)):e}function Bn(e,t){return e.byteLength<=t?{data:e,truncated:!1,originalBytes:e.byteLength}:{data:e.subarray(0,t),truncated:!0,originalBytes:e.byteLength}}function Vn(e){return`${e}-${Date.now().toString(36)}-${rt(3).toString(`hex`)}`}async function Hn(e,t,n,r){let i=await Un(e,t,r),a=new Set(i.map(e=>e.id));for(let e=0;e<8;e+=1){let e=`${n}:${Vn(n)}`;if(!a.has(e))return e}throw Error(`failed_to_generate_unique_evidence_id`)}async function Un(e,t,n){let r=kn(e,t,n);try{let e=await W.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 cn(`corrupt evidence registry line ${r.index+1}`)}return t}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Wn(e,t,n,r){let i=kn(e,t,r);await W.mkdir(G.dirname(i),{recursive:!0}),await W.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Gn(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 Un(e,t,r),o=new Map(a.map(e=>[e.id,e])),s=[],c=Kn(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?G.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 W.readFile(n);if(t.hash&&Fn(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?G.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 W.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 In(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?G.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 W.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 Kn(e,t,n){return G.dirname(ne(e,t,n))}async function qn(e,t,n,r){_n(n),await gn(pn(e,t,r),JSON.stringify(n,null,2))}async function Jn(e,t,n){let r=Nn(e,t,n);try{let e=await W.readFile(r,`utf-8`);return JSON.parse(e)}catch(e){if(e.code===`ENOENT`)return{};throw e}}async function Yn(e,t,n,r){await gn(Nn(e,t,r),JSON.stringify(n,null,2))}async function Xn(e,t,n,r){let i=await Jn(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 Yn(e,t,a,r),a}async function Zn(e,t,n,r){try{let i=Wt(n,await Jn(e,t,r));return await gn(mn(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 Qn(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 W.mkdir(G.dirname(s),{recursive:!0}),await W.appendFile(s,`${JSON.stringify(o)}\n`,`utf-8`)}function $n(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 er(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 tr(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 Hn(e,t,n.kind,r),a=i.split(`:`)[1]??Vn(n.kind),o=An(e,t,r);await W.mkdir(o,{recursive:!0});let s=`goal/artifacts/notes/${a}.md`,c=G.join(An(e,t,r),`${a}.md`),l=Pn(n.content);await W.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 Wn(e,t,u,r)}catch{return await W.unlink(c).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:i}}async function nr(e,t,n,r){let i=zn(n.workspaceDir,n.cwd);if(!Ln(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=an(),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=Bn(d,Tn),m=Bn(f,Tn),h=Pn(p.data.toString(`utf-8`)),g=Pn(m.data.toString(`utf-8`)),_=h.redactionIncomplete||g.redactionIncomplete,v=await Hn(e,t,`command`,r),y=v.split(`:`)[1]??Vn(`command`),b=jn(e,t,r);await W.mkdir(b,{recursive:!0});let x=`goal/artifacts/commands/${y}.out.txt`,S=`goal/artifacts/commands/${y}.err.txt`,C=G.join(b,`${y}.out.txt`),w=G.join(b,`${y}.err.txt`);await W.writeFile(C,h.text,`utf-8`),await W.writeFile(w,g.text,`utf-8`);let T=Object.keys({...process.env,...n.baseEnv}).filter(e=>En.test(e)),E={id:v,kind:`command`,command:Pn(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:Fn(h.text),createdAt:new Date().toISOString()};try{await Wn(e,t,E,r)}catch{return await Promise.all([W.unlink(C).catch(()=>{}),W.unlink(w).catch(()=>{})]),{error:`registry_write_failed`}}return{evidenceRef:v,exitCode:l.exitCode??1}}function rr(e,t){let n=G.normalize(e),r=n.split(G.sep).filter(Boolean);if(r.includes(`.aimax`)||r.includes(`.ssh`)||r.includes(`.gnupg`))return!0;let i=G.normalize(t);return n.startsWith(G.join(i,`.aimax`)+G.sep)||n===G.join(i,`.aimax`)}async function ir(e,t,n,r){let i=G.isAbsolute(n.path)?G.normalize(n.path):G.normalize(G.join(n.workspaceDir,n.path));if(!Ln(i,n.allowedRoots))return{error:`snapshot_path_outside_allowed_roots`};if(rr(i,e))return{error:`snapshot_sensitive_path_not_allowed`};let a;try{a=await W.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=G.extname(i).toLowerCase(),s=o.length>0&&On.has(o),c;try{c=await W.readFile(i)}catch{return{error:`snapshot_read_failed`}}if(!s){let e=Pn(c.toString(`utf-8`));c=Buffer.from(e.text,`utf-8`)}else if(!On.has(o))return{error:`snapshot_binary_type_not_allowed`};let l=await Hn(e,t,`snapshot`,r),u=l.split(`:`)[1]??Vn(`snapshot`),d=Mn(e,t,r);await W.mkdir(d,{recursive:!0});let f=`${u}${o||G.extname(i)}`,p=`goal/artifacts/snapshots/${f}`,m=G.join(d,f);await W.writeFile(m,c);let h={id:l,kind:`snapshot`,summary:n.summary,path:i,hash:Fn(c),sizeBytes:c.byteLength,snapshotPath:p,createdAt:new Date().toISOString()};try{await Wn(e,t,h,r)}catch{return await W.unlink(m).catch(()=>{}),{error:`registry_write_failed`}}return{evidenceRef:l}}function ar(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function or(e){let t=[`Workflow status: ${e.workflowStatus}`];if(e.currentTaskId&&(t.push(`Current task: ${e.currentTaskId} — ${ar(e.currentTaskTitle??`untitled`)}`,`Current task status: ${e.currentTaskStatus??`unknown`}`),e.currentTaskKind&&t.push(`Current task kind: ${e.currentTaskKind}`)),e.blockedReason&&t.push(`Workflow blocked: ${ar(e.blockedReason)}`),e.taskBlockedReason&&e.taskBlockedReason!==e.blockedReason&&t.push(`Task blocked: ${ar(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}: ${ar(n.text)}`)}}if(e.openQuestions.length>0){t.push(``,`Open questions:`);for(let n of e.openQuestions)t.push(`- ${ar(n)}`)}return t}function sr(e){let t=[`- Treat goal/state.json as the only task workflow machine state; use goal/plan.md for human-readable context.`,`- Work on the current task 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===Dt)&&t.unshift(`- Current task is "${Dt}": 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 cr(){return[`- Keep the full objective intact; do not redefine it as a smaller task.`,`- Use the current worktree, files, command output, and test results as authoritative evidence of progress.`,`- Do not rely solely on conversation memory to assess completion.`,`- Perform a completion audit: check each requirement in the objective against actual state.`,`- 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 lr=`The user just set a thread goal. Acknowledge it implicitly, then work on the current workflow task below.`;function ur(e,t,n){return dr(e,t,n,{introLine:lr})}function dr(e,t,n,r){let i=ar(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>`,...or(n),`</workflow>`,``,`Rules:`,...sr(n)):l.push(`Rules:`,...cr()),l.push(``,`</goal_context>`),l.join(`
5
+ `)}function fr(e,t){let n=ar(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 pr(e,t){let n=ar(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 mr(e){return{role:`user`,content:e}}function hr(e){return e.startsWith(`<goal_context>`)&&e.endsWith(`</goal_context>`)}const gr=`AIMAX_GOAL_CONTINUATION`;var _r=class{continuationCount=0;lastTurnHadOutput=!0;budgetWrapUpDone=!1;reset(){this.continuationCount=0,this.lastTurnHadOutput=!0,this.budgetWrapUpDone=!1}};async function vr(e,t,n){let r=await yn(e,t,{storeName:n?.storeName});if(!r)return null;let i=await Jn(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 yr(){let e=process.env[gr];return e===void 0||e===``||e!==`0`}async function br(e,t,n,r){if(!yr()||n.continuationCount>=Ye)return!1;let i=await H(e,t,{storeName:r?.storeName});if(!i)return!1;let a=i.status===`budget_limited`&&!n.budgetWrapUpDone;if(i.status!==`active`&&!a)return!1;let{readPendingHitl:o}=await import(`./session-store-D8wJoo7a.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 Sr(e){let{agent:t,dataDir:n,sessionId:r,sessionStoreName:i,state:a,accounting:o,abortSignal:s,executeTurn:c,flushAccountingAfterTurn:l}=e;if(!await br(n,r,a,{storeName:i}))return!1;let u=await H(n,r,{storeName:i});if(!u)return!1;let d=u.status===`budget_limited`&&!a.budgetWrapUpDone;if(u.status!==`active`&&!d)return!1;let f=await z(n,r,u,{storeName:i}),p=u.status===`budget_limited`||u.tokenBudget!==null&&u.tokensUsed>=u.tokenBudget,m=await vr(n,r,{storeName:i}),h=mr(p?fr(u,f):dr(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>=Ye){let e=await H(n,r,{storeName:i});if(e?.status===`active`){let{updateGoal:t}=await import(`./goal-store-Clnnb4f2.js`).then(e=>e.a),{appendGoalEvent:o}=await import(`./goal-events-vnNkQVzi.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 (${Ye}), goal paused`)}}return!0}async function Cr(e,t,n){t&&await e(t);for(let t of n)await e(t)}async function wr(e,t,n){let r=await yn(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 qn(e,t,c,{storeName:n?.storeName}),await Qn(e,t,{type:`goal_blocked_recovered`,goalId:r.goalId,taskId:i,reason:a},{storeName:n?.storeName});let l=await Jn(e,t,{storeName:n?.storeName}),u=`${o.slice(0,16).replace(`T`,` `)}: 用户补充后解除阻塞${a?` — ${a}`:``}`;return await Xn(e,t,{progressLog:[...l.progressLog??[],u]},{storeName:n?.storeName}),await Zn(e,t,c,{storeName:n?.storeName}),{recovered:!0,taskId:i??void 0,reason:a??void 0}}async function Tr(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let a=await vr(e,t,{storeName:r?.storeName});if(!a)return{prompt:n,hadFirstGoalWorkflowSteering:!1};let o=mr(ur(i,await z(e,t,i,{storeName:r?.storeName}),a)).content;return typeof n==`string`?{prompt:`${o}\n\n${n}`,hadFirstGoalWorkflowSteering:!0}:{prompt:[{role:`user`,content:o,timestamp:Date.now()},...n],hadFirstGoalWorkflowSteering:!0}}async function Er(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i?.pendingObjectiveUpdatedNotice)return{prompt:n,hadObjectiveUpdatedSteering:!1};let a=mr(pr(i,await z(e,t,i,{storeName:r?.storeName}))).content;return typeof n==`string`?{prompt:`${a}\n\n${n}`,hadObjectiveUpdatedSteering:!0}:{prompt:[{role:`user`,content:a,timestamp:Date.now()},...n],hadObjectiveUpdatedSteering:!0}}async function Dr(e,t,n){(await H(e,t,{storeName:n?.storeName}))?.pendingObjectiveUpdatedNotice&&await V(e,t,{pendingObjectiveUpdatedNotice:!1},{storeName:n?.storeName,eventSource:`runner`})}const Or=new Set([`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_update`,`memory_forget`,`subagent_spawn`,`batch_subagent_spawn`]);function kr(e){return e.currentTaskKind===`clarify`||e.currentTaskTitle===Dt}function Ar(e){return Or.has(e)}function jr(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 Mr(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())&&Ar(n.toolName))return{block:!0,blockReason:jr(n.toolName)}}}),()=>{t=!1}}function Nr(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 Pr(e){let t=new Set,n=0,r=0,i=0;for(let a of e){if(Hr(a)){for(let e of a.toolCalls??[])n+=1,t.add(e.name);continue}Ur(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 Fr(e,t={}){let n=Br(t.limit,`limit`),r=Vr(t.maxPreviewChars??400,`maxPreviewChars`),i=[];if(n===0)return i;for(let a of e){if(!Ur(a)||!a.isError)continue;let e={toolCallId:a.toolCallId,toolName:a.toolName,preview:zr(a.content,r)};if(t.includeContent&&(e.content=a.content),i.push(e),i.length>=n)break}return i}function Ir(e,t){let n=Vr(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 Lr(e,t=80){let n=Vr(e,`totalEntryCount`),r=Vr(t,`limit`);return{startIndex:Math.max(0,n-r),endIndex:n}}function Rr(e,t){return e.slice(t.startIndex,t.endIndex)}function zr(e,t){let n=e.trim();return t===0?``:n.length<=t?n:t===1?`…`:`${n.slice(0,t-1)}\u2026`}function Br(e,t){return e===void 0?1/0:Vr(e,t)}function Vr(e,t){if(!Number.isFinite(e))throw Error(`${t} must be a finite non-negative integer.`);return Math.max(0,Math.floor(e))}function Hr(e){return e.role===`assistant`}function Ur(e){return e.role===`tool_result`}const Wr=24e3;async function Gr(e){return $r({params:e,kind:`current_run`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Kr(e){return $r({params:e,kind:`recent_conversation`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function qr(e){return $r({params:e,kind:`transcript_range`,transcript:await F(e.dataDir,e.sessionId,e.sessionOptions),range:e.range})}async function Jr(e){let t=si(e),n=await Xr(e),r=await ri(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:Zr(e.dataDir,e.sessionId,e.sessionOptions)}}function Yr(e){return{maxEntries:ci(e?.maxEntries??80,`limits.maxEntries`),maxBytes:ci(e?.maxBytes??Wr,`limits.maxBytes`)}}async function Xr(e){if(!e.toolCallId&&!e.storagePath)throw Error(`tool_result requires toolCallId or storagePath.`);let t=ei(await ti(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 ni({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:e.sessionOptions,reference:t})}}function Zr(e,t,n){return{transcriptPath:c(e,t,n),contextSnapshotPath:_(e,t,n),toolResultsDir:s(e,t,n)}}function Qr(e,t,n){let r=li(e.startIndex,`startIndex`),i=li(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 $r(e){let t=si(e.params),n=Qr(e.range,e.transcript.length,t.maxEntries),r=e.transcript.slice(n.startIndex,n.endIndex),i=ii(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:Zr(e.params.dataDir,e.params.sessionId,e.params.sessionOptions)}}function ei(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 ti(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)fi(e)&&e.toolResultRef?.sessionId===t&&a.set(pi(e.toolResultRef),e.toolResultRef);for(let e of i.toolResults)e.sessionId===t&&a.set(pi(e),e);return Array.from(a.values())}async function ni(e){if(e.reference.sessionId!==e.sessionId)throw Error(`Requested tool result belongs to a different session.`);if(G.isAbsolute(e.reference.storagePath))throw Error(`Referenced tool result storagePath must be relative.`);let t=s(e.dataDir,e.sessionId,e.sessionOptions),n=r(e.dataDir,e.sessionId,e.sessionOptions),i=G.resolve(e.dataDir,e.reference.storagePath);if(!di(G.resolve(t),i))throw Error(`Referenced tool result is outside the session tool-results directory.`);if(!di(G.resolve(n),i))throw Error(`Referenced tool result is outside the session directory.`);let[a,o,c]=await Promise.all([ui(t),ui(n),ui(i)]);if(!di(a,c))throw Error(`Referenced tool result resolves outside the session tool-results directory.`);if(!di(o,c))throw Error(`Referenced tool result resolves outside the session directory.`);return c}async function ri(e,t){let n=await W.stat(e),r=await W.open(e,`r`);try{let e=Buffer.alloc(t+1),{bytesRead:i}=await r.read(e,0,t+1,0),a=Math.min(i,t);return{content:oi(e.subarray(0,a)),originalBytes:n.size,truncated:n.size>t||i>t}}finally{await r.close()}}function ii(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=ai(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 ai(e,t){return Buffer.byteLength(e,`utf-8`)<=t?{value:e,truncated:!1}:{value:oi(Buffer.from(e,`utf-8`).subarray(0,Math.max(0,t))),truncated:!0}}function oi(e){let t=new st(`utf-8`,{fatal:!0}),n=e.length;for(;n>0;)try{return t.decode(e.subarray(0,n))}catch{--n}return``}function si(e){return Yr(e.limits)}function ci(e,t){if(!Number.isFinite(e)||e<=0)throw Error(`${t} must be a positive finite integer.`);return Math.floor(e)}function li(e,t){if(!Number.isFinite(e)||Math.floor(e)!==e)throw Error(`${t} must be a finite integer.`);return e}async function ui(e){try{return await W.realpath(e)}catch(e){throw Error(`Unable to resolve controlled evidence path: ${mi(e)}`)}}function di(e,t){let n=G.relative(e,t);return n===``||!n.startsWith(`..`)&&!G.isAbsolute(n)}function fi(e){return e.role===`tool_result`}function pi(e){return`${e.toolCallId}\n${e.storagePath}`}function mi(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function hi(e){return G.join(e,`.aimax`,`auto-skills`)}function gi(e){return G.join(e,`categories.json`)}function _i(e){return G.join(e,`.auto_skills_prompt_snapshot.json`)}const vi=/^[a-z0-9][a-z0-9-]*$/,yi=/^[a-z0-9][a-z0-9-]*$/;function bi(e){let t=e.trim();if(!t)throw Error(`Auto-skill category path cannot be empty.`);if(t.length>180)throw Error(`Auto-skill category path is too long.`);if(t.includes(`\\`)||G.win32.isAbsolute(t)||G.posix.isAbsolute(t))throw Error(`Invalid auto-skill category path: ${e}`);let n=t.split(`/`);if(n.length!==1)throw Error(`Auto-skill category path must be a single slug.`);for(let t of n){if(!t||t===`.`||t===`..`||t.startsWith(`.`))throw Error(`Invalid auto-skill category path: ${e}`);if(!vi.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(`.`)||!yi.test(t))throw Error(`Invalid auto-skill name: ${e}`);return t}function Si(e,t){return`auto:${bi(e)}/${xi(t)}`}function Ci(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=bi(n.slice(0,r)),a=xi(n.slice(r+1));return{skillId:Si(i,a),categoryPath:i,skillName:a}}function wi(e){if(e==null||e===``)return`active`;if(e===`active`||e===`archived`)return e;throw Error(`Invalid auto-skill status: ${String(e)}`)}function Ti(e,t,n){let r=G.resolve(e),i=G.resolve(r,...bi(t).split(`/`),xi(n));return Di(r,i),i}function Ei(e,t){let n=t.trim();if(!n)throw Error(`Auto-skill resource path cannot be empty.`);if(n.includes(`\\`)||G.win32.isAbsolute(n)||G.posix.isAbsolute(n))throw Error(`Invalid auto-skill resource path: ${t}`);let r=n.split(`/`);for(let e of r)if(!e||e===`.`||e===`..`||e.startsWith(`.`))throw Error(`Invalid auto-skill resource path: ${t}`);let i=G.resolve(e),a=G.resolve(i,...r);return Di(i,a),a}function Di(e,t){let n=G.resolve(e),r=G.resolve(t),i=G.relative(n,r);if(i.startsWith(`..`)||G.isAbsolute(i))throw Error(`Path escapes auto-skill root: ${t}`)}async function Oi(e){let t=gi(e),n;try{n=await W.readFile(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return[];throw e}let r=JSON.parse(n);if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Auto-skill categories.json must be a JSON object.`);return Object.entries(r).map(([e,t])=>{let n=bi(e),r=Ai(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 ki(e){return new Map(e.map(e=>[e.path,e]))}function Ai(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 ji=32*1024,Mi=new Map;function Ni(e){return new Fi(e)}async function Pi(e){let t=G.resolve(e);for(let e of Array.from(Mi.keys()))e.startsWith(`${t}|`)&&Mi.delete(e);await W.rm(_i(t),{force:!0}).catch(()=>{})}var Fi=class{rootDir;includeArchived;maxSkillBytes;maxResourceBytes;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillsLoader requires either rootDir or dataDir.`);this.rootDir=G.resolve(e.rootDir??hi(e.dataDir)),this.includeArchived=e.includeArchived??!1,this.maxSkillBytes=e.maxSkillBytes??98304,this.maxResourceBytes=e.maxResourceBytes??131072}async autoSkillCategories(){return Li(ki((await this.loadIndexState()).categories))}async autoSkillList(e={}){let t=e.categoryPath?bi(e.categoryPath):void 0;return(await this.visibleEntries()).filter(e=>Ri(e.categoryPath,t)).map(Ii)}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:zi(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})=>({...Ii(e),score:t}))}async autoSkillView(e){let t=Ci(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=Ei(n.skillDir,e.filePath),r=await Ji(t,this.maxResourceBytes);return{...Ii(n),status:n.status,content:r,path:Zi(G.relative(this.rootDir,t)),skillDir:n.skillDir,filePath:Zi(G.relative(n.skillDir,t))}}let r=await Ji(n.skillFile,this.maxSkillBytes);return{...Ii(n),status:n.status,content:r,path:Zi(G.relative(this.rootDir,n.skillFile)),skillDir:n.skillDir,tags:n.tags,relatedSkills:n.relatedSkills}}async loadIndex(){let e=await this.loadIndexState();return this.visibleEntriesFrom(e.entries)}async loadIndexState(e=!1){let t=this.optionsHash(),n=`${this.rootDir}|${t}`,r=await Bi(this.rootDir),i=Mi.get(n);if(!e&&i&&Gi(i.manifest,r))return i;let a=e?void 0:await Ui(this.rootDir,t,r);if(a){let e={optionsHash:t,manifest:r,entries:a.entries,categories:a.categories};return Mi.set(n,e),e}let o=await Oi(this.rootDir),s=ki(o),c={optionsHash:t,manifest:r,entries:(await this.parseEntriesFromManifest(r)).filter(e=>s.has(e.categoryPath)),categories:o};return Mi.set(n,c),await Wi(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 ea({loaderVersion:`auto-skills-loader-v2`,rootDir:this.rootDir,includeArchived:this.includeArchived,maxSkillBytes:this.maxSkillBytes,maxResourceBytes:this.maxResourceBytes,indexHeadBytes:ji})}async loadEntry(e){try{let t=G.dirname(e),n=xi(G.basename(t)),r=Zi(G.relative(this.rootDir,t)),i=bi(G.posix.dirname(r)),a=Si(i,n),o=G.join(t,`metadata.json`),s=await Ki(o);if(s?.skillId&&Ci(s.skillId).skillId!==a)throw Error(`metadata skillId does not match path for ${a}`);if(s?.categoryPath&&bi(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=wi(s?.status);return{skillId:a,name:n,description:Yi(await qi(e,ji)),categoryPath:i,source:`auto`,status:c,rootDir:this.rootDir,skillDir:t,skillFile:e,metadataFile:s?o:void 0,tags:Xi(s?.tags),relatedSkills:Xi(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}: ${Qi(t)}\n`);return}}};function Ii(e){return{skillId:e.skillId,name:e.name,description:e.description,categoryPath:e.categoryPath,source:e.source}}function Li(e){return Array.from(e.values()).sort((e,t)=>e.path.localeCompare(t.path))}function Ri(e,t){return t?e===t:!0}function zi(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 Bi(e){let t;try{t=await W.readdir(e,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)return[];throw e}let n=[];return await Hi(G.join(e,`categories.json`),`categories`,n),await Vi(e,t,n),n.sort((e,t)=>e.filePath.localeCompare(t.filePath)||e.kind.localeCompare(t.kind))}async function Vi(e,t,n){for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(r.name.startsWith(`.`))continue;let t=G.join(e,r.name);if(r.isFile()&&r.name===`SKILL.md`){await Hi(t,`skill`,n),await Hi(G.join(e,`metadata.json`),`metadata`,n),await Hi(G.join(e,`DESCRIPTION.md`),`description`,n);continue}if(!r.isDirectory())continue;let i;try{i=await W.readdir(t,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)continue;throw e}await Vi(t,i,n)}}async function Hi(e,t,n){try{let r=await W.stat(e);if(!r.isFile())return;n.push({filePath:e,kind:t,size:r.size,mtimeMs:r.mtimeMs})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}}async function Ui(e,t,n){let r;try{r=await W.readFile(_i(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)||!Gi(e.manifest,n)?void 0:e}catch{return}}async function Wi(e,t){if(!await $i(e))return;let n={version:1,createdAt:new Date().toISOString(),optionsHash:t.optionsHash,manifest:t.manifest,entries:t.entries,categories:t.categories};await W.writeFile(_i(e),`${JSON.stringify(n,null,2)}\n`,`utf-8`)}function Gi(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 Ki(e){try{let t=await W.readFile(e,`utf-8`),n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}catch(e){if(e.code===`ENOENT`)return;throw e}}async function qi(e,t){let n=await W.open(e,`r`);try{let e=await n.stat(),r=Math.min(e.size,t),i=Buffer.alloc(r);return await n.read(i,0,r,0),i.toString(`utf-8`)}finally{await n.close()}}async function Ji(e,t){if((await W.stat(e)).size>t)throw Error(`Auto-skill file exceeds size limit: ${e}`);return W.readFile(e,`utf-8`)}function Yi(e){let t=ct(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 Xi(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function Zi(e){return e.split(G.sep).join(`/`)}function Qi(e){return e instanceof Error?e.message:String(e)}async function $i(e){try{return await W.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ea(e){return nt(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function ta(e){return e??`openai-completions`}function na(e,t,n){let r={"Client-Code":`AIMax`,"X-Session-Id":e};return t&&(r[`X-Message-Id`]=t),n&&(r[`X-Channel`]=n),r}function ra(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}const ia={apiFormat:`anthropic-messages`,createModel:aa,buildRequest:sa,normalizeResponse:ca};function aa(e,t,n,r){return{id:e.model,name:e.model,api:`anthropic-messages`,provider:`anthropic`,baseUrl:oa(e.baseUrl),reasoning:!1,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:na(t,n,r)}}function oa(e){return e.replace(/\/+$/,``).replace(/\/v1$/,``)}function sa(e,t,n,r){let i=e.baseUrl.replace(/\/+$/,``),a=[],o=[];for(let e of n){if(e.role===`system`){e.content.trim()&&o.push(e.content);continue}a.push({role:e.role,content:e.content})}let s={model:t,messages:a.length>0?a:[{role:`user`,content:``}],max_tokens:r.maxTokens??2048,stream:!1};return o.length>0&&(s.system=o.join(`
9
+
10
+ `)),typeof r.temperature==`number`&&(s.temperature=r.temperature),{url:i.endsWith(`/v1`)?`${i}/messages`:`${i}/v1/messages`,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`,"Client-Code":`AIMax`},body:s}}function ca(e){let t=e,n=t.content?.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``)??``,r=(t.usage?.input_tokens??0)+(t.usage?.cache_read_input_tokens??0)+(t.usage?.cache_creation_input_tokens??0),i=t.usage?.output_tokens??0;return{text:n,usage:{input:r,output:i,total:r+i},raw:e}}const la={apiFormat:`openai-completions`,createModel:ua,buildRequest:da,normalizeResponse:fa};function ua(e,t,n,r){let i=e.baseUrl.includes(`deepseek.com`),a=e.thinking;return{id:e.model,name:e.model,api:`openai-completions`,provider:i?`deepseek`:`openai`,baseUrl:e.baseUrl,reasoning:i||!!a,...i&&{thinkingLevelMap:{high:`high`,xhigh:`max`}},...a&&!i&&{thinkingLevelMap:{high:`high`,xhigh:`high`}},input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:na(t,n,r),compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!!(a&&!i),supportsUsageInStreaming:!0,...a&&!i&&{thinkingFormat:`deepseek`}}}}function da(e,t,n,r){let i={model:t,messages:n,stream:!1};return typeof r.temperature==`number`&&(i.temperature=r.temperature),typeof r.maxTokens==`number`&&(i.max_tokens=r.maxTokens),{url:`${e.baseUrl.replace(/\/+$/,``)}/chat/completions`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:i}}function fa(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:ra(t.usage),raw:e}}const pa={"openai-completions":la,"anthropic-messages":ia};function ma(e){return pa[e]}function ha(e,t,n,r){return ma(ta(e.apiFormat)).createModel(e,t,n,r)}const ga=`/aimax/agents`,_a=/^[a-z]+(?:-[a-z]+)*$/;function va(e){let t=[{dir:e.systemAgentsDir??ga,source:`system`},{dir:G.join(e.dataDir,`.aimax`,`agents`),source:`user`}];return e.projectDir?.trim()&&t.push({dir:G.join(e.projectDir.trim(),`.aimax`,`agents`),source:`project`}),t}async function ya(e){let t=new Map;for(let n of va(e)){let e=await Ca(n.dir,n.source);for(let n of e)t.set(n.name,n)}return Array.from(t.values())}function ba(e={}){let t=e.allAgents??e.availableAgents??[],n=Da(e.availableAgents??t);return{allAgents:t,availableAgents:n,findPublic:e=>Ta(n,e),findAny:e=>Ta(t,e,{includeInternal:!0}),stats:()=>({total:t.length,public:n.length,internal:Math.max(0,t.length-n.length)})}}function xa(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 Sa(e){return xa(e.agentPolicy)?e.agentPolicy:ba({allAgents:await ya(e)})}async function Ca(e,t){let n;try{n=await W.readdir(e,{withFileTypes:!0})}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return[];throw e}let r=[];for(let i of n){if(!i.isFile()||!i.name.endsWith(`.md`))continue;let n=G.join(e,i.name),a=wa(await W.readFile(n,`utf-8`),{sourcePath:n,source:t});a&&r.push(a)}return r.sort((e,t)=>e.name.localeCompare(t.name)),r}function wa(e,t){let n=ct(e),r=Ma(n.data.name)?.trim(),i=Ma(n.data.description)?.trim();if(!r||!_a.test(r)||!i)return;let a=Ma(n.data.model)?.trim(),o=Ma(n.data.initPrompt)?.trim()??Ma(n.data.initialPrompt)?.trim(),s=Na(n.data.maxTurns),c=Pa(n.data.tools),l=Pa(n.data.disallowedTools),u=Pa(n.data.skills),d=Fa(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 Ta(e,t,n={}){let r=t?.trim();if(r)return e.find(e=>e.name===r&&(n.includeInternal||Ea(e)===`public`))}function Ea(e){return e.visibility??`public`}function Da(e){return e.filter(e=>Ea(e)===`public`)}function Oa(e,t){if(!t?.skills)return e;let n=new Set(t.skills);return e.filter(e=>n.has(e.name))}function ka(e,t){if(!t?.tools&&!t?.disallowedTools)return e;let n=t.tools?new Set(t.tools.map(Ia)):void 0,r=new Set((t.disallowedTools??[]).map(Ia));return e.filter(e=>{let t=typeof e.name==`string`?Ia(e.name):``;return!t||n&&!n.has(t)?!1:!r.has(t)})}function Aa(e){let t=Da(e).filter(e=>e.source!==`system`);return t.length===0?``:[`## Custom Agents`,`The following custom agents are currently effective.`,"When delegating with `subagent_spawn`, you may set the optional `agent` field only to one of the exact names listed below.","Do not guess, invent, paraphrase, translate, or synthesize agent names. If no listed custom agent clearly matches, leave `agent` unset and delegate normally.","When the user's message contains `@<agent-name>` (e.g. `@secure-code-reviewer`) and the name exactly matches one of the listed custom agents, that mention is an explicit delegation request.","For such a matching `@<agent-name>` request, you MUST call `subagent_spawn` to run the request through that custom agent, with the `agent` field set to the exact matched agent name.","Do not answer the request yourself, do not merely describe the agent, and do not omit the tool call when a matching `@<agent-name>` is present.",`If the mention does not exactly match a listed custom agent, do not invent a match; continue with the current agent or ask a concise clarification if needed.`,t.map(e=>`- ${e.name}: ${e.description}`).join(`
11
11
  `),``].join(`
12
- `)}function Oa(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function ka(e){return typeof e==`string`?e:void 0}function Aa(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function ja(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 Ma(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Na(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}const Pa=new ct;async function Fa(e,t){return await Pa.run(e,t)}function Ia(e){return{async emit(t){let n=Pa.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const La={before_prompt_build:`before_agent_start`,after_tool_call:`tool_result (for mutable results) or before_tool_call (for blocking)`};var Ra=class{hooks=new Map;deprecatedWarned=new Set;register(e){let t=La[e.hookName];t&&!this.deprecatedWarned.has(e.hookName)&&(this.deprecatedWarned.add(e.hookName),console.warn(`[PluginHookRegistry] Hook "${e.hookName}" is deprecated. Use "${t}" instead. (plugin: ${e.pluginId})`));let n=this.hooks.get(e.hookName)??[];n.push(e),n.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,n)}async dispatch(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await Fa({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push(o)}return a}};function za(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function Ba(e=new Date){let t=za(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let Va=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});const Ha=new ct;function Ua(e,t){return Ha.run(e,t)}let Wa=null,Ga=[];function Ka(){return Ba()}function qa(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Ja(e){return W.join(e,`.aimax`)}function Ya(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function Xa(e,t){let n=t?.sessionStoreName?.trim()||`sessions`,r=Ya(t?.messageId);return t?.sessionDir?{runLogId:r,logDir:W.join(t.sessionDir,`logs`,r)}:t?.sessionId?{runLogId:r,logDir:W.join(Ja(e),n,t.sessionId,`logs`,r)}:{runLogId:r,logDir:W.join(Ja(e),`logs`,r)}}function Za(e){return{appLogPath:W.join(e,`app.log`),errorLogPath:W.join(e,`errors.log`)}}function Qa(e){let{appLogPath:t,errorLogPath:n}=Za(e);lt.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function $a(e,t,n){return`[${Ka()}] [${e}] ${t}${qa(n)}`}function eo(e,t,n){let r=Ha.getStore();if(r){r({level:e,message:t,context:n,formatted:$a(e,t,n)});return}try{process.stderr.write(`${$a(e,t,n)}\n`)}catch{}}function to(e,t,n){if(!Wa){Ga.push({level:e,message:t,context:n}),Ga.length>200&&(Ga=Ga.slice(-200)),eo(e,t,n);return}let r=$a(e,t,n),i=lt.getLogger();e===Va.ERROR?i.error(r):e===Va.WARN?i.warn(r):i.info(r);let a=Ha.getStore();a&&a({level:e,message:t,context:n,formatted:r})}function no(e,t){let{logDir:n,runLogId:r}=Xa(e,t);if(Wa?.dataDir===e&&Wa.runLogId===r&&Wa.logDir===n)return;G.mkdirSync(n,{recursive:!0}),Qa(n),Wa={dataDir:e,logDir:n,runLogId:r};let i=Ga;Ga=[];for(let e of i)to(e.level,e.message,e.context)}const J={info:(e,t)=>to(Va.INFO,e,t),warn:(e,t)=>to(Va.WARN,e,t),error:(e,t)=>to(Va.ERROR,e,t)};function ro(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}var io=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){J.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})}},ao=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function oo(e){return{async chat(t){let n=co(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await uo(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:lo(n),historyMessages:n},e.hookCtx);let i=da(Qi(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=fo(t.signal,t.timeoutMs);try{let t;try{t=await fetch(a.url,{method:`POST`,headers:a.headers,body:JSON.stringify(a.body),signal:o})}catch(e){throw mo(e,c())}if(!t.ok){let e=await po(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new ao({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:go(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw so(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await uo(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:l?[l]:[],durationMs:d,usage:u},e.hookCtx),{text:l,usage:u,raw:s}}finally{s()}}}}function so(e,t){return ho(e)&&t?new ao({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):ho(e)?new ao({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new ao({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function co(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function lo(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
13
- `)}async function uo(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function fo(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function po(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function mo(e,t){return e instanceof ao?e:ho(e)?t?new ao({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new ao({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function ho(e){return e instanceof Error&&e.name===`AbortError`}function go(e){return e===408||e===409||e===425||e===429||e>=500}var _o=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 vo(e){return!!(e instanceof _o||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var yo=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function bo(e){return!!(e instanceof yo||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const xo=new ct;function So(){return{}}async function Co(e,t){return await xo.run(e,t)}function wo(e){let t=xo.getStore();!t||t.signal||(t.signal=e)}const To=new ct;function Eo(){return{}}async function Do(e,t){return await To.run(e,t)}function Oo(e){let t=To.getStore();!t||t.signal||(t.signal=e)}function ko(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function Ao(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 jo(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 Mo(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:jo(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:jo(e.content,`(tool image omitted: model does not support images)`)}:e)}function No(e,t,n){let r=new Map,i=Mo(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 Po(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function Fo(e){if(!Po(e))return null;let t=e,n=Io(t.message),r=Ro(n?.code)??Ro(t.code),i=Ro(n?.type)??Ro(t.type),a=Ro(n?.message)??Lo(t.error)??Ro(t.message)??`Unknown upstream error`;return{message:zo(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:Bo(r,i),raw:e}}function Io(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 Lo(e){if(!(!e||typeof e!=`object`))return Ro(e.message)}function Ro(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 Bo(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 Vo(e,t=`error`){let n={};Ho(n,t,e);let r=qo(e);return r!==void 0&&Ho(n,`${t}Cause`,r),n}function Ho(e,t,n){e[`${t}Type`]=Uo(n),e[`${t}Name`]=Go(n,`name`),e[`${t}Message`]=Wo(n),e[`${t}Code`]=Ko(n,`code`),e[`${t}Status`]=Ko(n,`status`),e[`${t}StatusCode`]=Ko(n,`statusCode`)}function Uo(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 Wo(e){if(e instanceof Error)return Jo(e.message);if(typeof e==`string`)return Jo(e);let t=Go(e,`message`);return t?Jo(t):void 0}function Go(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 Ko(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 qo(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function Jo(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const Yo=(e,t,n)=>{let r=pt();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=Qo(e,t,n?.apiKey||mt(e.provider)||``,n?.headers),c=$o(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=ht(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=Fo(t);if(n)throw new ao({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}},dt(e,i.usage)}let o=t.choices?.[0];if(!o||(o.finish_reason&&(i.stopReason=is(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=ht(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){J.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,...Vo(t,`streamError`)});for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=t instanceof Error?t.message:JSON.stringify(t),t instanceof ao&&Object.assign(i,{errorCode:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable});let s=t?.error?.metadata?.raw;s&&(i.errorMessage+=`\n${s}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Xo=(e,t,n)=>{let r=n?.apiKey||mt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=Ao(e,n,r),a=n?.reasoning?ft(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return Yo(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function Zo(e,t,n){return $o(e,t,n)}function Qo(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 $o(e,t,n){let r=os(e),i=ns(e,t,r);ts(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=rs(t.tools,r):es(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 es(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 ts(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 ns(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=No(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:ko(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:ko(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:ko(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=>ko(e.text)).join(``):a.map(e=>({type:`text`,text:ko(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
12
+ `)}function ja(e,t){let n=e.initPrompt?.trim(),r=t.trim();return n?`${n}\n\n${r}`:r}function Ma(e){return typeof e==`string`?e:void 0}function Na(e){if(!(typeof e!=`number`||!Number.isInteger(e)||e<=0))return e}function Pa(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 Fa(e){if(e!==void 0&&!(e!==`public`&&e!==`internal`))return e}function Ia(e){let t=e.trim();return{bash:`exec`,read:`read_file`,write:`write_file`,edit:`edit_file`,multiedit:`edit_file`,glob:`list_dir`,grep:`exec`}[t.toLowerCase()]??t}const La=new ut;async function Ra(e,t){return await La.run(e,t)}function za(e){return{async emit(t){let n=La.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const Ba={before_prompt_build:`before_agent_start`,after_tool_call:`tool_result (for mutable results) or before_tool_call (for blocking)`};var Va=class{hooks=new Map;deprecatedWarned=new Set;register(e){let t=Ba[e.hookName];t&&!this.deprecatedWarned.has(e.hookName)&&(this.deprecatedWarned.add(e.hookName),console.warn(`[PluginHookRegistry] Hook "${e.hookName}" is deprecated. Use "${t}" instead. (plugin: ${e.pluginId})`));let n=this.hooks.get(e.hookName)??[];n.push(e),n.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,n)}async dispatch(e,t,n,r){return(await this.dispatchWithMetadata(e,t,n,r)).map(e=>e.result)}async dispatchWithMetadata(e,t,n,r){let i=this.hooks.get(e)??[],a=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await Ra({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push({pluginId:e.pluginId,source:e.source,result:o})}return a}};function Ha(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function Ua(e=new Date){let t=Ha(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let Wa=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});const Ga=new ut;function Ka(e,t){return Ga.run(e,t)}let qa=null,Ja=[];function Ya(){return Ua()}function Xa(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Za(e){return G.join(e,`.aimax`)}function Qa(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function $a(e,t){let n=t?.sessionStoreName?.trim()||`sessions`,r=Qa(t?.messageId);return t?.sessionDir?{runLogId:r,logDir:G.join(t.sessionDir,`logs`,r)}:t?.sessionId?{runLogId:r,logDir:G.join(Za(e),n,t.sessionId,`logs`,r)}:{runLogId:r,logDir:G.join(Za(e),`logs`,r)}}function eo(e){return{appLogPath:G.join(e,`app.log`),errorLogPath:G.join(e,`errors.log`)}}function to(e){let{appLogPath:t,errorLogPath:n}=eo(e);dt.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function no(e,t,n){return`[${Ya()}] [${e}] ${t}${Xa(n)}`}function ro(e,t,n){let r=Ga.getStore();if(r){r({level:e,message:t,context:n,formatted:no(e,t,n)});return}try{process.stderr.write(`${no(e,t,n)}\n`)}catch{}}function io(e,t,n){if(!qa){Ja.push({level:e,message:t,context:n}),Ja.length>200&&(Ja=Ja.slice(-200)),ro(e,t,n);return}let r=no(e,t,n),i=dt.getLogger();e===Wa.ERROR?i.error(r):e===Wa.WARN?i.warn(r):i.info(r);let a=Ga.getStore();a&&a({level:e,message:t,context:n,formatted:r})}function ao(e,t){let{logDir:n,runLogId:r}=$a(e,t);if(qa?.dataDir===e&&qa.runLogId===r&&qa.logDir===n)return;K.mkdirSync(n,{recursive:!0}),to(n),qa={dataDir:e,logDir:n,runLogId:r};let i=Ja;Ja=[];for(let e of i)io(e.level,e.message,e.context)}const J={info:(e,t)=>io(Wa.INFO,e,t),warn:(e,t)=>io(Wa.WARN,e,t),error:(e,t)=>io(Wa.ERROR,e,t)};function oo(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}var so=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){J.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})}},co=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function lo(e){return{async chat(t){let n=fo(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await mo(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:po(n),historyMessages:n},e.hookCtx);let i=ma(ta(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=ho(t.signal,t.timeoutMs);try{let t;try{t=await fetch(a.url,{method:`POST`,headers:a.headers,body:JSON.stringify(a.body),signal:o})}catch(e){throw _o(e,c())}if(!t.ok){let e=await go(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new co({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:yo(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw uo(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await mo(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:l?[l]:[],durationMs:d,usage:u},e.hookCtx),{text:l,usage:u,raw:s}}finally{s()}}}}function uo(e,t){return vo(e)&&t?new co({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):vo(e)?new co({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new co({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function fo(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function po(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
13
+ `)}async function mo(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function ho(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function go(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function _o(e,t){return e instanceof co?e:vo(e)?t?new co({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new co({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function vo(e){return e instanceof Error&&e.name===`AbortError`}function yo(e){return e===408||e===409||e===425||e===429||e>=500}const bo=`<aimax_artifacts>`,xo=`</aimax_artifacts>`;function So(e,t={}){let n=[];if(!e.includes(bo))return{cleanedText:e,artifacts:[],warnings:n};let r=e,i,a=[];for(;;){let e=r.indexOf(bo);if(e===-1)break;let o=r.indexOf(xo,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(...Co(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(`
14
+ `).trimEnd()}return{cleanedText:r,artifacts:a,warnings:n}}function Co(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=wo(t,{index:e,warnings:n,timestamp:r,workspaceDir:i});s&&o.push(s)}return o}function wo(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=Eo(t,a);return o?{kind:`file`,file:o,timestamp:i,label:To(e.label,G.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=Oo(s)??`URL artifact`;return Do(s)?{kind:`url`,url:s,timestamp:i,label:To(e.label,c,n,r)}:(r.push(`Artifact at index ${n}: url is invalid, skipping`),null)}function To(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 Eo(e,t){return G.isAbsolute(e)?G.normalize(e):t?.trim()?G.normalize(G.join(t,e)):null}function Do(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}function Oo(e){try{return new URL(e).host||void 0}catch{return}}var ko=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(xo);if(e===-1){let e=Ao(this.buffer,xo);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(bo);if(e!==-1){t+=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e+17),this.suppressing=!0;continue}let n=Ao(this.buffer,bo);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 Ao(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 jo(e){if(e.isError)return[];let t=(e.now??(()=>new Date))().toISOString(),n=Ro(e.result),r=[];if(e.toolName===`write_file`){let i=Bo(Yo(n.details?.path),e.workspaceDir);return i&&r.push(Uo(i,t,Ko(i))),Go(r)}if(e.toolName===`edit_file`){let i=Xo(n.details?.occurrences),a=Bo(Yo(n.details?.path),e.workspaceDir);return a&&i!==0&&r.push(Uo(a,t,Ko(a))),Go(r)}if(e.toolName===`apply_patch`)return r.push(...Mo(n.details,e.workspaceDir,t)),Go(r);if(e.toolName===`exec`||e.toolName===`bash`||e.toolName===`process`){if(Ho(n.details))return[];let i=Yo(e.input?.command),a=zo(Yo(n.details?.cwd),e.workspaceDir);return r.push(...No({command:i,output:n.content,cwd:a,workspaceDir:e.workspaceDir,timestamp:t})),r}let i=Vo(n.content);return i?[Wo(i,t,qo(i))]:[]}function Mo(e,t,n){let r=e?.summary&&typeof e.summary==`object`?e.summary:void 0;return r?[...Jo(r.added),...Jo(r.modified)].flatMap(e=>{let r=Bo(e,t);return r?[Uo(r,n,Ko(r))]:[]}):[]}function No(e){let t=[],n=e.cwd??e.workspaceDir,r=r=>{let i=Bo(r,n);i&&t.push(Uo(i,e.timestamp,Ko(i)))};if(e.command)for(let t of Po(e.command))r(t);for(let t of Lo(e.output))r(t);let i=Vo(e.output);return i&&t.push(Wo(i,e.timestamp,qo(i))),Go(t)}function Po(e){let t=Fo(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 Fo(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(...Io(r))}return t.join(`
15
+ `)}function Io(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 Lo(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(Qo(a.trim()))}return t}function Ro(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 zo(e,t){return e?.trim()?G.normalize(e):t}function Bo(e,t){let n=Zo(e?.trim()??``);return!n||n.startsWith(`-`)||n===`/dev/null`||n.startsWith(`/dev/`)||$o(n)?null:G.isAbsolute(n)?G.normalize(n):t?.trim()?G.normalize(G.join(t,n)):null}function Vo(e){let t=e.trim();return!t||/\s/.test(t)?null:es(t)?new URL(t).toString():null}function Ho(e){let t=Yo(e?.status);return t===`running`||t===`failed`||t===`killed`||t===`timeout`}function Uo(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 Go(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 Ko(e){return G.basename(e)||`File artifact`}function qo(e){try{return new URL(e).host||`URL artifact`}catch{return`URL artifact`}}function Jo(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim().length>0):[]}function Yo(e){return typeof e==`string`&&e.trim().length>0?e:void 0}function Xo(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Zo(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function Qo(e){return e.replace(/[),.;,。;)]+$/u,``)}function $o(e){return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)}function es(e){try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}}var ts=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 ns(e){return!!(e instanceof ts||typeof e==`object`&&e&&`isHitlPause`in e&&e.isHitlPause===!0)}var rs=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function is(e){return!!(e instanceof rs||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const as=new ut;function os(){return{}}async function ss(e,t){return await as.run(e,t)}function cs(e){let t=as.getStore();!t||t.signal||(t.signal=e)}const ls=new ut;function us(){return{}}async function ds(e,t){return await ls.run(e,t)}function fs(e){let t=ls.getStore();!t||t.signal||(t.signal=e)}function ps(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,``)}function ms(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 hs(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 gs(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:hs(e.content,`(image omitted: model does not support images)`)}:e.role===`toolResult`?{...e,content:hs(e.content,`(tool image omitted: model does not support images)`)}:e)}function _s(e,t,n){let r=new Map,i=gs(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 vs(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.error&&typeof t.error==`object`?!0:t.object===`error`}function ys(e){if(!vs(e))return null;let t=e,n=bs(t.message),r=Ss(n?.code)??Ss(t.code),i=Ss(n?.type)??Ss(t.type),a=Ss(n?.message)??xs(t.error)??Ss(t.message)??`Unknown upstream error`;return{message:Cs(a,i,r),providerMessage:a,providerCode:r,providerType:i,retryable:ws(r,i),raw:e}}function bs(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 xs(e){if(!(!e||typeof e!=`object`))return Ss(e.message)}function Ss(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function Cs(e,t,n){let r=[t,n].filter(Boolean).join(` `);return r?`${e} (${r})`:e}function ws(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 Ts(e,t=`error`){let n={};Es(n,t,e);let r=js(e);return r!==void 0&&Es(n,`${t}Cause`,r),n}function Es(e,t,n){e[`${t}Type`]=Ds(n),e[`${t}Name`]=ks(n,`name`),e[`${t}Message`]=Os(n),e[`${t}Code`]=As(n,`code`),e[`${t}Status`]=As(n,`status`),e[`${t}StatusCode`]=As(n,`statusCode`)}function Ds(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 Os(e){if(e instanceof Error)return Ms(e.message);if(typeof e==`string`)return Ms(e);let t=ks(e,`message`);return t?Ms(t):void 0}function ks(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 As(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 js(e){if(!(!e||typeof e!=`object`&&typeof e!=`function`))return e.cause}function Ms(e,t=500){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}const Ns=(e,t,n)=>{let r=ht();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=Is(e,t,n?.apiKey||gt(e.provider)||``,n?.headers),c=Ls(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=_t(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=ys(t);if(n)throw new co({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}},pt(e,i.usage)}let o=t.choices?.[0];if(!o||(o.finish_reason&&(i.stopReason=Hs(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=_t(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){J.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,...Ts(t,`streamError`)});for(let e of i.content)delete e.index;i.stopReason=n?.signal?.aborted?`aborted`:`error`,i.errorMessage=t instanceof Error?t.message:JSON.stringify(t),t instanceof co&&Object.assign(i,{errorCode:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable});let s=t?.error?.metadata?.raw;s&&(i.errorMessage+=`\n${s}`),r.push({type:`error`,reason:i.stopReason,error:i}),r.end()}})(),r},Ps=(e,t,n)=>{let r=n?.apiKey||gt(e.provider);if(!r)throw Error(`No API key for provider: ${e.provider}`);let i=ms(e,n,r),a=n?.reasoning?mt(e,n.reasoning):void 0,o=a===`off`?void 0:a,{onPayload:s,...c}=i;return Ns(e,t,{...c,...s?{onPayload:t=>s(t,e)}:{},reasoningEffort:o,toolChoice:void 0})};function Fs(e,t,n){return Ls(e,t,n)}function Is(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 ft({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:i})}function Ls(e,t,n){let r=Ws(e),i=Bs(e,t,r);zs(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=Vs(t.tools,r):Rs(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 Rs(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 zs(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 Bs(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=_s(t.messages,e,e=>i(e));if(t.systemPrompt){let i=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;r.push({role:i,content:ps(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:ps(i.content)});else{let t=i.content.map(e=>e.type===`text`?{type:`text`,text:ps(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=>ps(e.text)).join(``):a.map(e=>({type:`text`,text:ps(e.text)})));let s=i.content.filter(e=>e.type===`thinking`&&e.thinking?.trim().length>0);if(s.length>0)if(n.requiresThinkingAsText){let e=s.map(e=>e.thinking).join(`
14
16
 
15
17
  `);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
16
18
  `))}let c=i.content.filter(e=>e.type===`toolCall`);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}let l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t),o=i.role;continue}if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s+=1){let t=a[s],o=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
17
- `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:ko(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 rs(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function is(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 as(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 os(e){let t=as(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 ss=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),cs=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),ls=[`llmrequesterror`];function us(e){let t=ms(e?.maxAttempts,3),n=hs(e?.initialDelayMs,250),r=hs(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function ds(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function fs(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 ps(e){if(vs(e))return!1;let t=gs(e),n=_s(e);if(t?.statusCode!==void 0)return bs(t.statusCode);if(t?.providerCode!==void 0)return ys(t.providerCode);let r=t?.message??n,i=xs(r);if(i!==void 0)return bs(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(ss.has(e))return!0;if(cs.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;let a=Ss(r);return a===void 0?Cs(r)?!0:t?.retryable===!0:a}function ms(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function hs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function gs(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 _s(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 vs(e){return gs(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function ys(e){return/^\d+$/.test(e)?bs(Number(e)):!1}function bs(e){return e===408||e===409||e===425||e===429||e>=500}function xs(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function Ss(e){if(!e)return;let t=ws(e);for(let e of cs)if(t.includes(e))return!1;for(let e of ss)if(t.includes(e))return!0}function Cs(e){if(!e)return!1;let t=ws(e);return ls.some(e=>t.includes(e))}function ws(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const Ts=Symbol(`omit-json-value`);function Es(e,t=new WeakSet){if(e===void 0)return Ts;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=Es(r,t);e!==Ts&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=Es(i,t);e!==Ts&&(n[r]=e)}return n}finally{t.delete(e)}}function Ds(e,t,n){return W.join(W.dirname(C(e,t,n)),`session-tools.json`)}function Os(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:Es(e.parameters??{})}))}async function ks(e,t,n){let r=await o(Ds(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 As(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:Os(n.tools)},a=`${JSON.stringify(i,null,2)}\n`;await Promise.all([L(C(e,t,r),n.systemPrompt,r?.encryptSessions),L(Ds(e,t,r),a,r?.encryptSessions)])}async function js(e,t,n){let[r,i]=await Promise.all([g(e,t,n),ks(e,t,n)]);return{...r?.trim()?{systemPrompt:r}:{},...i&&i.tools.length>0?{tools:i.tools}:{}}}function Ms(e){return Math.ceil(e.length/4*1.2)}function Ns(e){if(e.role===`user`)return Ms(e.content);if(e.role===`assistant`){let t=Ms(e.content),n=e.thinking?.trim();n&&(t+=Ms(n)),e.errorMessage&&(t+=Ms(e.errorMessage));for(let n of e.toolCalls??[])t+=Ms(n.name)+Ms(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(`
18
- `):e.content;return Ms(e.toolName)+Ms(t)}function Y(e){return e.reduce((e,t)=>e+Ns(t),0)}function Ps(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 Fs(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 Is=[`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.`],Ls={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Rs(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function zs(e,t,n){return e.map(e=>Bs(e,t,n))}function Bs(e,t,n){let r=new Date(e.timestamp).getTime();if(Vs(e))return{role:`user`,content:e.content,timestamp:r};if(Hs(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:Ls,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:Us(i)}],isError:i.isError,timestamp:r}}function Vs(e){return e.role===`user`}function Hs(e){return e.role===`assistant`}function Us(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:`,...Is];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
19
- `)}const Ws=[`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(`
20
- `);async function Gs(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=qs(t,r,i,a),u=Js(a),d,f=oo({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:Ws,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 Ks(500*e)}throw d}function Ks(e){return new Promise(t=>setTimeout(t,e))}function qs(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${Qs(t.trim(),Ys(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=Xs(e,t,n,r),o=Zs(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: ${Qs(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(`, `)}]`:``} ${Qs(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?$s(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(`
21
- `):n.content;r=`Tool(${n.toolName})[${e}]: ${Qs(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
22
- `)}function Js(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function Ys(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function Xs(e,t,n,r){let i=Zs(t,n,r);if(!r||r<=0)return 2e3;let a=Js(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=Ws.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 Zs(e,t,n){if(!n||n<=0)return 1/0;let r=Js(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=Ws.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function Qs(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function $s(e){let t=ec(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(`
23
- `)}function ec(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=tc(t);if(e.name||e.path)return e}return{}}function tc(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 nc(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=Ns(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function rc(e){return ac((await oo({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:cc,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 ic(e){return oc((await oo({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:lc,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 ac(e){let t=sc(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=sc(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 sc(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(`
24
- `);const cc=[`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(`
25
- `),lc=[`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(`
26
- `);async function uc(e){let t=hc(e);if(t)try{let e=await U.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(jc);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function dc(e){let t=hc(e);t&&(await U.mkdir(W.dirname(t),{recursive:!0}),await U.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function fc(e){let t=gc(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||_c(t,e)){r.push(e);continue}n.push(yc(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(yc(r,n.length+1,!0)),n}function pc(e,t){let n=gc(t);if(n.length===0)return[];if(!e||e.length===0)return fc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return fc(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&&vc(t,e)){a[a.length-1]=wc(t,e);continue}t&&(t.status=`closed`),a.push(yc([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 mc(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 hc(e){if(!(!e.dataDir||!e.sessionId))return W.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function gc(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 _c(e,t){return Dc(Ec(e.user,e.assistant),Ec(t.user,t.assistant))>0}function vc(e,t){return Dc(Ec(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),Ec(t.user,t.assistant,t.toolNames.join(` `)))>0}function yc(e,t,n){return bc(e,t,n)}function bc(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=xc(e,o),c=Ac(r?.summary||s),l=Tc(r?.keywords,c,o),u=Ac(r?.compressedSummary||Cc(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(`
19
+ `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:ps(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 Vs(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function Hs(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 Us(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 Ws(e){let t=Us(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 Gs=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),Ks=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]),qs=[`llmrequesterror`];function Js(e){let t=Qs(e?.maxAttempts,3),n=$s(e?.initialDelayMs,250),r=$s(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function Ys(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function Xs(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 Zs(e){if(nc(e))return!1;let t=ec(e),n=tc(e);if(t?.statusCode!==void 0)return ic(t.statusCode);if(t?.providerCode!==void 0)return rc(t.providerCode);let r=t?.message??n,i=ac(r);if(i!==void 0)return ic(i);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(Gs.has(e))return!0;if(Ks.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;let a=oc(r);return a===void 0?sc(r)?!0:t?.retryable===!0:a}function Qs(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function $s(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function ec(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 tc(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 nc(e){return ec(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function rc(e){return/^\d+$/.test(e)?ic(Number(e)):!1}function ic(e){return e===408||e===409||e===425||e===429||e>=500}function ac(e){if(!e)return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}function oc(e){if(!e)return;let t=cc(e);for(let e of Ks)if(t.includes(e))return!1;for(let e of Gs)if(t.includes(e))return!0}function sc(e){if(!e)return!1;let t=cc(e);return qs.some(e=>t.includes(e))}function cc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,``)}const lc=Symbol(`omit-json-value`);function uc(e,t=new WeakSet){if(e===void 0)return lc;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=uc(r,t);e!==lc&&n.push(e)}return n}let n={};for(let[r,i]of Object.entries(e)){let e=uc(i,t);e!==lc&&(n[r]=e)}return n}finally{t.delete(e)}}function dc(e,t,n){return G.join(G.dirname(C(e,t,n)),`session-tools.json`)}function fc(e){return e.map(e=>({name:typeof e.name==`string`?e.name:String(e.name),description:typeof e.description==`string`?e.description:``,parameters:uc(e.parameters??{})}))}async function pc(e,t,n){let r=await o(dc(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 mc(e,t,n,r){await v(e,t,r);let i={version:1,recordedAt:new Date().toISOString(),tools:fc(n.tools)},a=`${JSON.stringify(i,null,2)}\n`;await Promise.all([L(C(e,t,r),n.systemPrompt,r?.encryptSessions),L(dc(e,t,r),a,r?.encryptSessions)])}async function hc(e,t,n){let[r,i]=await Promise.all([g(e,t,n),pc(e,t,n)]);return{...r?.trim()?{systemPrompt:r}:{},...i&&i.tools.length>0?{tools:i.tools}:{}}}function gc(e){return Math.ceil(e.length/4*1.2)}function _c(e){if(e.role===`user`)return gc(e.content);if(e.role===`assistant`){let t=gc(e.content),n=e.thinking?.trim();n&&(t+=gc(n)),e.errorMessage&&(t+=gc(e.errorMessage));for(let n of e.toolCalls??[])t+=gc(n.name)+gc(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(`
20
+ `):e.content;return gc(e.toolName)+gc(t)}function Y(e){return e.reduce((e,t)=>e+_c(t),0)}function vc(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 yc(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 bc=[`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.`],xc={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function Sc(e){let t=e.baseUrl.includes(`deepseek.com`);if(!(!e.thinking&&!t))return{replayThinking:!0,thinkingSignature:`reasoning_content`}}function Cc(e,t,n){return e.map(e=>wc(e,t,n))}function wc(e,t,n){let r=new Date(e.timestamp).getTime();if(Tc(e))return{role:`user`,content:e.content,timestamp:r};if(Ec(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:xc,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 Tc(e){return e.role===`user`}function Ec(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:`,...bc];return t&&(n.push(`Preview:`),n.push(t)),n.join(`
21
+ `)}const Oc=[`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(`
22
+ `);async function kc(e){let{entries:t,llm:n,previousSummary:r,instructions:i,contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}=e,l=jc(t,r,i,a),u=Mc(a),d,f=lo({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:Oc,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 Ac(500*e)}throw d}function Ac(e){return new Promise(t=>setTimeout(t,e))}function jc(e,t,n,r){let i=[];n?.trim()&&i.push(`[Extra instructions]\n${n.trim()}\n`),t?.trim()?(i.push(`[Prior summary]\n${Ic(t.trim(),Nc(r))}\n`),i.push(`[Conversation to incorporate]`)):i.push(`[Conversation to summarise]`);let a=Pc(e,t,n,r),o=Fc(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: ${Ic(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(`, `)}]`:``} ${Ic(n.content,Math.min(a,o))}`.trimEnd();else if(n.role===`tool_result`){let e=n.isError?`error`:`ok`,t=n.toolName===`skill_load`?Lc(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(`
23
+ `):n.content;r=`Tool(${n.toolName})[${e}]: ${Ic(t,Math.min(a,o))}`}i.push(r),o-=r.length}return i.join(`
24
+ `)}function Mc(e){return!e||e<=0?2048:Math.max(512,Math.min(2048,Math.floor(e*.1)))}function Nc(e){return!e||e<=0?4e3:Math.max(500,Math.min(4e3,Math.floor(e*.2*4)))}function Pc(e,t,n,r){let i=Fc(t,n,r);if(!r||r<=0)return 2e3;let a=Mc(r)+1e3,o=Math.max(500,Math.floor(r*.6)-a),s=Oc.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 Fc(e,t,n){if(!n||n<=0)return 1/0;let r=Mc(n)+1e3,i=Math.max(250,Math.floor(n*.6)-r),a=Oc.length+(e?.length??0)+(t?.length??0)+1e3;return Math.max(500,i*4-a)}function Ic(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated for summarization; original chars: ${e.length}]`}function Lc(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(`
25
+ `)}function Rc(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=zc(t);if(e.name||e.path)return e}return{}}function zc(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 Bc(e,t){let n=Math.floor(t*.35),r=0,i=e.length;for(let t=e.length-1;t>=0;t--){let a=_c(e[t]);if(r+a>n)break;r+=a,i=t}return{toKeep:e.slice(i),toSummarise:e.slice(0,i)}}async function Vc(e){return Uc((await lo({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:Kc,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 Hc(e){return Wc((await lo({apiFormat:e.llm.apiFormat,baseUrl:e.llm.baseUrl,apiKey:e.llm.apiKey,defaultModel:e.llm.model}).chat({system:qc,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 Uc(e){let t=Gc(e);if(t.version!==1||!Array.isArray(t.selectedSegmentIds))throw Error(`Topic segment selection decision has invalid schema.`);return{version:1,selectedSegmentIds:t.selectedSegmentIds.filter(e=>typeof e==`string`),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function Wc(e){let t=Gc(e);if(t.version!==1||!Array.isArray(t.selectedTurns))throw Error(`Topic turn selection decision has invalid schema.`);return{version:1,selectedTurns:t.selectedTurns.filter(e=>!!(e&&typeof e==`object`&&typeof e.turnId==`string`&&typeof e.summary==`string`)).map(e=>({turnId:e.turnId,summary:e.summary.trim(),topicLabel:typeof e.topicLabel==`string`?e.topicLabel.trim():void 0,keywords:Array.isArray(e.keywords)?e.keywords.filter(e=>typeof e==`string`&&e.trim().length>0):void 0})),reason:typeof t.reason==`string`?t.reason:``,confidence:t.confidence===`high`||t.confidence===`medium`||t.confidence===`low`?t.confidence:`low`}}function Gc(e){let t=e.trim();if(!t)throw Error(`Topic segmentation model returned empty content.`);let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i),r=n?n[1].trim():t;return JSON.parse(r)}[`You maintain SeCom-style conversation segments for an IM assistant.`,`Return ONLY strict JSON with this shape:`,`{"version":1,"action":"merge|split","reason":"...","topicLabel":"optional","summary":"...","compressedSummary":"...","keywords":["..."]}`,`Task: compare the active segment with the new user turn.`,`Use action=merge only when the new turn continues the same topic, task, artifact, bug, document, or refinement thread.`,`Use action=split when the new turn starts a different topic.`,`Always provide summary, compressedSummary, and concise keywords for the resulting segment after your decision.`,`Do not answer the user.`].join(`
26
+ `);const Kc=[`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(`
27
+ `),qc=[`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(`
28
+ `);async function Jc(e){let t=$c(e);if(t)try{let e=await W.readFile(t,`utf8`),n=JSON.parse(e);if(!Array.isArray(n))return;let r=n.filter(hl);return r.length===n.length?r:void 0}catch(e){e.code;return}}async function Yc(e){let t=$c(e);t&&(await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,`${JSON.stringify(e.segments,null,2)}\n`,`utf8`))}function Xc(e){let t=el(e);if(t.length===0)return[];let n=[],r=[];for(let e of t){let t=r[r.length-1];if(!t||tl(t,e)){r.push(e);continue}n.push(rl(r,n.length+1,!1)),r=[e]}return r.length>0&&n.push(rl(r,n.length+1,!0)),n}function Zc(e,t){let n=el(t);if(n.length===0)return[];if(!e||e.length===0)return Xc(t);let r=e.flatMap(e=>e.turnIds),i=n.slice(0,r.length).map(e=>e.turnId);if(r.join(`|`)!==i.join(`|`))return Xc(t);if(r.length===n.length)return e;let a=e.map(e=>({...e,turnIds:[...e.turnIds],toolNames:[...e.toolNames],keywords:[...e.keywords]})),o=n.slice(r.length);for(let e of o){let t=a[a.length-1];if(t&&nl(t,e)){a[a.length-1]=cl(t,e);continue}t&&(t.status=`closed`),a.push(rl([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 Qc(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 $c(e){if(!(!e.dataDir||!e.sessionId))return G.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.json`)}function el(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 tl(e,t){return dl(ul(e.user,e.assistant),ul(t.user,t.assistant))>0}function nl(e,t){return dl(ul(e.summary,e.assistantSummary,e.topicLabel,e.keywords.join(` `)),ul(t.user,t.assistant,t.toolNames.join(` `)))>0}function rl(e,t,n){return il(e,t,n)}function il(e,t,n,r){let i=e[0],a=e[e.length-1],o=[...new Set(e.flatMap(e=>e.toolNames))].sort(),s=al(e,o),c=ml(r?.summary||s),l=ll(r?.keywords,c,o),u=ml(r?.compressedSummary||sl(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(`
27
29
  `),assistantSummary:e.map(e=>e.assistant).filter(Boolean).join(`
28
- `)||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 xc(e,t){return Sc(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 Sc(e,t,n){let r=kc(e,220),i=t?kc(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return Ac(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function Cc(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return Ac(`Relevant prior segment: ${kc(e,280)}${n}`)}function wc(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(`
29
- `)||void 0,o=Sc(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:Ac(n?.summary||o),compressedSummary:Ac(n?.compressedSummary||Cc(n?.summary||o,r)),keywords:Tc(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function Tc(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:Oc(t,n)}function Ec(...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 Dc(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Oc(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 Ec(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 kc(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Ac(e){return e.replace(/\s+/g,` `).trim()}function jc(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 Mc(e){let t=Ic(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:Lc(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 Nc(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function Pc(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:Fc(i.compressedSummary),timestamp:e.timestamp})}return r}function Fc(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function Ic(...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 Lc(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=Ic(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 Rc=`Xenova/bge-small-zh-v1.5`;let zc,Bc;const Vc=new Map;async function Hc(e,t){if(e.length===0)return J.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=qc(t),i=r.path;J.info(`topic segmentation embedding started`,{provider:`transformers`,model:Rc,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await Gc({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=Vc.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Vc.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return J.info(`topic segmentation embedding completed`,{provider:`transformers`,model:Rc,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 J.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:Rc,textCount:e.length,modelDir:i,modelDirSource:r.source,durationMs:Date.now()-n,error:t instanceof Error?t.message:String(t)}),t}}async function Uc(e,t){let[n]=await Hc([e],t);return n??[]}function Wc(){return Rc}async function Gc(e){let t=qc(e).path;return(!zc||Bc!==t)&&(Bc=t,zc=Kc(t)),zc}async function Kc(e){let t=Date.now();J.info(`topic segmentation embedding extractor load started`,{model:Rc,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`,Rc,{dtype:`q8`});return J.info(`topic segmentation embedding extractor load completed`,{model:Rc,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw J.warn(`topic segmentation embedding extractor load failed`,{model:Rc,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function qc(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=W.dirname(yt(import.meta.url)),i=W.resolve(r,`../../../../../model`);if(G.existsSync(i))return{path:i,source:`repo_candidate`};let a=W.resolve(process.cwd(),`model`);return G.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const Jc=`topic_segments_vec`,Yc=`topic_segments_meta`,Xc=`topic_segment_embedding_cache`;async function Zc(e){let t=Date.now(),n=$c(e);if(!n){J.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}J.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await U.mkdir(W.dirname(n),{recursive:!0});let r=me(n,{allowExtension:!0});try{let i=await tl(r);J.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 ${Yc}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=Wc(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=ue(el(e));return o.get(e.segmentId)!==t});J.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 Hc(l.map(e=>el(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=el(t),n=ue(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:ol(r,t.segmentId);il(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(al(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(rl(r,i,o.length),r.prepare(`DELETE FROM ${Jc} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${Jc} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,fl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${Jc} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${Yc} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${Xc} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${Jc} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),J.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 J.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 Qc(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return J.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=$c(e);if(!n)return J.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 U.access(n)}catch{return J.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}J.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await ll(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return J.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=me(n,{allowExtension:!0});try{let a=await tl(i),o=Wc(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?sl(i,o,r,e.limit):cl(i,o,r,e.limit);return J.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 J.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 $c(e){if(!(!e.dataDir||!e.sessionId))return W.join(r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope}),`topic-segments.sqlite`)}function el(e){return[e.topicLabel?`Topic: ${e.topicLabel}`:``,e.summary,e.compressedSummary,e.keywords.join(` `),e.toolNames.join(` `)].filter(Boolean).join(`
30
- `)}async function tl(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${Yc} (\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 ${Xc} (\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_${Yc}_hash ON ${Yc}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Xc}_hash ON ${Xc}(content_hash)`),{vectorAvailable:(await ce({db:e})).ok,vectorDims:nl(e)}}function nl(e){let t=e.prepare(`SELECT dims FROM ${Xc} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function rl(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${Jc}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${Jc} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function il(e,t){e.prepare(`INSERT INTO ${Yc} (\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 al(e,t){e.prepare(`INSERT INTO ${Xc} (\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 ${Xc} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function sl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${Jc} v\n JOIN ${Yc} 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(fl(n),t,fl(n),r)}function cl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${Xc} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:dl(n,ul(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function ll(e,t){try{return await Uc(e,t)}catch(e){return J.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function ul(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function dl(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 fl(e){return Buffer.from(new Float32Array(e).buffer)}const pl=8e3,ml=new Map;function hl(e){return{enabled:e?.enabled!==!1,embeddingModelDir:jl(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 gl(e){let t=Sl(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(El(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?Pc({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function _l(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=Ml(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:Pl(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 vl(e){let t=hl(e.config),n=()=>Ll({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){J.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){J.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){J.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=Sl(e.entries),i=Y(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){J.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>Cl(e,t)),o=e.llm.flashModel||e.llm.model,s=await yl({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();J.info(`topic segmentation classify started`,Ll({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=Tl({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=gl({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=wl({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 Ol(e,g),J.info(`topic segmentation classify succeeded`,{...Ll({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 yl(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await bl({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 Qc({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=Mc({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=zl(l,e.config.maxShortlistSegments),d=xl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:pl});if(d&&Gl({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await Jl({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=Nc({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await Bl({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:pl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await dc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),Yl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=Wl(a,l.selectedCandidates),d=_l({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 bl(e){J.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await uc(e);if(!t){let t=fc(e.entries);if(t.length===0){J.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await dc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),Yl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),J.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}J.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=pc(t,e.entries);return n.length>0&&(await dc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),Yl({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),J.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function xl(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 Sl(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 Cl(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}Il(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:kl(e.user,t.maxCandidateUserChars),assistant:n?kl((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function wl(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:kl(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 Tl(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=Ml(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:Pl(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 El(e,t){let n=t?.assistant??Dl(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:Al(t?.user??e.user,50),assistantPreview:n?Al(n,50):void 0}}function Dl(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 Ol(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await U.mkdir(n,{recursive:!0}),await U.appendFile(W.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function kl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function Al(e,t){return[...e].slice(0,t).join(``)}function jl(e){return e?.trim()||void 0}function Ml(...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 Nl(e){return[...Ml(e)].slice(0,8)}function Pl(e,t,n,r){let i=Fl(e,Ml(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function Fl(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function Il(e){return e.role===`tool_result`}function Ll(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Rl(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 Rl(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function zl(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 Bl(e){if(!Vl(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=Hl(Ul(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=xl({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await ic({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??Nl(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?mc(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Vl(e){let t=e.selectedSegments.filter(e=>!e.forced);return Kl(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:ql(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Hl(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 Ul(e,t,n){let r=Math.max(n.length,1),i=Ml(t);return e.map(e=>({candidate:e,score:Pl(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function Wl(...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 Gl(e){if(e.retrieved.length<2||!Kl(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 Kl(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function ql(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 Jl(e){try{let t=await rc({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 Yl(e){let t=Xl(e);if(!t||ml.has(t)){J.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}J.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=Zc(e).catch(t=>{J.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(()=>{ml.delete(t)});ml.set(t,n)}function Xl(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(`
31
- `);const Zl=[`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 Ql(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 ru(t);for(let e of p.readStates)n.set($l(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 U.mkdir(W.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=$l(e,t,r),a=n.get(i);if(!a)return null;let o=await tu(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:nu(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await tu(e.path)??Date.now()};return n.set($l(e.path,e.offset,e.limit),r),await m(),r},async invalidatePath(e){let t=!1;for(let[r,i]of n.entries())eu(i.path)===eu(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=W.join(o,c);await U.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await L(l,t.content,u);let p=W.relative(e.dataDir,l).split(W.sep).join(`/`),h=su(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 cu(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 $l(e,t,n){return`${eu(e)}::${t??``}::${n??``}`}function eu(e){return W.normalize(e)}async function tu(e){try{return(await U.stat(e)).mtimeMs}catch{return null}}function nu(e){return et(`sha1`).update(e).digest(`hex`)}async function ru(e){try{let t=await o(e);if(t===null)return iu();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?iu():{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:au(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 iu()}}function iu(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function au(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?`
32
- ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...Zl,`Preview:`,e.preview+t].join(`
33
- `)}function su(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
34
- `),r=n>t*.5?n:t;return e.slice(0,r)}async function cu(e,t,n,r){let i=l(e,t,r);await U.mkdir(W.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await L(i,JSON.stringify(n,null,2),a)}const lu=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function uu(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=Su(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=Fs(Ps(S,a)),T=[],E=(await vl({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=>{J.warn(`topic segmentation failed; falling back to repaired history`,{sessionId:m,channel:_,isSubagent:!!v,error:e instanceof Error?e.message:String(e)})}))?.entries??w;if(E=await fu({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await pu({entries:E,contextStore:f,compactionEvents:T}),E=await mu({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g}),f&&(b=await du({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:zs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:Y(E),compacted:!1},compactionEvents:T};let D=f?.getSnapshot(),O=Math.max(1e3,Math.floor(r*.7)),k=Cu({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:D?.compaction.modelUsage}).projectedInputTokens>=O,A=D?.compaction.consecutiveAutocompactFailures??0;if(!k||A>=3)return{messages:zs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:Y(E),compacted:!1},compactionEvents:T};let{toKeep:j,toSummarise:M}=nc(E,r);if(M.length===0)return{messages:zs(E,n,y),priorSummary:b,compactionEntry:void 0,stats:{originalCount:C,keptCount:E.length,estimatedTokens:Y(E),compacted:!1},compactionEvents:T};let N=new Date().toISOString();try{let e=D?.compaction.sessionMemory,t=e?.summary?.trim()?e.summary.trim():await Gs({entries:M,llm:i,previousSummary:b,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d}),a={role:`compaction`,content:t,keptCount:j.length,droppedCount:M.length,timestamp:N};return await f?.recordAutocompactResult({layer:`L6`,failed:!1,timestamp:N}),T.push({type:`compaction`,reason:e?.summary?.trim()?`Autocompact replaced ${M.length} entries with session memory`:`Autocompact summarised ${M.length} entries`,layer:`L6`,strategy:e?.summary?.trim()?`session_memory`:`full_summary`,estimatedTokensFreed:Math.max(0,Y(M)),affectedEntries:M.length,snapshotVersion:2}),{messages:zs(Fs(j),n,y),priorSummary:t,compactionEntry:a,stats:{originalCount:C,keptCount:j.length,estimatedTokens:Y(j),compacted:!0},compactionEvents:T}}catch{return await f?.recordAutocompactResult({layer:`L6`,failed:!0,timestamp:N}),{messages:zs(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 du(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&&xu(t)>=3;if(!d&&!f)return n??u?.summary;let p=await Gs({entries:t,llm:r,previousSummary:n??u?.summary,instructions:[`Produce a durable session memory for future compaction and resume.`,`If skill_load results are present, do not restate or reconstruct SKILL.md instructions.`,`Record only that the skill was loaded and that it must be reloaded with skill_load if its full content is not visible.`].join(` `),contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}),m={version:1,summary:p,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:l,trigger:d?`threshold`:`autocompact`};return await i.setSessionMemory(m),p}async function fu(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(gu).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(!gu(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=_u(n)?vu(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
35
- `);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}),Fs(l.reverse())}async function pu(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(!gu(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=_u(r)?vu(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(`
36
- `);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}),fu({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function mu(e){let{entries:t,contextStore:n,compactionEvents:r,dataDir:i,sessionId:a,sessionStoreName:o,sessionPathScope:s}=e,c={storeName:o,...s},l=t.reduce((e,t,n)=>(t.role===`user`&&e.push(n),e),[]);if(l.length<=2)return t;let u=l[l.length-2]??t.length,d=[],f=0,p=0,m=0;for(;f<t.length;){if(f>=u||t[f]?.role===`user`){d.push(t[f]),f+=1;continue}let e=f;for(;f<u&&t[f]?.role!==`user`;)f+=1;let r=t.slice(e,f),o=r.filter(gu).filter(e=>lu.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=hu(r,o),h=new Date().toISOString(),g={role:`assistant`,content:l,timestamp:h};d.push(g),p+=r.length,m+=Math.max(0,Math.floor(Y(r)-Y([g])));let _={id:nt(),layer:`L5`,startEntryIndex:e,endEntryIndex:f-1,toolNames:[...new Set(o.map(e=>e.toolName))],summary:l,sourceCount:r.length,estimatedTokensFreed:m,createdAt:h};await n?.recordCollapse(_),i&&a&&await wu(i,a,_,c)}return p>0&&r.push({type:`compaction`,reason:`Collapsed ${p} historical tool activity entries`,layer:`L5`,strategy:`context_collapse`,estimatedTokensFreed:m,affectedEntries:p,snapshotVersion:2}),d}function hu(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(`
30
+ `)||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 al(e,t){return ol(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 ol(e,t,n){let r=pl(e,220),i=t?pl(t,220):void 0,a=n.length>0?` Tools: ${n.join(`, `)}.`:``;return ml(`User intents: ${r}.${i?` Outcomes: ${i}.`:``}${a}`)}function sl(e,t){let n=t.length>0?` Tools=${t.join(`,`)}.`:``;return ml(`Relevant prior segment: ${pl(e,280)}${n}`)}function cl(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(`
31
+ `)||void 0,o=ol(i,a,r);return{...e,turnIds:[...e.turnIds,t.turnId],endTurnId:t.turnId,endIndex:t.endIndex,userSummary:i,assistantSummary:a,summary:ml(n?.summary||o),compressedSummary:ml(n?.compressedSummary||sl(n?.summary||o,r)),keywords:ll(n?.keywords,n?.summary||o,r),toolNames:r,topicLabel:n?.topicLabel??e.topicLabel,turnMemories:e.turnMemories,status:`active`,updatedAt:t.timestamp??e.updatedAt}}function ll(e,t,n){let r=e?.map(e=>e.trim().toLowerCase()).filter(Boolean).slice(0,8);return r&&r.length>0?[...new Set(r)]:fl(t,n)}function ul(...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 dl(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function fl(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 ul(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 pl(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function ml(e){return e.replace(/\s+/g,` `).trim()}function hl(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 gl(e){let t=bl(e.currentUserMessage);return e.segments.map((n,r)=>({segment:n,forced:n.turnIds.some(t=>e.recentProtectedTurnIds.includes(t)),score:xl(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 _l(e){let t=new Set(e.retrievedSegments.flatMap(e=>e.segment.turnIds));return e.candidates.filter(e=>t.has(e.turnId))}function vl(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:yl(i.compressedSummary),timestamp:e.timestamp})}return r}function yl(e){let t=e.trim();return t?t.startsWith(`Relevant prior segment:`)?t:`Relevant prior segment: ${t}`:`Relevant prior segment:`}function bl(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function xl(e,t,n,r,i){let a=(t.turnMemories??[]).flatMap(e=>[e.summary,e.topicLabel,e.keywords.join(` `)]).join(` `),o=bl(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 Sl=`Xenova/bge-small-zh-v1.5`;let Cl,wl;const Tl=new Map;async function El(e,t){if(e.length===0)return J.info(`topic segmentation embedding skipped`,{reason:`empty_batch`,embeddingModelDir:t?.embeddingModelDir}),[];let n=Date.now(),r=jl(t),i=r.path;J.info(`topic segmentation embedding started`,{provider:`transformers`,model:Sl,textCount:e.length,modelDir:i,modelDirSource:r.source,configuredModelDir:t?.embeddingModelDir});try{let t=await kl({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=Tl.get(r);if(c){a.push(c),o+=1;continue}let l=await t(e,{pooling:`mean`,normalize:!0}),u=Array.from(l.data??[]);Tl.set(r,u),a.push(u)}let c=a.find(e=>e.length>0);return J.info(`topic segmentation embedding completed`,{provider:`transformers`,model:Sl,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 J.warn(`topic segmentation embedding failed`,{provider:`transformers`,model:Sl,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 El([e],t);return n??[]}function Ol(){return Sl}async function kl(e){let t=jl(e).path;return(!Cl||wl!==t)&&(wl=t,Cl=Al(t)),Cl}async function Al(e){let t=Date.now();J.info(`topic segmentation embedding extractor load started`,{model:Sl,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`,Sl,{dtype:`q8`});return J.info(`topic segmentation embedding extractor load completed`,{model:Sl,modelDir:e,durationMs:Date.now()-t}),i}catch(n){throw J.warn(`topic segmentation embedding extractor load failed`,{model:Sl,modelDir:e,durationMs:Date.now()-t,error:n instanceof Error?n.message:String(n)}),n}}function jl(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=G.dirname(xt(import.meta.url)),i=G.resolve(r,`../../../../../model`);if(K.existsSync(i))return{path:i,source:`repo_candidate`};let a=G.resolve(process.cwd(),`model`);return K.existsSync(a)?{path:a,source:`cwd`}:{path:i,source:`repo_candidate_missing`}}const Ml=`topic_segments_vec`,Nl=`topic_segments_meta`,Pl=`topic_segment_embedding_cache`;async function Fl(e){let t=Date.now(),n=Ll(e);if(!n){J.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}J.info(`topic segment vector store sync started`,{sessionId:e.sessionId,dbPath:n,segmentCount:e.segments.length,embeddingModelDir:e.embeddingModelDir}),await W.mkdir(G.dirname(n),{recursive:!0});let r=ge(n,{allowExtension:!0});try{let i=await zl(r);J.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 ${Nl}`).all(),o=new Map(a.map(e=>[e.segment_id,e.content_hash])),s=Ol(),c=new Set(e.segments.map(e=>e.segmentId)),l=e.segments.filter(e=>{let t=de(Rl(e));return o.get(e.segmentId)!==t});J.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 El(l.map(e=>Rl(e)),{embeddingModelDir:e.embeddingModelDir}):[];r.exec(`BEGIN`);try{for(let t of e.segments){let e=Rl(t),n=de(e),a=l.findIndex(e=>e.segmentId===t.segmentId),o=a>=0?u[a]??[]:Wl(r,t.segmentId);Hl(r,{segment:t,contentText:e,contentHash:n,embeddingModel:s}),o.length>0?(Ul(r,{segmentId:t.segmentId,contentHash:n,embeddingModel:s,embedding:o}),i.vectorAvailable&&(Vl(r,i,o.length),r.prepare(`DELETE FROM ${Ml} WHERE segment_id = ?`).run(t.segmentId),r.prepare(`INSERT INTO ${Ml} (segment_id, embedding) VALUES (?, ?)`).run(t.segmentId,Xl(o)))):i.vectorAvailable&&r.prepare(`DELETE FROM ${Ml} WHERE segment_id = ?`).run(t.segmentId)}for(let e of a)c.has(e.segment_id)||(r.prepare(`DELETE FROM ${Nl} WHERE segment_id = ?`).run(e.segment_id),r.prepare(`DELETE FROM ${Pl} WHERE segment_id = ?`).run(e.segment_id),i.vectorAvailable&&r.prepare(`DELETE FROM ${Ml} WHERE segment_id = ?`).run(e.segment_id));r.exec(`COMMIT`),J.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 J.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 Il(e){let t=Date.now();if(!e.query.trim()||e.limit<=0)return J.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=Ll(e);if(!n)return J.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 W.access(n)}catch{return J.info(`topic segment vector search skipped`,{sessionId:e.sessionId,reason:`missing_db`,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir}),new Map}J.info(`topic segment vector search started`,{sessionId:e.sessionId,dbPath:n,limit:e.limit,embeddingModelDir:e.embeddingModelDir});let r=await ql(e.query,{sessionId:e.sessionId,dbPath:n,embeddingModelDir:e.embeddingModelDir});if(r.length===0)return J.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 zl(i),o=Ol(),s=a.vectorAvailable&&a.vectorDims===r.length?`sqlite_vec`:`cache_cosine`,c=a.vectorAvailable&&a.vectorDims===r.length?Gl(i,o,r,e.limit):Kl(i,o,r,e.limit);return J.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 J.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 Ll(e){if(!(!e.dataDir||!e.sessionId))return G.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(`
32
+ `)}async function zl(e){return e.exec(`CREATE TABLE IF NOT EXISTS ${Nl} (\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 ${Pl} (\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_${Nl}_hash ON ${Nl}(content_hash)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_${Pl}_hash ON ${Pl}(content_hash)`),{vectorAvailable:(await me({db:e})).ok,vectorDims:Bl(e)}}function Bl(e){let t=e.prepare(`SELECT dims FROM ${Pl} LIMIT 1`).get();return typeof t?.dims==`number`&&t.dims>0?t.dims:void 0}function Vl(e,t,n){t.vectorDims!==n&&(t.vectorDims&&t.vectorDims!==n&&e.exec(`DROP TABLE IF EXISTS ${Ml}`),e.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${Ml} USING vec0(\n segment_id TEXT PRIMARY KEY,\n embedding FLOAT[${n}]\n)`),t.vectorDims=n)}function Hl(e,t){e.prepare(`INSERT INTO ${Nl} (\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 Ul(e,t){e.prepare(`INSERT INTO ${Pl} (\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 Wl(e,t){let n=e.prepare(`SELECT embedding FROM ${Pl} WHERE segment_id = ?`).get(t);if(!n?.embedding)return[];try{let e=JSON.parse(n.embedding);return Array.isArray(e)?e:[]}catch{return[]}}function Gl(e,t,n,r){return e.prepare(`SELECT v.segment_id, 1 - vec_distance_cosine(v.embedding, ?) AS score\n FROM ${Ml} v\n JOIN ${Nl} m ON m.segment_id = v.segment_id\n WHERE m.embedding_model = ?\n ORDER BY vec_distance_cosine(v.embedding, ?) ASC\n LIMIT ?`).all(Xl(n),t,Xl(n),r)}function Kl(e,t,n,r){return e.prepare(`SELECT segment_id, embedding FROM ${Pl} WHERE embedding_model = ?`).all(t).map(e=>({segment_id:e.segment_id,score:Yl(n,Jl(e.embedding))})).sort((e,t)=>(t.score??0)-(e.score??0)).slice(0,r)}async function ql(e,t){try{return await Dl(e,t)}catch(e){return J.warn(`topic segment query embedding failed`,{sessionId:t?.sessionId,dbPath:t?.dbPath,embeddingModelDir:t?.embeddingModelDir,error:e instanceof Error?e.message:String(e)}),[]}}function Jl(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Yl(e,t){if(e.length===0||t.length===0||e.length!==t.length)return 0;let n=0,r=0,i=0;for(let a=0;a<e.length;a+=1){let o=e[a]??0,s=t[a]??0;n+=o*s,r+=o*o,i+=s*s}return r<=0||i<=0?0:n/(Math.sqrt(r)*Math.sqrt(i))}function Xl(e){return Buffer.from(new Float32Array(e).buffer)}const Zl=8e3,Ql=new Map;function $l(e){return{enabled:e?.enabled!==!1,embeddingModelDir:hu(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 eu(e){let t=ou(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(uu(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?vl({selectedTurnIds:[...r],segments:e.segmentRecords,recentProtectedTurnIds:a,timestamp:new Date().toISOString()}):[],...c],recentTurnIds:a,selectedRanges:s,droppedTurnIds:l,droppedTurns:u}}function tu(e){if(e.candidates.length<=e.maxShortlist)return e.candidates;let t=gu(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:vu(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 nu(e){let t=$l(e.config),n=()=>xu({params:e,config:t,model:e.llm.flashModel||e.llm.model});if(!t.enabled){J.info(`topic segmentation skipped`,{...n(),reason:`disabled`});return}if(e.isSubagent){J.info(`topic segmentation skipped`,{...n(),reason:`subagent`});return}if(e.channel===`TASK`||e.channel===`CRON`){J.info(`topic segmentation skipped`,{...n(),reason:`channel`});return}if(!e.pendingUserMessage?.trim())return;let r=ou(e.entries),i=Y(e.entries);if(r.length<t.minUserTurns||i<t.minEstimatedTokens){J.info(`topic segmentation skipped`,{...n(),reason:`below_threshold`,userTurnCount:r.length,tokenEstimateBefore:i});return}let a=r.slice(-t.maxCandidates).map(e=>su(e,t)),o=e.llm.flashModel||e.llm.model,s=await ru({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();J.info(`topic segmentation classify started`,xu({params:e,config:t,model:o,candidates:a,shortlistedCandidates:s.candidates,tokenEstimateBefore:i,extraPromptChars:0}));let f=lu({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=eu({entries:e.entries,candidates:a,decision:f,recentProtectedTurnCount:t.recentProtectedTurnCount,segmentRecords:c}),g=cu({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 fu(e,g),J.info(`topic segmentation classify succeeded`,{...xu({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 ru(e){if(!e.pendingUserMessage?.trim())return{candidates:e.candidates,selectedSegmentIds:[],supplementalTurnIds:[],segmentRecords:void 0};let t=await iu({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 Il({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=gl({currentUserMessage:e.pendingUserMessage,segments:t,recentProtectedTurnIds:n,maxSegments:Math.max(e.config.maxShortlistSegments,e.config.maxShortlistSegments*2),vectorScores:o});c=l;let u=Cu(l,e.config.maxShortlistSegments),d=au({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:r,budgetMs:Zl});if(d&&ku({currentUserMessage:e.pendingUserMessage,retrieved:l,selected:u,recentProtectedTurnIds:n})){let t=await Mu({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=_l({retrievedSegments:u.length>0?u:l,candidates:e.candidates})}let l=await wu({allCandidates:e.candidates,segmentFilteredCandidates:a,currentUserMessage:e.pendingUserMessage,recentProtectedTurnIds:n,config:e.config,llm:e.llm,budgetStartedAtMs:r,budgetMs:Zl,segmentRecords:o,selectedSegments:s,retrievedSegments:c,signal:e.signal});l.updatedSegments&&(o=l.updatedSegments,e.dataDir&&e.sessionId&&(await Yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:l.updatedSegments}),Nu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:l.updatedSegments})));let u=Ou(a,l.selectedCandidates),d=tu({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 iu(e){J.info(`topic segment sidecar load started`,{sessionId:e.sessionId,hasDataDir:!!e.dataDir,embeddingModelDir:e.embeddingModelDir,entryCount:e.entries.length});let t=await Jc(e);if(!t){let t=Xc(e.entries);if(t.length===0){J.info(`topic segment sidecar rebuild skipped`,{sessionId:e.sessionId,reason:`empty_rebuild`,entryCount:e.entries.length});return}return await Yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:t}),Nu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:t}),J.info(`topic segment sidecar rebuilt`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir}),t}J.info(`topic segment sidecar loaded`,{sessionId:e.sessionId,segmentCount:t.length,embeddingModelDir:e.embeddingModelDir});let n=Zc(t,e.entries);return n.length>0&&(await Yc({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,segments:n}),Nu({dataDir:e.dataDir,sessionId:e.sessionId,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope,embeddingModelDir:e.embeddingModelDir,segments:n}),J.info(`topic segment sidecar updated`,{sessionId:e.sessionId,previousSegmentCount:t.length,segmentCount:n.length,embeddingModelDir:e.embeddingModelDir})),n}function au(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 ou(e){let t=[],n,r=()=>{n&&t.push(n),n=void 0};for(let[i,a]of e.entries()){if(a.role===`user`){r(),n={turnId:`turn-${t.length+1}`,startIndex:i,endIndex:i,entries:[a],user:a.content,timestamp:a.timestamp};continue}n&&(n.entries.push(a),n.endIndex=i)}return r(),t}function su(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}bu(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:pu(e.user,t.maxCandidateUserChars),assistant:n?pu((n.content||n.errorMessage||``).trim(),t.maxCandidateAssistantChars):void 0,toolNames:[...r].sort(),hasErrors:i,timestamp:e.timestamp}}function cu(e){return{version:1,createdAt:e.timestamp,sessionId:e.sessionId??`unknown`,durationMs:e.durationMs,model:{provider:`openai-compatible`,model:e.model,profile:`fast`},currentUserMessagePreview:pu(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 lu(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=gu(e.currentUserMessage),r=e.shortlistedCandidates.map((n,r)=>({candidate:n,score:vu(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 uu(e,t){let n=t?.assistant??du(e);return{turnId:e.turnId,startIndex:e.startIndex,endIndex:e.endIndex,userPreview:mu(t?.user??e.user,50),assistantPreview:n?mu(n,50):void 0}}function du(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 fu(e,t){if(!(!e.dataDir||!e.sessionId))try{let n=r(e.dataDir,e.sessionId,{storeName:e.sessionStoreName,...e.sessionPathScope});await W.mkdir(n,{recursive:!0}),await W.appendFile(G.join(n,`topic-segmentation-log.jsonl`),`${JSON.stringify(t)}\n`,`utf8`)}catch{}}function pu(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function mu(e,t){return[...e].slice(0,t).join(``)}function hu(e){return e?.trim()||void 0}function gu(...e){let t=new Set;for(let n of e)if(n)for(let e of n.toLowerCase().match(/[\p{Script=Han}]+|[\p{Letter}\p{Number}_-]+/gu)??[]){let n=e.trim();n.length<2&&!/[\p{Script=Han}]/u.test(n)||t.add(n)}return t}function _u(e){return[...gu(e)].slice(0,8)}function vu(e,t,n,r){let i=yu(e,gu(t.user,t.assistant,t.toolNames.join(` `))),a=(n+1)/Math.max(r,1);return i*10+a}function yu(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);return n}function bu(e){return e.role===`tool_result`}function xu(e){return{sessionId:e.params.sessionId,channel:e.params.channel,isSubagent:!!e.params.isSubagent,model:e.model,baseUrl:Su(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 Su(e){try{let t=new URL(e);return`${t.protocol}//${t.host}${t.pathname.replace(/\/$/,``)}`}catch{return e.replace(/[?#].*$/,``)}}function Cu(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 wu(e){if(!Tu(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=Eu(Du(r,e.currentUserMessage,e.allCandidates),e.segmentRecords).slice(0,8);if(i.length===0)return{selectedCandidates:[],selectedTurnIds:[]};let a=au({requestTimeoutMs:e.llm.timeoutMs,budgetStartedAtMs:e.budgetStartedAtMs,budgetMs:e.budgetMs});if(!a)return{selectedCandidates:[],selectedTurnIds:[]};try{let t=await Hc({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??_u(`${e.topicLabel??``} ${e.summary}`)).slice(0,8),updatedAt:new Date().toISOString()}));return{selectedCandidates:o,selectedTurnIds:n,updatedSegments:e.segmentRecords?Qc(e.segmentRecords,s):void 0}}catch{return{selectedCandidates:[],selectedTurnIds:[]}}}function Tu(e){let t=e.selectedSegments.filter(e=>!e.forced);return Au(e.currentUserMessage)?t.length<2&&e.retrievedSegments.filter(e=>!e.forced).length>=2:ju(e.currentUserMessage)?t.length<1&&e.retrievedSegments.filter(e=>!e.forced).length>=1:!1}function Eu(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=gu(t);return e.map(e=>({candidate:e,score:vu(i,e,e.startIndex,r)})).sort((e,t)=>t.score-e.score||e.candidate.startIndex-t.candidate.startIndex).map(e=>e.candidate)}function Ou(...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 ku(e){if(e.retrieved.length<2||!Au(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 Au(e){let t=e.toLowerCase();return/(结合|并到|一并|同时|前面.*后面|之前.*后面|连同|一起)/u.test(t)?!0:/\b(and|along with|combine|combined|together with)\b/i.test(t)}function ju(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 Mu(e){try{let t=await Vc({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 Nu(e){let t=Pu(e);if(!t||Ql.has(t)){J.info(`topic segment vector sync skipped`,{sessionId:e.sessionId,reason:t?`job_already_running`:`missing_job_key`,hasDataDir:!!e.dataDir});return}J.info(`topic segment vector sync scheduled`,{sessionId:e.sessionId,embeddingModelDir:e.embeddingModelDir,segmentCount:e.segments.length});let n=Fl(e).catch(t=>{J.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(()=>{Ql.delete(t)});Ql.set(t,n)}function Pu(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(`
33
+ `);const Fu=[`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 Iu(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 Vu(t);for(let e of p.readStates)n.set(Lu(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 W.mkdir(G.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=Lu(e,t,r),a=n.get(i);if(!a)return null;let o=await zu(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:Bu(e.content),lineCount:e.lineCount,capturedAt:t,lastModifiedMs:await zu(e.path)??Date.now()};return n.set(Lu(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=G.join(o,c);await W.mkdir(o,{recursive:!0});let u=e.encryptSessions??!1;await L(l,t.content,u);let p=G.relative(e.dataDir,l).split(G.sep).join(`/`),h=Gu(t.content,a),g={sessionId:e.sessionId,toolCallId:t.toolCallId,toolName:t.toolName,storagePath:p,preview:h,originalChars:t.content.length,truncated:!0,createdAt:new Date().toISOString()};return r.set(g.toolCallId,g),i.push({toolCallId:g.toolCallId,toolName:g.toolName,originalChars:t.content.length,storedChars:t.content.length,previewChars:h.length,strategy:`persist`,createdAt:g.createdAt}),d=g.createdAt,f=`L2`,await m(),{content:Wu(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 Ku(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 Lu(e,t,n){return`${Ru(e)}::${t??``}::${n??``}`}function Ru(e){return G.normalize(e)}async function zu(e){try{return(await W.stat(e)).mtimeMs}catch{return null}}function Bu(e){return nt(`sha1`).update(e).digest(`hex`)}async function Vu(e){try{let t=await o(e);if(t===null)return Hu();let n=JSON.parse(t),r=typeof n.version==`number`?n.version:void 0;return r!==1&&r!==2?Hu():{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:Uu(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 Hu()}}function Hu(){return{version:2,updatedAt:new Date(0).toISOString(),readStates:[],toolResults:[],compaction:{budgets:[],snips:[],collapseSpans:[],consecutiveAutocompactFailures:0}}}function Uu(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 Wu(e){let t=e.preview.length<e.originalChars?`
34
+ ...`:``;return[`[tool result persisted] ${e.toolName} output was too large (${e.originalChars} chars).`,`Full output: ${e.storagePath}`,`Instruction:`,...Fu,`Preview:`,e.preview+t].join(`
35
+ `)}function Gu(e,t){if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
36
+ `),r=n>t*.5?n:t;return e.slice(0,r)}async function Ku(e,t,n,r){let i=l(e,t,r);await W.mkdir(G.dirname(i),{recursive:!0});let a=r?.encryptSessions??!1;await L(i,JSON.stringify(n,null,2),a)}const qu=new Set([`read_file`,`list_dir`,`glob`,`grep`,`bash`,`exec`,`web_fetch`,`web_search`]);async function Ju(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=cd(t),S=x>=0?t.slice(x+1):t;x>=0&&(b=t[x].content);let C=t.length,w=yc(vc(S,a)),T=[],E=(await nu({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=>{J.warn(`topic segmentation failed; falling back to repaired history`,{sessionId:m,channel:_,isSubagent:!!v,error:e instanceof Error?e.message:String(e)})}))?.entries??w;E=await Xu({entries:E,maxInlineResults:16,maxChars:1e3,layer:`L3`,strategy:`snip`,contextStore:f,compactionEvents:T}),E=await Zu({entries:E,contextStore:f,compactionEvents:T});let D=await Qu({entries:E,contextStore:f,compactionEvents:T,dataDir:p,sessionId:m,sessionStoreName:h,sessionPathScope:g});if(E=D.entries,b=ed(b,D.summaries),f&&(b=await Yu({entries:E,existingSummary:b,llm:i,contextStore:f,contextWindowTokens:r,signal:l,hooks:u,hookCtx:d})),!o)return{messages:Cc(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=ld({entries:t,workingEntries:E,pendingUserMessage:s,checkpoint:O?.compaction.modelUsage}).projectedInputTokens>=k,j=O?.compaction.consecutiveAutocompactFailures??0;if(!A||j>=3)return{messages:Cc(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}=Bc(E,r);if(N.length===0)return{messages:Cc(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 kc({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:Cc(yc(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:Cc(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 Yu(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&&sd(t)>=3;if(!d&&!f)return td(n,u?.summary);let p=await kc({entries:t,llm:r,previousSummary:td(n,u?.summary),instructions:[`Produce a durable session memory for future compaction and resume.`,`If skill_load results are present, do not restate or reconstruct SKILL.md instructions.`,`Record only that the skill was loaded and that it must be reloaded with skill_load if its full content is not visible.`].join(` `),contextWindowTokens:a,signal:o,hooks:s,hookCtx:c}),m={version:1,summary:p,generatedAt:new Date().toISOString(),sourceEntryCount:t.length,tokenEstimate:l,trigger:d?`threshold`:`autocompact`};return await i.setSessionMemory(m),p}async function Xu(e){let{entries:t,maxInlineResults:n,maxChars:r,layer:i,strategy:a,contextStore:o,compactionEvents:s}=e;if(t.filter(nd).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(!nd(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=rd(n)?id(n):[`[${a}] Older tool output condensed for context control.`,`Tool: ${n.toolName}`,i?`Preview:\n${i}`:``].filter(Boolean).join(`
37
+ `);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}),yc(l.reverse())}async function Zu(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(!nd(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=rd(r)?id(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(`
38
+ `);a!==r.content&&(s+=1,c+=Math.max(0,Math.floor((r.content.length-a.length)/4)),await n?.recordSnip({toolCallId:r.toolCallId,toolName:r.toolName,originalChars:r.content.length,retainedChars:a.length,reason:`microcompact`,createdAt:new Date().toISOString()})),l.push({...r,content:a})}return s===0?t:(r.push({type:`compaction`,reason:`Microcompacted ${s} stale tool results`,layer:`L4`,strategy:`microcompact_age`,estimatedTokensFreed:c,affectedEntries:s,snapshotVersion:2}),Xu({entries:l,maxInlineResults:4,maxChars:400,layer:`L4`,strategy:`microcompact`,contextStore:n,compactionEvents:r}))}async function Qu(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(nd).filter(e=>qu.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=$u(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:it(),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 ud(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 $u(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(`
37
39
  `),i=e.filter(e=>e.role===`assistant`).map(e=>e.content.trim()).filter(Boolean).slice(-2).join(`
38
- `);return[`[context collapse] ${t.length} tool results across ${n.join(`, `)}`,i?`Assistant checkpoints:\n${i}`:``,r?`Recent tool findings:\n${r}`:``].filter(Boolean).join(`
39
-
40
- `)}function gu(e){return e.role===`tool_result`}function _u(e){return e.toolName===`skill_load`}function vu(e){let t=yu(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(`
41
- `)}function yu(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=bu(t);if(e.name||e.path)return e}return{}}function bu(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 xu(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function Su(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function Cu(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 wu(e,t,n,r){let i=j(e,t,r);await U.mkdir(W.dirname(i),{recursive:!0}),await U.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function Tu(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await Ql({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 uu({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function Eu(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}):uu({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 Du=K.Object({command:K.String({description:`Shell command to execute`}),workdir:K.Optional(K.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:K.Optional(K.Record(K.String(),K.String())),timeout:K.Optional(K.Number({description:`Max total runtime in seconds before the process is killed (default: 1800)`})),yieldMs:K.Optional(K.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:K.Optional(K.Boolean({description:`Return immediately with a running session (poll with the process tool)`}))}),Ou=6e4;function ku(e,t,n){return Math.max(t,Math.min(n,e))}function Au(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function ju(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?Ou:ku(Math.floor(e),0,12e4)}function Mu(e,t){if(!t?.trim())return e;let n=W.isAbsolute(t)?W.normalize(t):W.normalize(W.join(e,t));if(!n.startsWith(e+W.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function Nu(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 Pu(e){return Iu({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
42
- `)}function Fu(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Iu(e){let t=Fu(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 Lu(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:Du,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=Mu(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=Au(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?ju(n.yieldMs):Ou,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:Nu(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?Iu({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[Pu(l)],p=Fu(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(`
43
- `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const Ru=K.Object({action:K.String({description:`Process action: list | poll | log | kill`}),sessionId:K.Optional(K.String({description:`Session id for non-list actions`})),offset:K.Optional(K.Number({description:`Log line offset (0-based)`})),limit:K.Optional(K.Number({description:`Maximum lines to return`})),timeout:K.Optional(K.Number({description:`Poll wait time in milliseconds`}))});function zu(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Bu(e){return{content:[{type:`text`,text:e}],details:{status:`failed`}}}function Vu(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:Ru,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
44
- `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Bu(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,zu(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`}}:Bu(`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}}:Bu(`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}}:Bu(`No session found for ${i}`)}return Bu(`Unsupported action: ${n.action}`)}}}function Hu(e){return Lu({workspaceDir:e,registry:nn(),scopeKey:e})}const Uu=5*1024*1024,Wu=2e3;async function Gu(e,t){e&&await e(t).catch(()=>{})}function Ku(e,t){return W.isAbsolute(e)?W.normalize(e):W.normalize(W.join(t,e))}const qu=K.Object({path:K.String({description:`File path (relative to workspace or absolute)`}),offset:K.Optional(K.Number({description:`Line offset (1-based, default: 1)`})),limit:K.Optional(K.Number({description:`Maximum lines to read (default: 2000)`}))});function Ju(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=Ku(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 U.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 bt(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>Uu){let e=o.slice(0,Uu).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${Uu} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
45
- `),l=Math.max(1,r.offset??1),u=Math.min(Wu,r.limit??Wu),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(`
40
+ `);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(`
41
+
42
+ `)}function ed(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,`
43
+ `)}`)].join(`
44
+ `);return[e?.trim(),r].filter(Boolean).join(`
45
+
46
+ `)}function td(...e){return e.map(e=>e?.trim()).filter(Boolean).join(`
47
+
48
+ `)||void 0}function nd(e){return e.role===`tool_result`}function rd(e){return e.toolName===`skill_load`}function id(e){let t=ad(e),n=t.name||`<skill-name>`,r=t.path?`skill_load(name="${n}", skillPath="${t.path}")`:`skill_load(name="${n}")`;return[`[skill content folded] The previous skill_load result for "${n}" was folded out of model-visible context.`,`The complete SKILL.md content is no longer available in the current prompt.`,`Before using this skill again, call ${r} again. Do not infer or reconstruct the skill instructions from memory or summaries.`,t.path?`Original path: ${t.path}`:``].filter(Boolean).join(`
49
+ `)}function ad(e){for(let t of[e.content,e.toolResultRef?.preview??``]){let e=od(t);if(e.name||e.path)return e}return{}}function od(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 sd(e){return e.reduce((e,t)=>e+(t.role===`user`?1:0),0)}function cd(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.role===`compaction`)return t;return-1}function ld(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 ud(e,t,n,r){let i=j(e,t,r);await W.mkdir(G.dirname(i),{recursive:!0}),await W.appendFile(i,`${JSON.stringify(n)}\n`,`utf-8`)}async function dd(e){let t={storeName:e.sessionStoreName,...e.sessionPathScope},n=await Iu({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 Ju({...t,contextStore:n,sessionStoreName:e.sessionStoreName,sessionPathScope:e.sessionPathScope})},getSnapshot:n.getSnapshot}}async function fd(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}):Ju({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 pd=q.Object({command:q.String({description:`Shell command to execute`}),workdir:q.Optional(q.String({description:"Working directory, must be inside the workspace root (relative path resolved against workspace, or an absolute path under it). If the desired directory cannot be located inside the workspace, do NOT set workdir — instead adjust the command itself (e.g. prefix with `cd /abs/path && ...` or pass absolute paths as arguments)."})),env:q.Optional(q.Record(q.String(),q.String())),timeout:q.Optional(q.Number({description:`Max total runtime in seconds before the process is killed (default: 1800)`})),yieldMs:q.Optional(q.Number({description:`Foreground wait window in ms before returning a running session to poll (default: 60000). Raise it to wait longer inline for a slow command.`})),background:q.Optional(q.Boolean({description:`Return immediately with a running session (poll with the process tool)`}))}),md=6e4;function hd(e,t,n){return Math.max(t,Math.min(n,e))}function gd(e){return typeof e!=`number`||!Number.isFinite(e)||e<=0?1800:Math.floor(e)}function _d(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?md:hd(Math.floor(e),0,12e4)}function vd(e,t){if(!t?.trim())return e;let n=G.isAbsolute(t)?G.normalize(t):G.normalize(G.join(e,t));if(!n.startsWith(e+G.sep)&&n!==e)throw Error(`workdir escapes workspace: ${t}`);return n}function yd(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 bd(e){return Sd({stdout:e.stdoutTail,stderr:e.stderrTail,exitCode:e.exitCode,backgroundInfo:``}).join(`
50
+ `)}function xd(e){return e.replace(/^(\s*\n)+/,``).trimEnd()}function Sd(e){let t=xd(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 Cd(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:pd,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=vd(e.workspaceDir,n.workdir)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{status:`failed`}}}let a=gd(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?_d(n.yieldMs):md,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:yd(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?Sd({stdout:d.stdout,stderr:d.stderr,exitCode:l.exitCode,backgroundInfo:``}):[bd(l)],p=xd(d?.stdout??l.stdoutTail),m=await e.contextManager?.persistToolResult({toolCallId:t,toolName:`exec`,content:p.length>0?p:`(no output)`});return{content:[{type:`text`,text:[m?.content??(p.length>0?p:`(no output)`),...f.slice(1)].join(`
51
+ `)}],details:{status:l.status,sessionId:l.sessionId,command:l.command,cwd:l.cwd,exitCode:l.exitCode,exitSignal:l.exitSignal,toolResultRef:m?.reference}}}}}const wd=q.Object({action:q.String({description:`Process action: list | poll | log | kill`}),sessionId:q.Optional(q.String({description:`Session id for non-list actions`})),offset:q.Optional(q.Number({description:`Log line offset (0-based)`})),limit:q.Optional(q.Number({description:`Maximum lines to return`})),timeout:q.Optional(q.Number({description:`Poll wait time in milliseconds`}))});function Td(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?0:Math.max(0,Math.min(12e4,Math.floor(e)))}function Ed(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:wd,async execute(t,n){let r=n.action?.trim().toLowerCase();if(r===`list`){let t=e.registry.list(e.scopeKey);return{content:[{type:`text`,text:t.length===0?`No running or recent sessions.`:t.map(e=>{let t=(e.endedAt??Date.now())-e.startedAt;return`${e.sessionId} ${e.status.padEnd(9)} ${t}ms :: ${e.command}`}).join(`
52
+ `)}],details:{status:`completed`,sessions:t}}}if(!n.sessionId?.trim())return Ed(`sessionId is required for this action.`);let i=n.sessionId.trim();if(r===`poll`){let t=await e.registry.wait(i,e.scopeKey,Td(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`}}:Ed(`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}}:Ed(`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}}:Ed(`No session found for ${i}`)}return Ed(`Unsupported action: ${n.action}`)}}}function Od(e){return Cd({workspaceDir:e,registry:an(),scopeKey:e})}const kd=5*1024*1024,Ad=2e3;async function jd(e,t){e&&await e(t).catch(()=>{})}function Md(e,t){return G.isAbsolute(e)?G.normalize(e):G.normalize(G.join(t,e))}const Nd=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),offset:q.Optional(q.Number({description:`Line offset (1-based, default: 1)`})),limit:q.Optional(q.Number({description:`Maximum lines to read (default: 2000)`}))});function Pd(e,t){return{name:`read_file`,label:`Read File`,description:`Read the contents of a file`,parameters:Nd,async execute(n,r){let i;try{i=Md(r.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let a=await t?.getReusableRead(i,r.offset,r.limit);if(a?.reused)return{content:[{type:`text`,text:`[file unchanged] ${r.path}`}],details:{content:``,lines:a.lineCount??0,truncated:!1,deduplicated:!0}};let o;try{o=await W.readFile(i)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${r.path}`:String(e)}`}],details:{content:``,lines:0,truncated:!1}}}let s=o.subarray(0,Math.min(o.length,4096));if(await St(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>kd){let e=o.slice(0,kd).toString(`utf-8`);return{content:[{type:`text`,text:`${e}\n[...file truncated at ${kd} bytes]`}],details:{content:e,lines:0,truncated:!0}}}let c=o.toString(`utf-8`).split(`
53
+ `),l=Math.max(1,r.offset??1),u=Math.min(Ad,r.limit??Ad),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(`
46
54
  `),m=f?`\n[...${c.length-(l-1+d.length)} more lines]`:``;return await t?.rememberRead({path:i,content:d.join(`
47
55
  `),lineCount:d.length,offset:r.offset,limit:r.limit}),{content:[{type:`text`,text:p+m}],details:{content:d.join(`
48
- `),lines:d.length,truncated:f}}}}}const Yu=K.Object({path:K.String({description:`File path (relative to workspace or absolute)`}),content:K.String({description:`File content to write`})});function Xu(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Yu,async execute(r,i){let a;try{a=Ku(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await U.mkdir(W.dirname(a),{recursive:!0}),await U.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await Gu(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 Zu=K.Object({path:K.String({description:`File path (relative to workspace or absolute)`}),old_string:K.String({description:`Exact text to replace`}),new_string:K.String({description:`Replacement text`})});function Qu(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:Zu,async execute(r,i){let a;try{a=Ku(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 U.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 U.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await Gu(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 $u=K.Object({path:K.Optional(K.String({description:`Directory path (default: workspace root)`}))});function ed(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:$u,async execute(t,n){let r=n.path??`.`,i;try{i=Ku(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await U.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(`
49
- `)||`(empty directory)`}],details:{entries:a}}}}}const td=K.Object({input:K.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function nd(e,t){let n=W.isAbsolute(e)?W.normalize(e):W.normalize(W.join(t,e));if(!n.startsWith(t+W.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function rd(e,t){let n=W.relative(t,e);return!n||n===``?W.basename(e):n.startsWith(`..`)||W.isAbsolute(n)?e:n}async function id(e){await U.mkdir(W.dirname(e),{recursive:!0})}async function ad(e,t){e&&await e(t).catch(()=>{})}function od(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(`
50
- `)}function sd(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=ld(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=nd(r.path,e);await id(i),await U.writeFile(i,r.contents,`utf-8`),await ad(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),cd(o,s,`added`,rd(i,e));continue}if(r.kind===`delete`){let i=nd(r.path,e);await U.rm(i,{force:!0,recursive:!1}),await ad(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),cd(o,s,`deleted`,rd(i,e));continue}let i=nd(r.path,e),a=await pd(i,r.chunks);if(r.movePath){let c=nd(r.movePath,e);await id(c),await U.writeFile(c,a,`utf-8`),await U.rm(i,{force:!0,recursive:!1}),await ad(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),cd(o,s,`modified`,rd(c,e))}else await U.writeFile(i,a,`utf-8`),await ad(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),cd(o,s,`modified`,rd(i,e))}return{content:[{type:`text`,text:od(o)}],details:{summary:o}}}catch(e){if(vo(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function cd(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function ld(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);ud(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=dd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function ud(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 dd(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}=fd(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 fd(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 pd(e,t){let n=(await U.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
51
- `);n.length>0&&n[n.length-1]===``&&n.pop();let r=hd(n,md(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
52
- `)}function md(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=gd(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=gd(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=gd(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
53
- `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function hd(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 gd(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(_d(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(_d(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(_d(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(_d(e,t,n,e=>vd(e.trim())))return n;return null}function _d(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 vd(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 yd(e){return W.join(e,`.aimax`)}function bd(e){return W.join(yd(e),`MEMORY.md`)}async function xd(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function Sd(e,t){let n=yd(e),r=ge({providerId:t?.providerId,pluginId:t?.pluginId,dataDir:e,memoryDir:n,sessionId:t?.sessionId});return r?{provider:r.provider,resolvedProviderId:r.registration.id,source:`plugin`}:{provider:de({dataDir:e,memoryDir:n,sessionId:t?.sessionId}),resolvedProviderId:`builtin-memory`,source:`builtin`}}async function Cd(e){return he(yd(e))}async function wd(e){try{return await U.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Td(e){return wd(bd(e))}async function Ed(e,t,n){let{provider:r}=Sd(e,n);return await r.search(t)}async function Dd(e,t,n,r,i){try{let{provider:a}=Sd(e,i);return await a.getLines(t,n,r)}catch{return null}}async function Od(e,t,n){let{provider:r,resolvedProviderId:i}=Sd(e,n);await r.append(t),await xd(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 kd(e,t,n,r){let{provider:i,resolvedProviderId:a}=Sd(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 xd(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await xd(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 xd(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 xd(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await xd(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 Ad(e,t,n,r){let{provider:i,resolvedProviderId:a}=Sd(e,r);await i.updateFile(t,n),await xd(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function jd(e,t,n){let{provider:r,resolvedProviderId:i}=Sd(e,n);await r.deleteFile(t),await xd(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const Md=K.Object({query:K.String({description:`Search query (case-insensitive substring match)`})});function Nd(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:Md,async execute(n,r){let i=(await Ed(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(`
54
- `)}],details:{matches:i}}}}}const Pd=K.Object({file:K.String({description:`Memory file path (from memory_search results)`}),start_line:K.Number({description:`Start line number (1-based)`}),end_line:K.Number({description:`End line number (1-based)`})});function Fd(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:Pd,async execute(n,r){let i=await Dd(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(`
55
- `)||`(empty)`}],details:{lines:i}}}}}const Id=K.Object({content:K.String({description:`Content to write to memory`})});function Ld(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:Id,async execute(n,r){try{return await Od(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 Rd=K.Object({section:K.Optional(K.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:K.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:K.Union([K.Literal(`append`),K.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function zd(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:Rd,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await Od(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 Ad(e,`MEMORY.md`,Bd(await Td(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await Od(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 Bd(e,t,n){let r=e.split(`
56
+ `),lines:d.length,truncated:f}}}}}const Fd=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),content:q.String({description:`File content to write`})});function Id(e,t,n){return{name:`write_file`,label:`Write File`,description:`Create or overwrite a file with the given content`,parameters:Fd,async execute(r,i){let a;try{a=Md(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path}}}try{await W.mkdir(G.dirname(a),{recursive:!0}),await W.writeFile(a,i.content,`utf-8`),await t?.invalidateReadPath(a),await jd(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 Ld=q.Object({path:q.String({description:`File path (relative to workspace or absolute)`}),old_string:q.String({description:`Exact text to replace`}),new_string:q.String({description:`Replacement text`})});function 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:Ld,async execute(r,i){let a;try{a=Md(i.path,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{path:i.path,occurrences:0}}}let o;try{o=await W.readFile(a,`utf-8`)}catch(e){return{content:[{type:`text`,text:`Error: ${e.code===`ENOENT`?`File not found: ${i.path}`:String(e)}`}],details:{path:a,occurrences:0}}}if(!o.includes(i.old_string))return{content:[{type:`text`,text:`Error: old_string not found in ${i.path}`}],details:{path:a,occurrences:0}};let s=o.replace(i.old_string,i.new_string);return await W.writeFile(a,s,`utf-8`),await t?.invalidateReadPath(a),await jd(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 zd=q.Object({path:q.Optional(q.String({description:`Directory path (default: workspace root)`}))});function Bd(e){return{name:`list_dir`,label:`List Directory`,description:`List the contents of a directory`,parameters:zd,async execute(t,n){let r=n.path??`.`,i;try{i=Md(r,e)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}let a;try{a=(await W.readdir(i,{withFileTypes:!0})).map(e=>`${e.name}${e.isDirectory()?`/`:``}`)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{entries:[]}}}return{content:[{type:`text`,text:a.join(`
57
+ `)||`(empty directory)`}],details:{entries:a}}}}}const Vd=q.Object({input:q.String({description:`Patch content using the *** Begin Patch/End Patch format.`})});function Hd(e,t){let n=G.isAbsolute(e)?G.normalize(e):G.normalize(G.join(t,e));if(!n.startsWith(t+G.sep)&&n!==t)throw Error(`Path escapes workspace: ${e}`);return n}function Ud(e,t){let n=G.relative(t,e);return!n||n===``?G.basename(e):n.startsWith(`..`)||G.isAbsolute(n)?e:n}async function Wd(e){await W.mkdir(G.dirname(e),{recursive:!0})}async function Gd(e,t){e&&await e(t).catch(()=>{})}function Kd(e){let t=[`Success. Updated the following files:`];for(let n of e.added)t.push(`A ${n}`);for(let n of e.modified)t.push(`M ${n}`);for(let n of e.deleted)t.push(`D ${n}`);return t.join(`
58
+ `)}function qd(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:Vd,async execute(n,r){try{let i=r.input?.trim();if(!i)return{content:[{type:`text`,text:`Error: Provide a patch input.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let a=Yd(i);if(a.hunks.length===0)return{content:[{type:`text`,text:`Error: No files were modified.`}],details:{summary:{added:[],modified:[],deleted:[]}}};let o={added:[],modified:[],deleted:[]},s={added:new Set,modified:new Set,deleted:new Set};for(let r of a.hunks){if(r.kind===`add`){let i=Hd(r.path,e);await Wd(i),await W.writeFile(i,r.contents,`utf-8`),await Gd(t.artifactRecorder,{type:`write`,operation:`patch_add`,file:i,content:r.contents,toolCallId:n,toolName:`apply_patch`}),Jd(o,s,`added`,Ud(i,e));continue}if(r.kind===`delete`){let i=Hd(r.path,e);await W.rm(i,{force:!0,recursive:!1}),await Gd(t.artifactRecorder,{type:`delete`,operation:`patch_delete`,file:i,content:``,toolCallId:n,toolName:`apply_patch`}),Jd(o,s,`deleted`,Ud(i,e));continue}let i=Hd(r.path,e),a=await $d(i,r.chunks);if(r.movePath){let c=Hd(r.movePath,e);await Wd(c),await W.writeFile(c,a,`utf-8`),await W.rm(i,{force:!0,recursive:!1}),await Gd(t.artifactRecorder,{type:`move`,operation:`patch_move`,file:c,sourceFile:i,content:a,toolCallId:n,toolName:`apply_patch`}),Jd(o,s,`modified`,Ud(c,e))}else await W.writeFile(i,a,`utf-8`),await Gd(t.artifactRecorder,{type:`edit`,operation:`patch_update`,file:i,content:a,toolCallId:n,toolName:`apply_patch`}),Jd(o,s,`modified`,Ud(i,e))}return{content:[{type:`text`,text:Kd(o)}],details:{summary:o}}}catch(e){if(ns(e))throw e;return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:String(e)}`}],details:{summary:{added:[],modified:[],deleted:[]}}}}}}}function Jd(e,t,n,r){t[n].has(r)||(t[n].add(r),e[n].push(r))}function Yd(e){let t=e.trim();if(!t)throw Error(`Invalid patch: input is empty.`);let n=t.split(/\r?\n/);Xd(n);let r=[],i=n.slice(1,n.length-1),a=2;for(;i.length>0;){let{hunk:e,consumed:t}=Zd(i,a);r.push(e),a+=t,i=i.slice(t)}return{hunks:r}}function Xd(e){let t=e[0]?.trim(),n=e[e.length-1]?.trim();if(t!==`*** Begin Patch`)throw Error(`The first line of the patch must be '*** Begin Patch'`);if(n!==`*** End Patch`)throw Error(`The last line of the patch must be '*** End Patch'`)}function Zd(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}=Qd(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 Qd(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 $d(e,t){let n=(await W.readFile(e,`utf-8`).catch(t=>{throw Error(`Failed to read file to update ${e}: ${t}`)})).split(`
59
+ `);n.length>0&&n[n.length-1]===``&&n.pop();let r=tf(n,ef(n,e,t));return(r.length===0||r[r.length-1]!==``)&&(r=[...r,``]),r.join(`
60
+ `)}function ef(e,t,n){let r=[],i=0;for(let a of n){if(a.changeContext){let n=nf(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=nf(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=nf(e,n,i,a.isEndOfFile)),s===null)throw Error(`Failed to find expected lines in ${t}:\n${a.oldLines.join(`
61
+ `)}`);r.push([s,n.length,o]),i=s+n.length}return r.sort((e,t)=>e[0]-t[0]),r}function tf(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 nf(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(rf(e,t,n,e=>e))return n;for(let n=a;n<=i;n+=1)if(rf(e,t,n,e=>e.trimEnd()))return n;for(let n=a;n<=i;n+=1)if(rf(e,t,n,e=>e.trim()))return n;for(let n=a;n<=i;n+=1)if(rf(e,t,n,e=>af(e.trim())))return n;return null}function rf(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 af(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 of(e){return G.join(e,`.aimax`)}function sf(e){return G.join(of(e),`MEMORY.md`)}async function cf(e,t,n){e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{}),t&&await Promise.resolve(t(n)).catch(()=>{})}function lf(e,t){let n=of(e),r=_e({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 uf(e){return ue(of(e))}async function df(e){try{return await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ff(e){return df(sf(e))}async function pf(e,t,n){let{provider:r}=lf(e,n);return await r.search(t)}async function mf(e,t,n,r,i){try{let{provider:a}=lf(e,i);return await a.getLines(t,n,r)}catch{return null}}async function hf(e,t,n){let{provider:r,resolvedProviderId:i}=lf(e,n);await r.append(t),await cf(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 gf(e,t,n,r){let{provider:i,resolvedProviderId:a}=lf(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 cf(i,r?.onMemoryChanged,{reason:`appendRecent`,files:[o],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await cf(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 cf(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 cf(i,r?.onMemoryChanged,{reason:`append`,files:[`MEMORY.md`],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()}),await cf(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 _f(e,t,n,r){let{provider:i,resolvedProviderId:a}=lf(e,r);await i.updateFile(t,n),await cf(i,r?.onMemoryChanged,{reason:`update`,files:[t],source:`memory`,sessionId:r?.sessionId,providerId:r?.providerId??r?.pluginId??a,timestamp:new Date().toISOString()})}async function vf(e,t,n){let{provider:r,resolvedProviderId:i}=lf(e,n);await r.deleteFile(t),await cf(r,n?.onMemoryChanged,{reason:`delete`,files:[t],source:`memory`,sessionId:n?.sessionId,providerId:n?.providerId??n?.pluginId??i,timestamp:new Date().toISOString()})}const yf=q.Object({query:q.String({description:`Search query (case-insensitive substring match)`})});function bf(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:yf,async execute(n,r){let i=(await pf(e,r.query,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId})).map(e=>({id:e.id,file:e.path,start_line:e.startLine,end_line:e.endLine,score:Number(e.score.toFixed(4)),text:e.snippet,source:e.source,citation:e.citation}));return i.length===0?{content:[{type:`text`,text:`No results found for: ${r.query}`}],details:{matches:i}}:{content:[{type:`text`,text:i.map(e=>{let t=`${e.id?`[${e.id}] `:``}${e.file}:${e.start_line}-${e.end_line} (${e.score}): ${e.text}`;return e.citation?`${t}\n${e.citation}`:t}).join(`
62
+ `)}],details:{matches:i}}}}}const xf=q.Object({file:q.String({description:`Memory file path (from memory_search results)`}),start_line:q.Number({description:`Start line number (1-based)`}),end_line:q.Number({description:`End line number (1-based)`})});function Sf(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:xf,async execute(n,r){let i=await mf(e,r.file,r.start_line,r.end_line,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});return i===null?{content:[{type:`text`,text:`File not found: ${r.file}`}],details:{lines:null}}:{content:[{type:`text`,text:i.map((e,t)=>`${(r.start_line+t).toString().padStart(4)} ${e}`).join(`
63
+ `)||`(empty)`}],details:{lines:i}}}}}const Cf=q.Object({content:q.String({description:`Content to write to memory`})});function wf(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:Cf,async execute(n,r){try{return await hf(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 Tf=q.Object({section:q.Optional(q.String({description:`Section heading in MEMORY.md (e.g. "Preferences", "Project Notes", "Decisions"). Omit for flat append without a section.`})),content:q.String({description:`Content to write under this section (Markdown formatting is supported)`}),mode:q.Union([q.Literal(`append`),q.Literal(`replace`)],{description:`"append" adds to existing section; "replace" overwrites the section`,default:`append`})});function Ef(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:Tf,async execute(n,r){let i=r.section?.trim(),a=r.mode??`append`;if(!i)try{return await hf(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 _f(e,`MEMORY.md`,Df(await ff(e)??``,i,r.content),{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged}):await hf(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(`
56
64
  `),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(`
57
65
  `).trimEnd(),a,r.slice(s).join(`
58
66
  `).trimStart()].filter(e=>e.length>0).join(`
59
- `)}\n`}function Vd(e,t){let n=e.split(`
67
+ `)}\n`}function Of(e,t){let n=e.split(`
60
68
  `),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(`
61
69
  `).trimEnd(),n.slice(a).join(`
62
70
  `).trimStart()].filter(e=>e.length>0);return o.length>0?`${o.join(`
63
- `)}\n`:``}function Hd(e,t){let n=e.split(`
71
+ `)}\n`:``}function kf(e,t){let n=e.split(`
64
72
  `);return t<1||t>n.length?null:(n.splice(t-1,1),n.length>0?`${n.join(`
65
- `)}\n`:``)}function Ud(e,t,n){let r=e.split(`
73
+ `)}\n`:``)}function Af(e,t,n){let r=e.split(`
66
74
  `);return t<1||t>r.length?null:(r[t-1]=n,`${r.join(`
67
- `)}\n`)}function Wd(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 Gd(e,t){let n=[],r=t.split(`
68
- `);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 Kd=K.Object({content:K.String({description:`Note to append to today's daily log`}),scope:K.Optional(K.Union([K.Literal(`daily`),K.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function 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:Kd,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await kd(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 Jd=K.Object({scope:K.Optional(K.Union([K.Literal(`long-term`),K.Literal(`recent`),K.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function Yd(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:Jd,async execute(n,r){try{let n=r.scope??`all`,i=await Cd(e),a=[];for(let n of i.slice(0,30)){let r=await Dd(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
69
- `),t=Gd(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
+ `)}\n`)}function jf(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 Mf(e,t){let n=[],r=t.split(`
76
+ `);for(let t of r){let r=t.match(/^##\s+(.+)$/);if(r?.[1]){let t=r[1].trim(),i=`${e}#${t}`;n.push({id:i,heading:t})}}if(n.length===0){let t=0;for(let i of r){t+=1;let r=i.trim();if(!r||r.startsWith(`---`)||r.startsWith(`# `))continue;let a=r.length>60?`${r.slice(0,57)}...`:r;if(n.push({id:`${e}#L${t}`,heading:a}),n.length>=20)break}}return n}const Nf=q.Object({content:q.String({description:`Note to append to today's daily log`}),scope:q.Optional(q.Union([q.Literal(`daily`),q.Literal(`session`)],{description:`Write scope: "daily" (default) or "session"`,default:`daily`}))});function Pf(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:Nf,async execute(n,r){let i=new Date().toISOString().slice(0,10),a=r.scope??`daily`;try{return await gf(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 Ff=q.Object({scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`List scope: "long-term", "recent", or "all" (default)`,default:`all`}))});function If(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:Ff,async execute(n,r){try{let n=r.scope??`all`,i=await uf(e),a=[];for(let n of i.slice(0,30)){let r=await mf(e,n,1,100,{providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId});if(r&&r.length>0){let e=r.join(`
77
+ `),t=Mf(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(`
70
78
  `):` (no sections)`;return`--- ${e.file} ---\n${t}\n${e.content.slice(0,300)}`}).join(`
71
79
 
72
- `)||`(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 Xd=K.Object({id:K.Optional(K.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:K.Optional(K.String({description:`Search query used to find memories to delete`})),limit:K.Optional(K.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:K.Optional(K.Union([K.Literal(`long-term`),K.Literal(`recent`),K.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Zd(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:Xd,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=Wd(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Vd(await Td(e)??``,t.section);return n===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Ad(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 Dd(e,t.filePath,1,1e4,i);if(!n)return{content:[{type:`text`,text:`File not found: ${t.filePath}`}],details:{removed:0,id:r.id}};let a=Vd(n.join(`
73
- `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await Ad(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 Dd(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=Hd(n.join(`
74
- `),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 Ad(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 jd(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 Ed(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await jd(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 Qd=K.Object({id:K.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:K.String({description:`New content to replace the existing memory with`})});function $d(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:Qd,async execute(n,r){try{let n=Wd(r.id);if(n.section){let i=Bd(await Td(e)??``,n.section,r.content);return await Ad(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 Dd(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=Ud(i.join(`
75
- `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await Ad(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 Ad(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 ef=K.Object({query:K.Optional(K.String({description:`Search query; omit to browse recent sessions.`})),role_filter:K.Optional(K.Union([K.Literal(`user`),K.Literal(`assistant`),K.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:K.Optional(K.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:K.Optional(K.Union([K.Literal(`llm`),K.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function tf(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:ef,async execute(n,r){let i=nf(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await rf(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 af({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=vf(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 Gs({entries:hf(mf(await F(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:_f({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 nf(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function rf(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 af(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=lf(e.query),i=(await yf(n,6,async t=>of({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort(pf).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 of(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
76
- `);for(let t of r){let r=t.trim();if(!r||!sf(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!cf(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=df(i.content,e.terms,i.role);if(a<=0)continue;let o=ff(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort(pf),n.length=20)}return n.sort(pf),n}function sf(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function cf(e){return e===`user`||e===`assistant`||e===`tool_result`}function lf(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=>uf(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 uf(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 df(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 ff(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function pf(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function mf(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function hf(e,t,n){if(e.length===0)return e;let r=lf(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 gf(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 gf(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 _f(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(`
77
- `)}function vf(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(`
78
- `)}`}async function yf(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 bf(e){return W.join(e,`.aimax`,`skills`)}function xf(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Sf(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${xf(n)}\n`)}function Cf(e){let t=ot(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
79
- `);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 wf(e){let t=ot(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 Tf(e){return(await U.stat(e)).mtime.toISOString()}async function Ef(e){return Of([bf(e)])}async function Df(e,t,n=[]){return Of([...n,...t,bf(e)])}async function Of(e){let t=new Map;for(let n of e){let e;try{e=await U.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=W.join(n,e,`SKILL.md`),i;try{i=await U.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=Cf(i),o=wf(i),s=await Tf(r)}catch(t){Sf(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 kf(e,t){let n=t.trim();if(!n)return;let r=(await Of(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:W.dirname(r.location)}}async function Af(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=W.resolve(r),a=W.basename(i)===`SKILL.md`?i:W.join(i,`SKILL.md`);if(W.basename(a)!==`SKILL.md`)return;let o;try{o=await U.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=Cf(o),c=wf(o),l=await Tf(a)}catch(e){Sf(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:W.dirname(a)}}async function jf(e,t,n){let r=n?.trim()?await Af(t,n):await kf(e,t);if(!r)return;let i=await U.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function Mf(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(`
80
+ `)||`(no memories)`}],details:{count:a.length,scope:n,files:a}}}catch(e){throw Error(`Failed to list memories: ${e instanceof Error?e.message:String(e)}`)}}}}const Lf=q.Object({id:q.Optional(q.String({description:`The entry ID of the memory to delete (from memory_list or memory_search results)`})),query:q.Optional(q.String({description:`Search query used to find memories to delete`})),limit:q.Optional(q.Number({description:`Maximum number of matching memories to delete when using query mode (default 5, max 20)`,minimum:1,maximum:20})),scope:q.Optional(q.Union([q.Literal(`long-term`),q.Literal(`recent`),q.Literal(`all`)],{description:`Delete scope for query mode: "long-term", "recent", or "all" (default)`,default:`all`}))});function Rf(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:Lf,async execute(n,r){let i={providerId:t?.providerId,pluginId:t?.pluginId,sessionId:t?.sessionId,onMemoryChanged:t?.onMemoryChanged};try{if(r.id){let t=jf(r.id);if(t.section){if(t.filePath===`MEMORY.md`){let n=Of(await ff(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 _f(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 mf(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=Of(n.join(`
81
+ `),t.section);return a===null?{content:[{type:`text`,text:`Section "${t.section}" not found in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await _f(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 mf(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=kf(n.join(`
82
+ `),t.line);return a===null?{content:[{type:`text`,text:`Line ${t.line} out of range in ${t.filePath}`}],details:{removed:0,id:r.id}}:(await _f(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 vf(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 pf(e,r.query,i),a=0;for(let r of n.slice(0,t))r.path!==`MEMORY.md`&&(await vf(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 zf=q.Object({id:q.String({description:`The entry ID of the memory to update (from memory_list or memory_search results, e.g. MEMORY.md#Preferences)`}),content:q.String({description:`New content to replace the existing memory with`})});function Bf(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:zf,async execute(n,r){try{let n=jf(r.id);if(n.section){let i=Df(await ff(e)??``,n.section,r.content);return await _f(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 mf(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=Af(i.join(`
83
+ `),n.line,r.content);if(a===null)throw Error(`Line ${n.line} out of range in ${n.filePath}`);return await _f(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 _f(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 Vf=q.Object({query:q.Optional(q.String({description:`Search query; omit to browse recent sessions.`})),role_filter:q.Optional(q.Union([q.Literal(`user`),q.Literal(`assistant`),q.Literal(`tool_result`)],{description:`Optional role filter for transcript matching.`})),limit:q.Optional(q.Number({description:`Max sessions to return (default 3, max 5).`,minimum:1,maximum:5})),summary_mode:q.Optional(q.Union([q.Literal(`llm`),q.Literal(`off`)],{description:`Summary mode: "llm" (default) or "off" for extractive only.`,default:`llm`}))});function Hf(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:Vf,async execute(n,r){let i=Uf(r.limit),a=r.summary_mode??`llm`,o=r.query?.trim(),s=r.role_filter;if(!o){let n=await Wf(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 Gf({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=ip(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 kc({entries:tp(ep(await F(e,n.sessionId,{storeName:t?.sessionStoreName})),o,1e5),llm:t.llm,instructions:rp({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 Uf(e){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),1),5):3}async function Wf(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 Gf(e){let t=e.messageLimit??50,n=(await x(e.dataDir,{storeName:e.sessionStoreName})).filter(t=>t!==e.currentSessionId),r=Yf(e.query),i=(await ap(n,6,async t=>Kf({dataDir:e.dataDir,sessionId:t,terms:r,roleFilter:e.roleFilter,storeName:e.sessionStoreName}))).flat().sort($f).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 Kf(e){let t=await o(c(e.dataDir,e.sessionId,{storeName:e.storeName}));if(t===null)return[];let n=[],r=t.split(`
84
+ `);for(let t of r){let r=t.trim();if(!r||!qf(r,e.terms))continue;let i;try{i=JSON.parse(r)}catch{continue}if(!Jf(i.role)||e.roleFilter&&i.role!==e.roleFilter||typeof i.content!=`string`||i.content.trim().length===0)continue;let a=Zf(i.content,e.terms,i.role);if(a<=0)continue;let o=Qf(i.content);n.push({sessionId:e.sessionId,score:a,snippet:o,timestamp:typeof i.timestamp==`string`?i.timestamp:``}),n.length>20&&(n.sort($f),n.length=20)}return n.sort($f),n}function qf(e,t){let n=e.toLowerCase();for(let e of t)if(e&&n.includes(e))return!0;return!1}function Jf(e){return e===`user`||e===`assistant`||e===`tool_result`}function Yf(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=>Xf(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 Xf(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 Zf(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 Qf(e){let t=e.replace(/\s+/g,` `).trim();return t.length>280?`${t.slice(0,277)}...`:t}function $f(e,t){return t.score===e.score?t.timestamp.localeCompare(e.timestamp):t.score-e.score}function ep(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`)}function tp(e,t,n){if(e.length===0)return e;let r=Yf(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 np(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 np(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 rp(e){let t=e.languageHint?.trim(),n=[`Summarize this past session for retrieval use.`,`Focus query: ${e.query}`,`Prioritize: final outcome, key actions, concrete evidence (files/commands/ids), unresolved items.`,`Do not invent facts. If evidence is missing, say so explicitly.`,`Keep it concise and factual.`];return t&&n.push(`Respond in: ${t}`),n.join(`
85
+ `)}function ip(e,t){return t.length===0?`No direct transcript snippet was extracted for query: ${e}`:`Extractive summary for "${e}":\n${t.slice(0,3).map((e,t)=>`${t+1}. ${e}`).join(`
86
+ `)}`}async function ap(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 op(e){return G.join(e,`.aimax`,`skills`)}function sp(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function cp(e,t,n){process.stderr.write(`[skills] failed to load skill "${e}" from ${t}: ${sp(n)}\n`)}function lp(e){let t=ct(e),n=t.data.description;if(typeof n==`string`&&n.trim())return n.trim().slice(0,500);let r=t.content.split(`
87
+ `);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 up(e){let t=ct(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 dp(e){return(await W.stat(e)).mtime.toISOString()}async function fp(e){return mp([op(e)])}async function pp(e,t,n=[]){return mp([...n,...t,op(e)])}async function mp(e){let t=new Map;for(let n of e){let e;try{e=await W.readdir(n,{withFileTypes:!0})}catch(e){if(e.code===`ENOENT`)continue;throw e}let r=e.filter(e=>e.isDirectory()).map(e=>e.name);for(let e of r.sort()){let r=G.join(n,e,`SKILL.md`),i;try{i=await W.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)continue;throw e}let a,o,s;try{a=lp(i),o=up(i),s=await dp(r)}catch(t){cp(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 hp(e,t){let n=t.trim();if(!n)return;let r=(await mp(e)).find(e=>e.name===n);if(r)return{skill:r,rootDir:G.dirname(r.location)}}async function gp(e,t){let n=e.trim(),r=t.trim();if(!n||!r)return;let i=G.resolve(r),a=G.basename(i)===`SKILL.md`?i:G.join(i,`SKILL.md`);if(G.basename(a)!==`SKILL.md`)return;let o;try{o=await W.readFile(a,`utf-8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return;throw e}let s,c,l;try{s=lp(o),c=up(o),l=await dp(a)}catch(e){cp(n,a,e);return}return{skill:{name:n,description:s,location:a,version:c,skillFileMtime:l},rootDir:G.dirname(a)}}async function _p(e,t,n){let r=n?.trim()?await gp(t,n):await hp(e,t);if(!r)return;let i=await W.readFile(r.skill.location,`utf-8`);return{skill:r.skill,content:i}}function vp(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(`
80
88
  `)).join(`
81
- `)}\n</available_skills>`}const Nf=K.Object({category:K.Optional(K.String({description:`Reserved category filter field. Not used yet.`}))}),Pf=K.Object({name:K.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:K.Optional(K.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function Ff(e,t,n=[]){return[...n,...t,bf(e)]}function If(e,t,n=[]){let r=Ff(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:Nf,async execute(e,t){let n=await Of(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 Lf(e){let t=Ff(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:Pf,async execute(r,i){let a=await jf(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 Rf=K.Object({});function zf(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:Rf,async execute(r,i){let a=await H(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null,goalState:null,workflowWarning:null})}],details:{}};let o=await z(e,t,a,{storeName:n}),s=await bn(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:{}}}}}const Bf=K.Object({status:K.String({description:`Status to set. Only 'complete' is allowed.`})});function Vf(e,t,n,r,i=t){return{name:`update_goal`,label:`Update Goal`,description:'Legacy goal completion tool. V2-lite workflow goals must use `goal_complete` with final evidence refs instead. This tool rejects `status: "complete"` when workflow is active or not initialized.',parameters:Bf,async execute(r,i){if(i.status!==`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Invalid status: "${i.status}". Only "complete" is allowed via this tool.`},null,2)}],details:{}};let a=await H(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null,error:`No active goal exists for this session. Use the CLI to set a goal first.`},null,2)}],details:{}};if(a.status===`complete`)return{content:[{type:`text`,text:JSON.stringify({goal:a},null,2)}],details:{}};let o=await bn(e,t,{storeName:n});return o.workflowWarning===`workflow_not_initialized`?{content:[{type:`text`,text:JSON.stringify({goal:null,error:`workflow_not_initialized: goal exists under goal/ but goal/state.json is missing. Re-create the goal or initialize workflow before completing.`},null,2)}],details:{}}:o.goalState?{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Cannot complete goal via update_goal when V2-lite workflow is active. Use goal_complete with finalEvidenceRefs instead.`},null,2)}],details:{}}:{content:[{type:`text`,text:JSON.stringify({goal:null,error:`Cannot complete goal via update_goal in V2-lite. Use goal_complete with finalEvidenceRefs instead.`},null,2)}],details:{}}}}}function Hf(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 Uf(e){let t=Hf(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=W.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 Wf(e){let t=e.watchFactory??((e,t,n)=>G.watch(e,t,n)),n=W.join(e.dataDir,`.aimax`),r=[{target:W.join(n,`MEMORY.md`),kind:`memory-file`},{target:W.join(n,`memory.md`),kind:`memory-file-lower`},{target:W.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=Uf({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 Gf(e){return e.projectDir?.trim()||W.join(e.dataDir,`workspace`)}async function Kf(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=Gf(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Yf(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=W.join(t.dataDir,`.aimax`),m=ge({providerId:o,pluginId:s,dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),g=m?.provider??de({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName}),_=m?.registration.id??g.id,v=m?.registration.pluginId;await n.dispatchDiagnostic(i,{level:`info`,scope:`memory`,phase:`memory_provider_resolved`,message:`memory provider resolved for run`,details:{providerId:_,pluginId:v,providerSource:m?`plugin`:`builtin`,requestedProviderId:o,requestedPluginId:s,fallbackToBuiltin:!m}}).catch(()=>{});let y=Wf({dataDir:t.dataDir,sessionId:i,providerId:o??s??_,provider:g,onMemoryChanged:f});g.sync&&g.sync(`session-start`).catch(()=>{});let b=async e=>{await h(t.dataDir,i,e,Jf({sessionOptions:X(t),providerId:o,pluginId:s,onMemoryChanged:f}))};return{workspaceDir:c,memoryProviderId:o,memoryPluginId:s,appendTranscriptEntry:b,persistInitialUserEntry:async e=>d?!1:(await b({role:`user`,content:e,timestamp:new Date().toISOString()}),d=!0,!0),stop:()=>{y()}}}function qf(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Jf(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 Yf(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 Xf(e){return Gf({dataDir:e.dataDir,projectDir:e.projectDir})}function Zf(e){return In({dataDir:e.dataDir,workspaceDir:Xf(e),projectDir:e.projectDir})}function Q(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function $(e,t){return Q({ok:!1,error:e,...t})}function Qf(e,t){return un(e.dataDir,e.sessionId,Z(e),t)}async function $f(e){try{return await _n(e.dataDir,e.sessionId,Z(e))}catch(e){if(e instanceof sn)return{corrupt:!0};throw e}}function ep(){return $(`workflow_corrupt`,{repairTool:`goal_repair_workflow_state`})}const tp={hint:[`Use only the returned evidenceRef values from goal_record_note, goal_record_exec, or goal_record_snapshot.`,`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_exec; exec does not register goal evidence.`].join(` `),suggestedTools:[`goal_record_note`,`goal_record_exec`,`goal_record_snapshot`],example:{registerManualEvidence:{tool:`goal_record_note`,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_exec`,args:{command:`npm test`,cwd:`<workspace>`,timeoutMs:12e4}},registerSnapshotEvidence:{tool:`goal_record_snapshot`,args:{path:`<workspace>/artifact.html`,summary:`final deliverable`}},evidenceRefs:[`manual:...`]}},np=/goal[/\\]state\.json|\btask\s*list\b|\btask-\d+|\b(plan|planning|planned|added|through|workflow)\b/i,rp=/[/\\]|\.(?:html|css|js|ts|tsx|jsx|json|md|txt|py|go|rs|yaml|yml|sh)\b|\bexists\b/i,ip=/\b(npm|pnpm|yarn|cargo|go test|pytest|vitest|jest|exit code|stdout|stderr|command output|test pass|tests pass)\b/i;function ap(e,t){let n=`${e}\n${t}`;return np.test(n)?`goal/state.json`:/\buser\b/i.test(n)&&/\bconfirm/i.test(n)?`user`:`model`}function op(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 sp(e){let t=e.trim();return np.test(t)?{tool:`goal_record_note`,reason:`the ref describes planning state`}:rp.test(t)?{tool:`goal_record_snapshot`,reason:`the ref describes a file artifact`}:ip.test(t)?{tool:`goal_record_exec`,reason:`the ref describes command output`}:{tool:`goal_record_note`,reason:`the ref is natural language and must be registered as evidence`}}function cp(e,t){let n=e.trim();switch(t.tool){case`goal_record_note`:return{kind:`manual`,source:ap(n,n),summary:n.slice(0,120),content:n};case`goal_record_snapshot`:{let e=op(n);return e?{path:e,summary:n.slice(0,120)}:{kind:`manual`,source:`model`,summary:n.slice(0,120),content:n}}case`goal_record_exec`:return{command:n.includes(`npm test`)?`npm test`:`<command>`,cwd:`<workspace>`,timeoutMs:12e4}}}function lp(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=sp(e),a=i.tool===`goal_record_snapshot`&&!op(e)?`goal_record_note`:i.tool,o=a===`goal_record_note`&&i.tool===`goal_record_snapshot`?`the ref describes a file artifact but no reliable path could be extracted`:i.reason;n.push({tool:a,reason:o,args:cp(e,{tool:a,reason:o})})}return n}function up(e){let t=e.errors[0]?.code??`invalid_evidence`;return t===`unregistered_evidence_ref`?$(t,{errors:e.errors,repairPlan:lp(e.errors),...tp}):$(t,{errors:e.errors})}function dp(e,t){return $(`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:ap(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 fp(e){let t=Zn(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 pp(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 mp(e,t){return e.tasks.find(e=>e.id===t)}function hp(e){return e.tasks.some(e=>e.kind===`execution`&&e.required!==!1)}function gp(e){return e.ok===!1?e.warning:null}async function _p(e,t){await Gn(e.dataDir,e.sessionId,t,Z(e));let n=gp(await Yn(e.dataDir,e.sessionId,t,Z(e)));return n?{planWarning:n}:{}}function vp(e){return{name:`goal_plan_update`,label:`Goal Plan Update`,description:`Update controlled sections of goal/plan.md without changing task workflow state.`,parameters:K.Object({interpretation:K.Optional(K.String()),assumptions:K.Optional(K.Array(K.String())),openQuestions:K.Optional(K.Array(K.String())),taskPlanNotes:K.Optional(K.String())}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t;await q(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 Jn(e.dataDir,e.sessionId,{interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Z(e)),a=await Yn(e.dataDir,e.sessionId,r,Z(e));return Q({ok:!0,goalId:r.goalId,planMeta:i,warning:gp(a),hint:`Use goal_add_task to project executable tasks into goal/state.json.`})})}}}function yp(e){return{name:`goal_checkpoint`,label:`Goal Checkpoint`,description:`Record intermediate progress without marking a task done.`,parameters:K.Object({summary:K.String(),evidenceRefs:K.Optional(K.Array(K.String()))}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t,i=!0,a=n.evidenceRefs??[];a.length>0&&(i=(await Un(e.dataDir,e.sessionId,a,{...Z(e),requireCommandSuccess:!1})).valid),await q(e.dataDir,e.sessionId,{type:`goal_checkpoint`,goalId:r.goalId,taskId:r.currentTaskId,summary:n.summary,evidenceRefs:a,verified:i},Z(e));let o=[...(await Kn(e.dataDir,e.sessionId,Z(e))).progressLog??[],`${new Date().toISOString().slice(0,16).replace(`T`,` `)}: ${n.summary}${i?``:` (unverified evidence)`}`],s=await Jn(e.dataDir,e.sessionId,{progressLog:o},Z(e)),c=await Yn(e.dataDir,e.sessionId,r,Z(e));return Q({ok:!0,verified:i,planMeta:s,warning:gp(c)})})}}}function bp(e){return{name:`goal_task_start`,label:`Goal Task Start`,description:`Switch the current task to doing.`,parameters:K.Object({taskId:K.String()}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t;if(r.status===`blocked`)return $(`workflow_blocked`);let i=mp(r,n.taskId);if(!i)return $(`task_not_found`);if(i.status===`doing`&&i.id===r.currentTaskId)return Q({ok:!0,alreadyStarted:!0,currentTaskId:i.id});if(i.status!==`todo`&&i.status!==`blocked`)return $(`task_not_startable`);let a=r.tasks.find(e=>e.status===`doing`&&e.id!==i.id);if(a)return $(`another_task_is_doing`,{taskId:a.id});let o=new Date().toISOString(),s=r.tasks.map(e=>e.id===i.id?{...e,status:`doing`,blockedReason:null,updatedAt:o}:e),c={...r,currentTaskId:i.id,status:`active`,blockedReason:null,tasks:s,updatedAt:o};await q(e.dataDir,e.sessionId,{type:`goal_task_started`,goalId:r.goalId,taskId:i.id},Z(e));let{planWarning:l}=await _p(e,c);return Q({ok:!0,currentTaskId:i.id,warning:l??null})})}}}function xp(e){return{name:`goal_task_done`,label:`Goal Task Done`,description:`Mark the current doing task done with evidence covering required acceptance criteria.`,parameters:K.Object({taskId:K.String(),summary:K.Optional(K.String()),evidenceRefs:K.Optional(K.Array(K.String())),acceptanceEvidence:K.Optional(K.Array(K.Object({criterionId:K.String(),evidenceRefs:K.Array(K.String())})))}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t,i=mp(r,n.taskId);if(!i)return $(`task_not_found`);if(i.status!==`doing`)return $(`task_not_doing`);if(i.acceptanceCriteria.length===0)return $(`missing_acceptance_criteria`);let a=pp(n.evidenceRefs,n.acceptanceEvidence);if(a.length===0)return $(`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 $(`missing_required_acceptance_evidence`,{criterionId:e.id});let c=await Un(e.dataDir,e.sessionId,a,Z(e));if(!c.valid)return up(c);if(i.kind===`clarify`){if(!hp(r))return $(`missing_executable_followup_task`);if(!a.some(e=>e.startsWith(`note:`)||e.startsWith(`manual:`)))return $(`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 q(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 Kn(e.dataDir,e.sessionId,Z(e));await Jn(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 _p(e,m);return Q({ok:!0,currentTaskId:m.currentTaskId,hint:m.currentTaskId?null:`All tasks done. Call goal_complete with finalEvidenceRefs.`,warning:g??null})})}}}function Sp(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:K.Object({taskId:K.String(),reason:K.String(),neededInput:K.Optional(K.String()),evidenceRefs:K.Optional(K.Array(K.String()))}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t,i=mp(r,n.taskId);if(!i)return $(`task_not_found`);let a=n.evidenceRefs??[];if(a.length>0){let t=await Un(e.dataDir,e.sessionId,a,{...Z(e),requireCommandSuccess:!1});if(!t.valid)return $(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 q(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 Jn(e.dataDir,e.sessionId,{risks:[s]},Z(e));let{planWarning:u}=await _p(e,l);return Q({ok:!0,workflowStatus:`blocked`,warning:u??null})})}}}function Cp(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:K.Object({title:K.String(),kind:K.Optional(K.Literal(`execution`)),required:K.Optional(K.Boolean()),acceptanceCriteria:K.Array(K.Union([K.String(),K.Object({text:K.String(),required:K.Optional(K.Boolean())})])),afterTaskId:K.Optional(K.String()),startNow:K.Optional(K.Boolean())}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t;if((n.kind??`execution`)!==`execution`)return $(`invalid_task_kind`);if(n.acceptanceCriteria.length===0)return $(`missing_acceptance_criteria`);let i=new Date().toISOString(),a=Xn(r.tasks),o=fp(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 $(`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 q(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 _p(e,l);return Q({ok:!0,taskId:a,warning:u??null})})}}}function wp(e){return{name:`goal_record_note`,label:`Goal Record Note`,description:`Record note or manual evidence in the artifact registry.`,parameters:K.Object({kind:K.Union([K.Literal(`note`),K.Literal(`manual`)]),summary:K.String(),content:K.String(),taskId:K.Optional(K.String()),source:K.Optional(K.String())}),async execute(t,n){let r=await $f(e);if(r===null)return $(`workflow_not_initialized`);if(`corrupt`in r)return ep();let i=r,a=await Qn(e.dataDir,e.sessionId,{kind:n.kind,summary:n.summary,content:n.content,source:n.source},Z(e));return`error`in a?a.error===`manual evidence requires source`?dp(n.summary,n.content):$(a.error):(await q(e.dataDir,e.sessionId,{type:`goal_note_recorded`,goalId:i.goalId,taskId:n.taskId,evidenceRef:a.evidenceRef,kind:n.kind,summary:n.summary,source:n.source??`model`},Z(e)),Q({ok:!0,evidenceRef:a.evidenceRef}))}}}function Tp(e){return{name:`goal_record_exec`,label:`Goal Record Exec`,description:`Execute a bounded command and record command evidence.`,parameters:K.Object({command:K.String(),cwd:K.Optional(K.String()),timeoutMs:K.Optional(K.Number())}),async execute(t,n){let r=await $f(e);if(r===null)return $(`workflow_not_initialized`);if(`corrupt`in r)return ep();let i=r,a=await $n(e.dataDir,e.sessionId,{command:n.command,cwd:n.cwd,timeoutMs:n.timeoutMs,workspaceDir:Xf(e),allowedRoots:Zf(e),baseEnv:e.baseEnv},Z(e));return`error`in a?$(a.error):(await q(e.dataDir,e.sessionId,{type:`goal_command_recorded`,goalId:i.goalId,evidenceRef:a.evidenceRef,command:n.command,cwd:n.cwd??Xf(e),exitCode:a.exitCode},Z(e)),Q({ok:!0,evidenceRef:a.evidenceRef,exitCode:a.exitCode}))}}}function Ep(e){return{name:`goal_record_snapshot`,label:`Goal Record Snapshot`,description:`Snapshot a workspace file as evidence.`,parameters:K.Object({path:K.String(),summary:K.Optional(K.String())}),async execute(t,n){let r=await $f(e);if(r===null)return $(`workflow_not_initialized`);if(`corrupt`in r)return ep();let i=r,a=await tr(e.dataDir,e.sessionId,{path:n.path,summary:n.summary,workspaceDir:Xf(e),allowedRoots:Zf(e)},Z(e));return`error`in a?$(a.error):(await q(e.dataDir,e.sessionId,{type:`goal_snapshot_recorded`,goalId:i.goalId,evidenceRef:a.evidenceRef,path:n.path},Z(e)),Q({ok:!0,evidenceRef:a.evidenceRef}))}}}function Dp(e){return{name:`goal_complete`,label:`Goal Complete`,description:`Complete the goal after all required tasks are done and final evidence is recorded.`,parameters:K.Object({summary:K.String(),finalEvidenceRefs:K.Array(K.String()),risks:K.Optional(K.Array(K.String()))}),async execute(t,n){return Qf(e,async()=>{let t=await $f(e);if(t===null)return $(`workflow_not_initialized`);if(`corrupt`in t)return ep();let r=t,i=r.tasks.filter(e=>e.required!==!1),a=i.filter(e=>e.status!==`done`);if(a.length>0)return $(`required_tasks_not_done`,{pendingTaskIds:a.map(e=>e.id)});if(i.filter(e=>e.status===`blocked`).length>0)return $(`blocked_tasks_remain`);for(let e of i)if((e.evidenceRefs??[]).length===0)return $(`done_task_missing_evidence`,{taskId:e.id});if(n.finalEvidenceRefs.length===0)return $(`missing_final_evidence_refs`);let o=await Un(e.dataDir,e.sessionId,n.finalEvidenceRefs,Z(e));if(!o.valid)return up(o);let s=new Date().toISOString(),c={...r,status:`complete`,finalEvidenceRefs:n.finalEvidenceRefs,completedAt:s,currentTaskId:null,updatedAt:s};if(!await H(e.dataDir,e.sessionId,Z(e)))return $(`goal_not_found`);await Gn(e.dataDir,e.sessionId,c,Z(e));try{await B(e.dataDir,e.sessionId,{status:`complete`},{...Z(e),eventSource:`tool`})}catch(t){throw await Gn(e.dataDir,e.sessionId,r,Z(e)),t}return await q(e.dataDir,e.sessionId,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:n.finalEvidenceRefs,summary:n.summary,risks:n.risks??[]},Z(e)),await Jn(e.dataDir,e.sessionId,{finalSummary:n.summary,evidence:n.finalEvidenceRefs,risks:n.risks},Z(e)),Q({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,warning:gp(await Yn(e.dataDir,e.sessionId,c,Z(e)))})})}}}function Op(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:K.Object({confirm:K.Literal(!0)}),async execute(t,n){return Q(await Qf(e,()=>vn(e.dataDir,e.sessionId,Z(e))))}}}function kp(e){return[vp(e),yp(e),bp(e),xp(e),Sp(e),Cp(e),Op(e),wp(e),Tp(e),Ep(e),Dp(e)]}var Ap=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=W.resolve(e.rootDir??fi(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=_i(e.path),n=Ip(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 ji(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:pi(this.rootDir)}}async createSkill(e){let t=vi(e.name),n=_i(e.categoryPath),r=Ip(e.description,`auto-skill description`),i=Lp(e.body);await this.assertCategoryExists(n);let a=yi(n,t),o=Si(this.rootDir,n,t);if(await Pp(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=W.join(o,`SKILL.md`),l=W.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:Rp(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:zp(e.evidence,s)};return await U.mkdir(o,{recursive:!0}),await U.writeFile(c,jp(t,r,i),`utf-8`),await Fp(l,u),await ji(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=bi(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Si(this.rootDir,t.categoryPath,t.skillName),r=W.join(n,`SKILL.md`),i=W.join(n,`metadata.json`),a=await Mp(r),o=await Np(i),s=e.description===void 0?a.description:Ip(e.description,`auto-skill description`),c=e.body===void 0?a.body:Lp(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?Rp(o.tags):Rp(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:{},...zp(e.evidence,l)}};return await U.writeFile(r,jp(t.skillName,s,c),`utf-8`),await Fp(i,u),await ji(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=bi(e.skillId),n=Si(this.rootDir,t.categoryPath,t.skillName),r=W.join(n,`metadata.json`),i=W.join(n,`SKILL.md`);await U.access(i);let a=await Np(r),o=this.now().toISOString();return await Fp(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...zp(e.evidence,o)}}),await ji(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=pi(this.rootDir),t;try{t=await U.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=_i(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 U.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await Fp(pi(this.rootDir),t)}};function jp(e,t,n){return[`---`,`name: ${Bp(e)}`,`description: ${Bp(t)}`,`---`,``,n.trim(),``].join(`
82
- `)}async function Mp(e){let t=ot(await U.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function Np(e){let t;try{t=await U.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 Pp(e){try{return await U.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Fp(e,t){await U.mkdir(W.dirname(e),{recursive:!0}),await U.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function Ip(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function Lp(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 Rp(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function zp(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Bp(e){return JSON.stringify(e)}const Vp=[`create`,`update`,`archive`,`create_category`],Hp=K.Object({}),Up=K.Object({categoryPath:K.Optional(K.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:K.Optional(K.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),Wp=K.Object({query:K.String({description:`Search query for learned auto-skills.`}),limit:K.Optional(K.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),Gp=K.Object({skillId:K.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:K.Optional(K.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),Kp=K.Object({action:K.Union(Vp.map(e=>K.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:K.Optional(K.String({description:`Exact auto-skill id for update/archive.`})),name:K.Optional(K.String({description:`Auto-skill slug for create.`})),categoryPath:K.Optional(K.String({description:`Existing single-level category slug for create.`})),newCategory:K.Optional(K.Object({path:K.String({description:`New single-level category slug to create.`}),description:K.String({description:`New category description.`})})),description:K.Optional(K.String({description:`Auto-skill description for create/update.`})),tags:K.Optional(K.Array(K.String({description:`Auto-skill tag.`}))),confidence:K.Optional(K.Number({description:`Optional confidence score from 0 to 1.`})),body:K.Optional(K.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:K.Optional(K.Object({sessionId:K.String({description:`Source session id.`}),reason:K.String({description:`Why this auto-skill write is justified.`}),toolCallCount:K.Optional(K.Number({description:`Tool calls observed in source run.`})),loadedSkills:K.Optional(K.Array(K.String({description:`Skill loaded during source run.`})))}))});function qp(e){let t=new Mi({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 $p({categories:e,count:e.length,hint:`Use auto_skill_list({ categoryPath }) to list active auto-skills in a category.`})}catch(e){return $p({categories:[],count:0,error:em(e)})}}}}function Jp(e){let t=new Mi({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:Up,async execute(e,n){try{let e=await t.autoSkillList({categoryPath:n.categoryPath,recursive:n.recursive});return $p({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return $p({skills:[],count:0,error:em(e)})}}}}function Yp(e){let t=new Mi({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:Wp,async execute(e,n){try{let e=await t.autoSkillSearch({query:n.query,limit:n.limit});return $p({skills:e,count:e.length,hint:`Use auto_skill_view({ skillId }) to load the selected auto-skill.`})}catch(e){return $p({skills:[],count:0,error:em(e)})}}}}function Xp(e){let t=new Mi({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:Gp,async execute(e,n){try{return $p({...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 $p({skillId:n.skillId,error:em(e)})}}}}function Zp(e){let t=new Ap({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:Kp,async execute(e,n){try{return $p(await Qp(t,n))}catch(e){return $p({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:em(e)})}}}}async function Qp(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 $p(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function em(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const tm=2,nm=5;var rm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),J.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:ro(e.task),startedAt:e.startedAt})}complete(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`done`,n.record.result=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}fail(e,t){let n=this.entries.get(e);!n||n.record.status!==`running`||(n.record.status=`error`,n.record.error=t,n.record.endedAt=Date.now(),this.logTerminalStatus(n.record))}kill(e){let t=this.entries.get(e);return!t||t.record.status!==`running`?!1:(t.record.abortController.abort(),t.record.status=`killed`,t.record.endedAt=Date.now(),this.logTerminalStatus(t.record),!0)}killAll(e){let t=0;for(let{record:n}of this.entries.values())n.parentSessionId===e&&n.status===`running`&&(n.abortController.abort(),n.status=`killed`,n.endedAt=Date.now(),this.logTerminalStatus(n),t++);return t}list(e){return Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e).map(e=>e.record)}hasPending(e){return this.list(e).some(e=>e.status===`running`)}countActive(e){return this.list(e).filter(e=>e.status===`running`).length}async waitForAll(e){let t=Array.from(this.entries.values()).filter(t=>t.record.parentSessionId===e&&t.record.status===`running`).map(e=>e.promise);t.length>0&&await Promise.allSettled(t)}peekCompleted(e){return this.list(e).filter(e=>e.status!==`running`&&!this.announced.has(e.runId))}consumeCompleted(e){let t=this.peekCompleted(e);return this.markAnnounced(t.map(e=>e.runId)),t}markAnnounced(e){let t=Array.isArray(e)?e:[e];for(let e of t){this.announced.add(e);let t=this.entries.get(e)?.record;t&&J.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){J.info(`subagent status changed`,t);return}if(e.status===`killed`){J.warn(`subagent status changed`,t);return}J.error(`subagent status changed`,t)}};const im=K.Object({task:K.String({description:`The task description for the subagent to execute`}),label:K.Optional(K.String({description:`Optional short label to identify this subagent`})),agent:K.Optional(K.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),am=K.Object({task:K.String({description:`The task description for the subagent to execute`}),label:K.Optional(K.String({description:`Optional short label to identify this subagent`})),agent:K.Optional(K.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),om=K.Object({tasks:K.Array(im,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function sm(e){let t=e.label?`"${e.label}"`:`task: ${Je(e.task)}`;return e.status===`done`?`${t}\n\n${cm(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function cm(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 lm(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(J.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:ro(p)}),!p){let e={status:`error`,error:`task must not be empty`};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=nt(),v=new AbortController,y=t,b=Sa(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await 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 J.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}J.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let C=f({dataDir:s,sessionId:y,message:b?Oa(b,p):p,channel:c,llm:b?.model?{...l,model:b.model}:l,...d,agentPolicy:{availableAgents:d.agentPolicy?.availableAgents??[],...b?{activeAgent:b}:{}},loopDetection:u,abortSignal:v.signal,sessionPathScope:{subagent:{parentSessionId:i,parentDir:a}},subagentContext:{depth:o+1,parentSessionId:i}}).then(e=>{if(e.error){r.fail(_,e.error);return}r.complete(_,e.text||`(no output)`)}).catch(e=>{let t=e instanceof Error?e.message:String(e);r.fail(_,t)});r.register(S,C),J.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,J.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let w=sm({task:p,label:m,status:S.status,result:S.result,error:S.error});if(S.status===`done`){let e={status:`done`,childSessionId:y,runId:_,result:S.result??``};return J.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:w}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return J.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:w}],isError:!0,details:E}}function um(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:am,async execute(e,t){return lm(u,e,t)}}}function dm(e,t,n,r,i,a,o,s,c,l){let u={registry:e,parentSessionId:t,parentSessionDir:n,depth:r,dataDir:i,channel:a,llm:o,loopDetection:s,inheritedRunParams:c,spawnFn:l};return{name:`batch_subagent_spawn`,label:`Batch Spawn Subagents`,description:`Spawn multiple isolated subagent sessions from one tool call, running at most 5 subagents concurrently. Use this when the user explicitly asks for parallel subagent execution or when several independent subagent tasks should be delegated together. Each task waits for its subagent to finish; the tool returns all final subagent results in input order.`,parameters:om,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}J.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await lm(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${cm(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
89
+ `)}\n</available_skills>`}const yp=q.Object({category:q.Optional(q.String({description:`Reserved category filter field. Not used yet.`}))}),bp=q.Object({name:q.String({description:`The skill name. Use skill_list first to see available skills.`}),skillPath:q.Optional(q.String({description:`Optional explicit path to a skill directory or SKILL.md. Use this for scene skills outside the shared skills registry.`}))});function xp(e,t,n=[]){return[...n,...t,op(e)]}function Sp(e,t,n=[]){let r=xp(e,t,n);return{name:`skill_list`,label:`Skill List`,description:`List available skills with compact metadata. Use skill_load to load one.`,parameters:yp,async execute(e,t){let n=await mp(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 Cp(e){let t=xp(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:bp,async execute(r,i){let a=await _p(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 wp=q.Object({});function Tp(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:wp,async execute(r,i){let a=await H(e,t,{storeName:n});if(!a)return{content:[{type:`text`,text:JSON.stringify({goal:null,goalState:null,workflowWarning:null})}],details:{}};let o=await z(e,t,a,{storeName:n}),s=await Sn(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:{}}}}}q.Object({status:q.String({description:`Status to set. Only 'complete' is allowed.`})});function Ep(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=Ep(e.filename);if(e.kind===`memory-file`)return[`MEMORY.md`];if(e.kind===`memory-file-lower`)return[`memory.md`];if(e.kind===`memory-dir`){if(!t)return[`memory`];let e=G.basename(t).replace(/\\/g,`/`);return e.endsWith(`.md`)?[`memory/${e}`]:[]}return t?t===`MEMORY.md`||t===`memory.md`?[t]:t===`memory`?[`memory`]:t.startsWith(`memory/`)?t.endsWith(`.md`)?[t]:[`memory`]:[]:[`MEMORY.md`,`memory`]}function Op(e){let t=e.watchFactory??((e,t,n)=>K.watch(e,t,n)),n=G.join(e.dataDir,`.aimax`),r=[{target:G.join(n,`MEMORY.md`),kind:`memory-file`},{target:G.join(n,`memory.md`),kind:`memory-file-lower`},{target:G.join(n,`memory`),kind:`memory-dir`},{target:n,kind:`memory-root`}],i=[],a=new Set,o=null,s=Number.isFinite(e.debounceMs)&&(e.debounceMs??0)>0?Math.floor(e.debounceMs):1500,c=async()=>{let t=Array.from(a);if(a.clear(),t.length===0)return;let n={reason:`external-watch`,files:t,source:`memory`,sessionId:e.sessionId,providerId:e.providerId,timestamp:new Date().toISOString()};e.provider?.sync&&await e.provider.sync(`external-watch`).catch(()=>{}),e.provider?.onMemoryChanged&&await Promise.resolve(e.provider.onMemoryChanged(n)).catch(()=>{}),e.onMemoryChanged&&await Promise.resolve(e.onMemoryChanged(n)).catch(()=>{})},l=()=>{o&&clearTimeout(o),o=setTimeout(()=>{o=null,c()},s)};for(let e of r)try{let n=t(e.target,{recursive:!1},(t,n)=>{let r=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 kp(e){return e.projectDir?.trim()||G.join(e.dataDir,`workspace`)}async function Ap(e){let{runParams:t,eventDispatcher:n,hookRegistry:r}=e,{sessionId:i,hookContext:a,memoryProviderId:o,memoryPluginId:s}=e,c=kp(t),l=new Map,u=new Map,d=!1,f=async e=>{let t=Date.now(),c=Pp(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=G.join(t.dataDir,`.aimax`),m=he({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=ye({dataDir:t.dataDir,memoryDir:p,sessionId:i,sessionStoreName:t.sessionStoreName},{includeSessions:!0})}catch(e){if(!pe(e))throw e;x=e instanceof Error?e.message:String(e),g=jp(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=Op({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,Np({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 jp(e,t){return{id:`builtin-memory`,name:`Builtin Memory Provider (degraded)`,status:()=>({backend:`builtin`,provider:`builtin-memory`,workspaceDir:e,dbPath:G.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 Mp(e){let t=new Date().toISOString();return{id:e.sessionId,title:e.title,channel:e.channel,createdAt:t,updatedAt:t}}function Np(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 Pp(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 Fp(e){return kp({dataDir:e.dataDir,projectDir:e.projectDir})}function Ip(e){return Rn({dataDir:e.dataDir,workspaceDir:Fp(e),projectDir:e.projectDir})}function Lp(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}],details:{}}}function Q(e,t){return Lp({ok:!1,error:e,...t})}function Rp(e,t){return fn(e.dataDir,e.sessionId,Z(e),t)}async function zp(e){try{return await yn(e.dataDir,e.sessionId,Z(e))}catch(e){if(e instanceof ln)return{corrupt:!0};throw e}}function Bp(){return Q(`workflow_corrupt`,{repairTool:`goal_repair_workflow_state`})}const Vp={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:...`]}},Hp=/goal[/\\]state\.json|\btask\s*list\b|\btask-\d+|\b(plan|planning|planned|added|through|workflow)\b/i,Up=/[/\\]|\.(?:html|css|js|ts|tsx|jsx|json|md|txt|py|go|rs|yaml|yml|sh)\b|\bexists\b/i,Wp=/\b(npm|pnpm|yarn|cargo|go test|pytest|vitest|jest|exit code|stdout|stderr|command output|test pass|tests pass)\b/i;function Gp(e,t){let n=`${e}\n${t}`;return Hp.test(n)?`goal/state.json`:/\buser\b/i.test(n)&&/\bconfirm/i.test(n)?`user`:`model`}function Kp(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 qp(e){let t=e.trim();return Hp.test(t)?{reason:`the ref describes planning state`}:Up.test(t)?{reason:Kp(t)?`the ref describes a file artifact`:`the ref describes a file artifact but no reliable path could be extracted`}:Wp.test(t)?{reason:`the ref describes command output`}:{reason:`the ref is natural language and must be registered as evidence`}}function Jp(e){let t=e.trim();if(Hp.test(t))return{kind:`manual`,source:`goal/state.json`,summary:t.slice(0,120),content:t};if(Up.test(t)){let e=Kp(t);if(e)return{kind:`snapshot`,path:e,summary:t.slice(0,120)}}return Wp.test(t)?{kind:`exec`,command:t.includes(`npm test`)?`npm test`:`<command>`,cwd:`<workspace>`,timeoutMs:12e4}:{kind:`manual`,source:Gp(t,t),summary:t.slice(0,120),content:t}}function Yp(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=qp(e);n.push({tool:`goal_record_evidence`,reason:i.reason,args:Jp(e)})}return n}function Xp(e){let t=e.errors[0]?.code??`invalid_evidence`;return t===`unregistered_evidence_ref`?Q(t,{errors:e.errors,repairPlan:Yp(e.errors),...Vp}):Q(t,{errors:e.errors})}function Zp(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:Gp(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 Qp(e){let t=er(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 $p(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 em(e,t){return e.tasks.find(e=>e.id===t)}function tm(e){return e.tasks.some(e=>e.kind===`execution`&&e.required!==!1)}function nm(e){return e.ok===!1?e.warning:null}async function rm(e,t){await qn(e.dataDir,e.sessionId,t,Z(e));let n=nm(await Zn(e.dataDir,e.sessionId,t,Z(e)));return n?{planWarning:n}:{}}function im(e){return{name:`goal_plan_update`,label:`Goal Plan Update`,description:`Update controlled sections of goal/plan.md without changing task workflow state.`,parameters:q.Object({interpretation:q.Optional(q.String()),assumptions:q.Optional(q.Array(q.String())),openQuestions:q.Optional(q.Array(q.String())),taskPlanNotes:q.Optional(q.String())}),async execute(t,n){return Rp(e,async()=>{let t=await zp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return Bp();let r=t;await Qn(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 Xn(e.dataDir,e.sessionId,{interpretation:n.interpretation,assumptions:n.assumptions,openQuestions:n.openQuestions,taskPlanNotes:n.taskPlanNotes},Z(e)),a=await Zn(e.dataDir,e.sessionId,r,Z(e));return Lp({ok:!0,goalId:r.goalId,planMeta:i,warning:nm(a),hint:`Use goal_add_task to project executable tasks into goal/state.json.`})})}}}function am(e){return{name:`goal_task_done`,label:`Goal Task Done`,description:`Mark the current doing task done with evidence covering required acceptance criteria.`,parameters:q.Object({taskId:q.String(),summary:q.Optional(q.String()),evidenceRefs:q.Optional(q.Array(q.String())),acceptanceEvidence:q.Optional(q.Array(q.Object({criterionId:q.String(),evidenceRefs:q.Array(q.String())})))}),async execute(t,n){return Rp(e,async()=>{let t=await zp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return Bp();let r=t,i=em(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=$p(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 Gn(e.dataDir,e.sessionId,a,Z(e));if(!c.valid)return Xp(c);if(i.kind===`clarify`){if(!tm(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 Qn(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 Jn(e.dataDir,e.sessionId,Z(e));await Xn(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 rm(e,m);return Lp({ok:!0,currentTaskId:m.currentTaskId,hint:m.currentTaskId?null:`All tasks done. Call goal_complete with finalEvidenceRefs.`,warning:g??null})})}}}function om(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:q.Object({taskId:q.String(),reason:q.String(),neededInput:q.Optional(q.String()),evidenceRefs:q.Optional(q.Array(q.String()))}),async execute(t,n){return Rp(e,async()=>{let t=await zp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return Bp();let r=t,i=em(r,n.taskId);if(!i)return Q(`task_not_found`);let a=n.evidenceRefs??[];if(a.length>0){let t=await Gn(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 Qn(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 Xn(e.dataDir,e.sessionId,{risks:[s]},Z(e));let{planWarning:u}=await rm(e,l);return Lp({ok:!0,workflowStatus:`blocked`,warning:u??null})})}}}function sm(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:q.Object({title:q.String(),kind:q.Optional(q.Literal(`execution`)),required:q.Optional(q.Boolean()),acceptanceCriteria:q.Array(q.Union([q.String(),q.Object({text:q.String(),required:q.Optional(q.Boolean())})])),afterTaskId:q.Optional(q.String()),startNow:q.Optional(q.Boolean())}),async execute(t,n){return Rp(e,async()=>{let t=await zp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return Bp();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=$n(r.tasks),o=Qp(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 Qn(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 rm(e,l);return Lp({ok:!0,taskId:a,warning:u??null})})}}}function cm(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:q.Object({kind:q.Union([q.Literal(`note`),q.Literal(`manual`),q.Literal(`exec`),q.Literal(`snapshot`)]),summary:q.Optional(q.String()),content:q.Optional(q.String()),taskId:q.Optional(q.String()),source:q.Optional(q.String()),command:q.Optional(q.String()),cwd:q.Optional(q.String()),timeoutMs:q.Optional(q.Number()),path:q.Optional(q.String())}),async execute(t,n){let r=await zp(e);if(r===null)return Q(`workflow_not_initialized`);if(`corrupt`in r)return Bp();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 tr(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`?Zp(n.summary,n.content):Q(t.error):(await Qn(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)),Lp({ok:!0,evidenceRef:t.evidenceRef}))}if(n.kind===`exec`){if(!n.command?.trim())return Q(`missing_command`);let t=await nr(e.dataDir,e.sessionId,{command:n.command,cwd:n.cwd,timeoutMs:n.timeoutMs,workspaceDir:Fp(e),allowedRoots:Ip(e),baseEnv:e.baseEnv},Z(e));return`error`in t?Q(t.error):(await Qn(e.dataDir,e.sessionId,{type:`goal_command_recorded`,goalId:i.goalId,evidenceRef:t.evidenceRef,command:n.command,cwd:n.cwd??Fp(e),exitCode:t.exitCode},Z(e)),Lp({ok:!0,evidenceRef:t.evidenceRef,exitCode:t.exitCode}))}if(!n.path?.trim())return Q(`missing_path`);let a=await ir(e.dataDir,e.sessionId,{path:n.path,summary:n.summary,workspaceDir:Fp(e),allowedRoots:Ip(e)},Z(e));return`error`in a?Q(a.error):(await Qn(e.dataDir,e.sessionId,{type:`goal_snapshot_recorded`,goalId:i.goalId,evidenceRef:a.evidenceRef,path:n.path},Z(e)),Lp({ok:!0,evidenceRef:a.evidenceRef}))}}}function lm(e){return{name:`goal_complete`,label:`Goal Complete`,description:`Complete the goal after all required tasks are done and final evidence is recorded.`,parameters:q.Object({summary:q.String(),finalEvidenceRefs:q.Array(q.String()),risks:q.Optional(q.Array(q.String()))}),async execute(t,n){return Rp(e,async()=>{let t=await zp(e);if(t===null)return Q(`workflow_not_initialized`);if(`corrupt`in t)return Bp();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 Gn(e.dataDir,e.sessionId,n.finalEvidenceRefs,Z(e));if(!o.valid)return Xp(o);let s=new Date().toISOString(),c={...r,status:`complete`,finalEvidenceRefs:n.finalEvidenceRefs,completedAt:s,currentTaskId:null,updatedAt:s};if(!await H(e.dataDir,e.sessionId,Z(e)))return Q(`goal_not_found`);await qn(e.dataDir,e.sessionId,c,Z(e));try{await V(e.dataDir,e.sessionId,{status:`complete`},{...Z(e),eventSource:`tool`})}catch(t){throw await qn(e.dataDir,e.sessionId,r,Z(e)),t}return await Qn(e.dataDir,e.sessionId,{type:`goal_completed`,goalId:r.goalId,finalEvidenceRefs:n.finalEvidenceRefs,summary:n.summary,risks:n.risks??[]},Z(e)),await Xn(e.dataDir,e.sessionId,{finalSummary:n.summary,evidence:n.finalEvidenceRefs,risks:n.risks},Z(e)),Lp({ok:!0,goalStatus:`complete`,workflowStatus:`complete`,warning:nm(await Zn(e.dataDir,e.sessionId,c,Z(e)))})})}}}function um(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:q.Object({confirm:q.Literal(!0)}),async execute(t,n){return Lp(await Rp(e,()=>bn(e.dataDir,e.sessionId,Z(e))))}}}function dm(e){return[im(e),sm(e),cm(e),am(e),om(e),um(e),lm(e)]}var fm=class{rootDir;now;constructor(e){if(!e.rootDir&&!e.dataDir)throw Error(`AutoSkillStore requires either rootDir or dataDir.`);this.rootDir=G.resolve(e.rootDir??hi(e.dataDir)),this.now=e.now??(()=>new Date)}async createCategory(e){let t=bi(e.path),n=vm(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 Pi(this.rootDir),{action:`create_category`,categoryPath:t,categoriesPath:gi(this.rootDir)}}async createSkill(e){let t=xi(e.name),n=bi(e.categoryPath),r=vm(e.description,`auto-skill description`),i=ym(e.body);await this.assertCategoryExists(n);let a=Si(n,t),o=Ti(this.rootDir,n,t);if(await gm(o))throw Error(`Auto-skill already exists: ${a}`);let s=this.now().toISOString(),c=G.join(o,`SKILL.md`),l=G.join(o,`metadata.json`),u={skillId:a,status:`active`,categoryPath:n,source:`auto`,tags:bm(e.tags),relatedSkills:[],confidence:e.confidence,createdAt:s,updatedAt:s,createdFrom:e.evidence,usage:{usageCount:0,lastUsedAt:null},review:xm(e.evidence,s)};return await W.mkdir(o,{recursive:!0}),await W.writeFile(c,pm(t,r,i),`utf-8`),await _m(l,u),await Pi(this.rootDir),{action:`create`,skillId:a,categoryPath:n,skillDir:o,skillFile:c,metadataFile:l}}async updateSkill(e){let t=Ci(e.skillId);await this.assertCategoryExists(t.categoryPath);let n=Ti(this.rootDir,t.categoryPath,t.skillName),r=G.join(n,`SKILL.md`),i=G.join(n,`metadata.json`),a=await mm(r),o=await hm(i),s=e.description===void 0?a.description:vm(e.description,`auto-skill description`),c=e.body===void 0?a.body:ym(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?bm(o.tags):bm(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:{},...xm(e.evidence,l)}};return await W.writeFile(r,pm(t.skillName,s,c),`utf-8`),await _m(i,u),await Pi(this.rootDir),{action:`update`,skillId:t.skillId,categoryPath:t.categoryPath,skillDir:n,skillFile:r,metadataFile:i}}async archiveSkill(e){let t=Ci(e.skillId),n=Ti(this.rootDir,t.categoryPath,t.skillName),r=G.join(n,`metadata.json`),i=G.join(n,`SKILL.md`);await W.access(i);let a=await hm(r),o=this.now().toISOString();return await _m(r,{...a,skillId:t.skillId,status:`archived`,categoryPath:t.categoryPath,source:`auto`,updatedAt:o,review:{...typeof a.review==`object`&&a.review!==null?a.review:{},...xm(e.evidence,o)}}),await Pi(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 W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`Auto-skill categories.json must be a JSON object.`);let r={};for(let[e,t]of Object.entries(n)){let n=bi(e);if(typeof t==`string`){r[n]={description:t.trim()};continue}if(!t||typeof t!=`object`||Array.isArray(t)){r[n]={description:``};continue}let i=t;r[n]={description:typeof i.description==`string`?i.description.trim():``,createdBy:typeof i.createdBy==`string`?i.createdBy.trim():void 0}}return r}async writeCategoryRegistry(e){await W.mkdir(this.rootDir,{recursive:!0});let t={};for(let n of Object.keys(e).sort())t[n]=e[n];await _m(gi(this.rootDir),t)}};function pm(e,t,n){return[`---`,`name: ${Sm(e)}`,`description: ${Sm(t)}`,`---`,``,n.trim(),``].join(`
90
+ `)}async function mm(e){let t=ct(await W.readFile(e,`utf-8`));return{description:typeof t.data.description==`string`?t.data.description.trim():``,body:t.content.trim()}}async function hm(e){let t;try{t=await W.readFile(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return{};throw e}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`metadata.json must be a JSON object.`);return n}async function gm(e){try{return await W.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function _m(e,t){await W.mkdir(G.dirname(e),{recursive:!0}),await W.writeFile(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function vm(e,t){let n=e.trim();if(!n)throw Error(`Auto-skill ${t} cannot be empty.`);return n}function ym(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 bm(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function xm(e,t){return e?{reason:e.reason,lastReviewedAt:t}:{lastReviewedAt:t}}function Sm(e){return JSON.stringify(e)}const Cm=[`create`,`update`,`archive`,`create_category`],wm=q.Object({}),Tm=q.Object({categoryPath:q.Optional(q.String({description:`Single-level category slug from auto_skill_categories. Omit to list all active auto-skills.`})),recursive:q.Optional(q.Boolean({description:`Reserved for future nested categories. Ignored while auto-skill categories are single-level.`}))}),Em=q.Object({query:q.String({description:`Search query for learned auto-skills.`}),limit:q.Optional(q.Number({description:`Maximum number of matches to return. Defaults to 5.`}))}),Dm=q.Object({skillId:q.String({description:`Exact auto-skill id, for example auto:software-development/fix-vitest-timeout.`}),filePath:q.Optional(q.String({description:`Optional file path inside the auto-skill directory. Omit to load SKILL.md.`}))}),Om=q.Object({action:q.Union(Cm.map(e=>q.Literal(e)),{description:`Restricted review-agent write action for learned auto-skills.`}),skillId:q.Optional(q.String({description:`Exact auto-skill id for update/archive.`})),name:q.Optional(q.String({description:`Auto-skill slug for create.`})),categoryPath:q.Optional(q.String({description:`Existing single-level category slug for create.`})),newCategory:q.Optional(q.Object({path:q.String({description:`New single-level category slug to create.`}),description:q.String({description:`New category description.`})})),description:q.Optional(q.String({description:`Auto-skill description for create/update.`})),tags:q.Optional(q.Array(q.String({description:`Auto-skill tag.`}))),confidence:q.Optional(q.Number({description:`Optional confidence score from 0 to 1.`})),body:q.Optional(q.String({description:`Markdown body for create/update. Do not include frontmatter.`})),evidence:q.Optional(q.Object({sessionId:q.String({description:`Source session id.`}),reason:q.String({description:`Why this auto-skill write is justified.`}),toolCallCount:q.Optional(q.Number({description:`Tool calls observed in source run.`})),loadedSkills:q.Optional(q.Array(q.String({description:`Skill loaded during source run.`})))}))});function km(e){let t=new Fi({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:wm,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:Fm(e)})}}}}function Am(e){let t=new Fi({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:Tm,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:Fm(e)})}}}}function jm(e){let t=new Fi({dataDir:e});return{name:`auto_skill_search`,label:`Auto-Skill Search`,description:`Search active learned auto-skills when the right category is unclear.`,parameters:Em,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:Fm(e)})}}}}function Mm(e){let t=new Fi({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:Fm(e)})}}}}function Nm(e){let t=new fm({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:Om,async execute(e,n){try{return $(await Pm(t,n))}catch(e){return $({action:n.action,skillId:n.skillId,categoryPath:n.categoryPath??n.newCategory?.path,error:Fm(e)})}}}}async function Pm(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 Fm(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}const Im=2,Lm=5;var Rm=class{entries=new Map;announced=new Set;register(e,t){this.entries.set(e.runId,{record:e,promise:t}),J.info(`subagent status changed`,{runId:e.runId,status:`running`,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,taskLength:e.task.length,taskPreview:oo(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&&J.info(`subagent result announced`,{runId:t.runId,status:t.status,parentSessionId:t.parentSessionId,childSessionId:t.childSessionId,depth:t.depth,durationMs:t.endedAt?t.endedAt-t.startedAt:void 0})}}isAnnounced(e){return this.announced.has(e)}hasUnannounced(e){return this.list(e).some(e=>e.status!==`running`&&!this.announced.has(e.runId))}needsAnnounce(e){return this.hasPending(e)||this.hasUnannounced(e)}checkSpawnAllowed(e,t){return t>2?{allowed:!1,reason:`Maximum subagent depth (2) reached`}:this.countActive(e)>=5?{allowed:!1,reason:`Maximum concurrent subagents (5) reached for this session`}:{allowed:!0}}getStatus(e){return this.entries.get(e)?.record.status??null}logTerminalStatus(e){let t={runId:e.runId,status:e.status,parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,depth:e.depth,label:e.label,durationMs:e.endedAt?e.endedAt-e.startedAt:void 0,resultLength:e.result?.length,error:e.error};if(e.status===`done`){J.info(`subagent status changed`,t);return}if(e.status===`killed`){J.warn(`subagent status changed`,t);return}J.error(`subagent status changed`,t)}};const zm=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),Bm=q.Object({task:q.String({description:`The task description for the subagent to execute`}),label:q.Optional(q.String({description:`Optional short label to identify this subagent`})),agent:q.Optional(q.String({description:`Optional custom agent name to use for this subagent. Must exactly match one of the names listed in the Custom Agents prompt section; do not guess or invent names.`}))}),Vm=q.Object({tasks:q.Array(zm,{description:`Tasks to run as subagents. The tool runs at most 5 at the same time.`})});function Hm(e){let t=e.label?`"${e.label}"`:`task: ${Xe(e.task)}`;return e.status===`done`?`${t}\n\n${Um(e.result??`(no output)`)}`:e.status===`error`?`${t}\n\nError: ${e.error??`unknown error`}`:`${t}\n\nStopped.`}function Um(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 Wm(e,t,n){let{registry:r,parentSessionId:i,parentSessionDir:a,depth:o,dataDir:s,channel:c,llm:l,loopDetection:u,inheritedRunParams:d,spawnFn:f}=e,p=n.task.trim(),m=n.label?.trim(),h=n.agent?.trim();if(J.info(`subagent spawn requested`,{parentSessionId:i,depth:o+1,label:m,requestedAgentName:h,taskLength:p.length,taskPreview:oo(p)}),!p){let e={status:`error`,error:`task must not be empty`};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let g=r.checkSpawnAllowed(i,o+1);if(!g.allowed){let e={status:`forbidden`,error:g.reason};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let _=it(),v=new AbortController,y=t,b=Ta(d.agentPolicy?.availableAgents??[],h);if(h&&!b){let e={status:`error`,error:`Unknown custom agent: ${h}`};return J.warn(`subagent spawn rejected`,{parentSessionId:i,depth:o+1,requestedAgentName:h,reason:e.error}),{content:[{type:`text`,text:JSON.stringify(e)}],details:e}}let x={parentSessionId:i,parentDir:a};try{await 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 J.error(`subagent session creation failed`,{parentSessionId:i,depth:o+1,error:t.error}),{content:[{type:`text`,text:JSON.stringify(t)}],details:t}}J.info(`subagent session created`,{parentSessionId:i,childSessionId:y,depth:o+1,runId:_,requestedAgentName:h,selectedAgent:b?.name});let S={runId:_,childSessionId:y,parentSessionId:i,task:p,label:m,depth:o+1,status:`running`,startedAt:Date.now(),abortController:v};await d.onProgress?.({type:`subagent_spawn`,childSessionId:y,task:p,label:m,sessionId:i,messageId:d.messageId,depth:o+1});let C=f({dataDir:s,sessionId:y,message:b?ja(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),J.info(`subagent run registered`,{runId:_,parentSessionId:i,childSessionId:y,depth:o+1,selectedAgent:b?.name}),await C,J.info(`subagent run settled`,{runId:_,parentSessionId:i,childSessionId:y,status:S.status,durationMs:S.endedAt?S.endedAt-S.startedAt:void 0,hasError:!!S.error}),r.markAnnounced(_),await d.onProgress?.({type:`subagent_complete`,childSessionId:y,task:p,status:S.status,sessionId:i,messageId:d.messageId,depth:o+1});let w=Hm({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 J.info(`subagent spawn completed`,{runId:_,parentSessionId:i,childSessionId:y,status:e.status,resultLength:e.result.length}),{content:[{type:`text`,text:w}],details:e}}let E=S.status===`killed`?{status:`killed`,childSessionId:y,runId:_,error:`subagent killed`}:{status:`error`,childSessionId:y,runId:_,error:S.error??`unknown error`};return J.warn(`subagent spawn completed with non-success status`,{runId:_,parentSessionId:i,childSessionId:y,status:E.status,error:E.error}),{content:[{type:`text`,text:w}],isError:!0,details:E}}function Gm(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:Bm,async execute(e,t){return Wm(u,e,t)}}}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:`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:Vm,async execute(n,i){let a=i.tasks??[];if(a.length===0){let e={status:`error`,results:[]};return{content:[{type:`text`,text:JSON.stringify({...e,error:`tasks must not be empty`})}],isError:!0,details:e}}J.info(`batch subagent spawn requested`,{parentSessionId:t,depth:r+1,taskCount:a.length,concurrencyLimit:5});let o=Array(a.length),s=0,c=Math.max(0,5-e.countActive(t)),l=Math.min(5,c,a.length);if(l===0){let n=e.checkSpawnAllowed(t,r+1),i=n.allowed?`Maximum concurrent subagents (5) reached for this session`:n.reason;for(let[e,t]of a.entries())o[e]={status:`forbidden`,error:i,index:e,task:t.task.trim(),label:t.label?.trim()}}else{let e=async()=>{for(;s<a.length;){let e=s++,t=a[e];o[e]={...(await Wm(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${Um(e.result)}`:`- ${t}: ${e.status}\n${e.error}`})].join(`
83
91
 
84
- `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const fm=K.Object({action:K.Union([`list`,`kill`].map(e=>K.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:K.Optional(K.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function pm(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 mm(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 hm(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:fm,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} (${pm(e.runtimeMs)})${n}`})).join(`
85
- `)};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=mm(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 gm=K.Object({image:K.String({description:`Image path or URL`}),prompt:K.Optional(K.String({description:`Prompt for image analysis`})),model:K.Optional(K.String({description:`Optional model override`})),maxBytesMb:K.Optional(K.Number({description:`Optional size cap in MB`}))});function _m(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:gm,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}const vm=K.Object({reason:K.String({description:`A brief explanation of why user input is needed through this UI form.`})});function ym(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??vm,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=Ze(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new yo(e,i,t,e,o,s,n);throw Oo(r),r}}}function bm(e,t){let n=Gf({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??nn(),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=[Lu({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),Vu({registry:i,scopeKey:n}),Ju(n,t?.contextManager),Xu(n,t?.contextManager,s),Qu(n,t?.contextManager,s),ed(n),sd(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[zf(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),Vf(e,t.sessionId,t.inheritedRunParams?.sessionStoreName,t.eventDispatcher,t.sessionId),...kp({dataDir:e,sessionId:t.sessionId,sessionStoreName:t.inheritedRunParams?.sessionStoreName,projectDir:t.inheritedRunParams?.projectDir,baseEnv:t.baseEnv})]:[],Nd(e,r),tf(e,r),Fd(e,r),zd(e,r),qd(e,r),Yd(e,r),Zd(e,r),$d(e,r),If(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Lf({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(qp(e),Jp(e),Yp(e),Xp(e)),t&&c.push(um(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),dm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),hm(t.registry,t.parentSessionId)),c}function xm(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(`
92
+ `);return f===`done`?{content:[{type:`text`,text:m}],details:p}:{content:[{type:`text`,text:m}],isError:!0,details:p}}}}const qm=q.Object({action:q.Union([`list`,`kill`].map(e=>q.Literal(e)),{description:`Action to perform: "list" to show subagents, "kill" to stop one or all`}),target:q.Optional(q.String({description:`For kill: a runId, label, or index from the list. Use "*" or "all" to kill every subagent.`}))});function Jm(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 Ym(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 Xm(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:qm,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} (${Jm(e.runtimeMs)})${n}`})).join(`
93
+ `)};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=Ym(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 Zm=q.Object({image:q.String({description:`Image path or URL`}),prompt:q.Optional(q.String({description:`Prompt for image analysis`})),model:q.Optional(q.String({description:`Optional model override`})),maxBytesMb:q.Optional(q.Number({description:`Optional size cap in MB`}))});function Qm(){return{name:`image`,label:`Image`,description:`Analyze an image with the configured image model. (Not implemented in AIMax yet.)`,parameters:Zm,async execute(e,t){let n={implemented:!1,error:`image tool not implemented (awaiting third-party integration).`};return{content:[{type:`text`,text:`Error: ${n.error}`}],details:n}}}}const $m=q.Object({reason:q.String({description:`A brief explanation of why user input is needed through this UI form.`})});function eh(e){let{name:t,label:n,description:r,sessionId:i,inputSchema:a,outputSchema:o,extra:s,validate:c,resume:l}=e;return{name:t,label:n,description:r,parameters:a??$m,async execute(e,n){if(l&&l.toolCallId===e&&l.toolName===t&&l.sessionId===i){let e=$e(o,l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(c){let e=await c(l.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:l.values})}],details:{}}}let r=new rs(e,i,t,e,o,s,n);throw fs(r),r}}}function th(e,t){let n=kp({dataDir:e,projectDir:t?.inheritedRunParams?.projectDir}),r=t?.memoryOptions,i=t?.processRegistry??an(),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=[Cd({sessionId:t?.sessionId,workspaceDir:n,registry:i,scopeKey:n,contextManager:t?.contextManager,hitlResume:t?.hitlResume,baseEnv:t?.baseEnv}),Dd({registry:i,scopeKey:n}),Pd(n,t?.contextManager),Id(n,t?.contextManager,s),Rd(n,t?.contextManager,s),Bd(n),qd(n,{sessionId:t?.sessionId,hitlResume:t?.hitlResume,artifactRecorder:s}),...t?.sessionId?[Tp(e,t.sessionId,t.inheritedRunParams?.sessionStoreName),...dm({dataDir:e,sessionId:t.sessionId,sessionStoreName:t.inheritedRunParams?.sessionStoreName,projectDir:t.inheritedRunParams?.projectDir,baseEnv:t.baseEnv})]:[],bf(e,r),Hf(e,r),Sf(e,r),Ef(e,r),Pf(e,r),If(e,r),Rf(e,r),Bf(e,r),Sp(e,t?.pluginSkillDirs??[],t?.skillsLoadPaths??[]),Cp({dataDir:e,pluginDirs:t?.pluginSkillDirs??[],skillsLoadPaths:t?.skillsLoadPaths??[],sessionId:t?.sessionId??`unknown`,reportSkillUsed:t?.reportSkillUsed})];return a&&c.push(km(e),Am(e),jm(e),Mm(e)),t&&c.push(Gm(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Km(t.registry,t.parentSessionId,t.currentSessionDir,t.depth,e,t.channel,t.llm,t.loopDetection,t.inheritedRunParams??{},t.spawnFn),Xm(t.registry,t.parentSessionId)),c}function nh(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
94
  `),`</auto_skill_categories>`,``].join(`
87
- `)}const Sm={get_goal:`Get the current thread goal including status, budget, usage, and workflow summary`,update_goal:`Legacy completion tool; V2-lite goals must use goal_complete with evidence refs`,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`},Cm=[`read_file`,`write_file`,`edit_file`,`list_dir`,`apply_patch`,`exec`,`process`,`skill_list`,`skill_load`,`get_goal`,`update_goal`,`auto_skill_categories`,`auto_skill_list`,`auto_skill_search`,`auto_skill_view`,`memory_search`,`memory_get`,`memory_write`,`memory_log`,`memory_list`,`memory_forget`,`memory_update`,`session_search`,`subagent_spawn`,`subagents`];function wm(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:[...Cm.filter(e=>t.has(e)),...n.filter(e=>!Cm.includes(e)).sort()],displayName:t}}function Tm(e){let{ordered:t,displayName:n}=wm(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)??Sm[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
95
+ `)}const rh={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`},ih=`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 ah(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:[...ih.filter(e=>t.has(e)),...n.filter(e=>!ih.includes(e)).sort()],displayName:t}}function oh(e){let{ordered:t,displayName:n}=ah(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)??rh[e];return i?`- ${t}: ${i}`:`- ${t}`}).join(`
88
96
  `),``].join(`
89
- `)}function Em(){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).","- Do NOT call `update_goal(complete)` to bypass workflow evidence gates.","- Do NOT call `update_goal(complete)` or `goal_complete` merely because the budget is nearly exhausted or work is paused.",`- Audit your progress against the objective before declaring completion. Check file state, test results, and any defined acceptance criteria.`,"- If no goal exists, `get_goal` returns null and `update_goal` reports an error.",``].join(`
90
- `)}function Dm(){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(`
91
- `)}function Om(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
92
- `)}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(`
93
- `)}function Am(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(`
97
+ `)}function sh(){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(`
98
+ `)}function ch(){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(`
99
+ `)}function lh(){return[`## Language`,`Preferred response language: Simplified Chinese (简体中文). Use another language only when the user, higher-priority instructions, or task context explicitly requires it.`,``].join(`
100
+ `)}function uh(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(`
101
+ `)}function dh(){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(`
102
+ `)}function fh(e){return e.length===0?``:[`## Skills (mandatory)`,`Before replying: scan <available_skills> <description> entries.`,"- If exactly one skill clearly applies: call `skill_load(name=<skill-name>)` for it, then follow it.","- If multiple could apply: choose the most specific one, then call `skill_load(name=<skill-name>)`.",`- If none clearly apply: do not load any skill.`,`Constraints: never load more than one skill up front.`,"The `skill_load` tool returns only the skill's `SKILL.md` entrypoint.","If that `SKILL.md` references scripts, templates, references, or assets, read those files later with normal file tools using paths relative to the skill directory.",`Skill content visibility:`,`- Loading a skill once does not guarantee its SKILL.md remains visible after context compaction.`,"- If you need to use a skill and the complete SKILL.md content is not currently visible in the prompt, call `skill_load` again.",`- If a prior tool result says the skill content was folded, persisted, snipped, microcompacted, collapsed, or summarized, treat the skill instructions as unavailable.`,"- If the current <available_skills> <version> or <skill_file_mtime> differs from a prior `skill_load` result for the same skill, call `skill_load` again before using that skill.","- If a prior `skill_load` result lacks `version` or `skillFileMtime`, treat its SKILL.md as stale unless the complete current SKILL.md content is visibly present.",`- Prefer reloading the skill over guessing. Re-read the skill as many times as needed; do not reconstruct instructions from memory or summaries.`,`<available_skills>\n${e.map(e=>[` <skill>`,` <name>${e.name}</name>`,` <description>${e.description}</description>`,` <location>${e.location}</location>`,` <version>${e.version}</version>`,` <skill_file_mtime>${e.skillFileMtime}</skill_file_mtime>`,` </skill>`].join(`
94
103
  `)).join(`
95
104
  `)}\n</available_skills>`,``].join(`
96
- `)}function jm(e=[]){let t=xm(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(`
97
- `)}function Nm(){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(`
98
- `)}function Pm(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(`
99
- `)}function Fm(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(`
100
- `)}function Im(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(`
101
- `)}function Lm(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=Rm(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
102
- `)}function Rm(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 zm(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(`
103
- `)}function Bm(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(`
104
- `)}function Vm(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(`
105
- `)}function Hm(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(`
106
- `)}function Um(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(`
107
- `)}function Wm(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(`
108
- `):``}function Gm(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:[...Cm],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Um(e.subagentDepth??0),Tm({toolNames:i,toolSummaries:e.toolSummaries}),km(n),Em(),Dm(),Da(e.availableAgents??[]),Am(a),jm(e.autoSkillCategories),Mm(),Nm(),Pm(e.memoryCitationsMode??`off`),Fm({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),Im(e.sandboxInfo),Lm({currentDate:e.currentDate,timezone:e.timezone}),Om(),zm({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Vm({isMinimal:n}),Bm(e.runtimeInfo),Hm({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Wm(e.priorConversationSummary)].filter(Boolean).join(`
109
- `)}const Km=Symbol(`pluginToolOwner`);var qm=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,Km,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=ym({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,Km,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Jm(e){return e[Km]}function Ym(e,t,n){return e.map(e=>{let r=e,i=Jm(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await Fa({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(vo(e))return wo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function Xm(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 Zm(e,t){let n=e.content,r=th(e.details),i=e.isError;for(let e of t)if(e){if(e.content!==void 0&&(n=Qm(n,e.content)),e.details!==void 0){let t=th(e.details);r={...r,...t}}e.isError===!0&&(i=!0)}return{content:n,details:r,isError:i}}function Qm(e,t){return t===void 0?e:e===void 0?t:Array.isArray(e)&&Array.isArray(t)?$m(e,t)?t:[...e,...t]:t}function $m(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!eh(e[n],t[n]))return!1;return!0}function eh(e,t){return JSON.stringify(e)===JSON.stringify(t)}function th(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function nh(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),vo(t))return wo(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=Xm(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(vo(e))return wo(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}let f=Zm({content:a.content,details:u,isError:s},d),p=Math.max(0,Date.now()-l),m=f.isError?rh(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 rh(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(`
110
- `):void 0}var ih=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 ah={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function oh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function sh(e){let t=oh(e?.warningThreshold,ah.warningThreshold),n=oh(e?.criticalThreshold,ah.criticalThreshold),r=oh(e?.globalCircuitBreakerThreshold,ah.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??ah.enabled,historySize:oh(e?.historySize,ah.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??ah.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??ah.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??ah.detectors.pingPong}}}function ch(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function lh(e,t){return`${e}:${fh(t)}`}function uh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(uh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${uh(t[e])}`).join(`,`)}}`}function dh(e){try{return uh(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 fh(e){let t=dh(e);return et(`sha256`).update(t).digest(`hex`)}function ph(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 mh(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(`
111
- `).trim()}function hh(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:uh(e)}function gh(e,t,n,r){if(r!==void 0)return`error:${fh(hh(r))}`;if(!ch(n))return n===void 0?void 0:fh(n);let i=ch(n.details)?n.details:{},a=mh(n);if(ph(e,t)&&e===`process`&&ch(t)){let e=t.action;if(e===`poll`)return fh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return fh({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 fh({details:i,text:a})}function _h(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 vh(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 yh(e,t){return[e,t].toSorted().join(`|`)}function bh(e,t,n,r){let i=sh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=lh(t,n),s=_h(a,t,o),c=s.count,l=ph(t,n),u=vh(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:${yh(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 xh(e,t,n,r,i){let a=sh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:lh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function Sh(e,t){let n=sh(t.config),r=gh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=lh(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 Ch(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 wh(e){return e&&e.trim()||`tool`}function Th(e,t,n){if(!e.execute)return e;let r=wh(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=bh(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);Ch(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}xh(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return Sh(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw Sh(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function Eh(e,t,n){return e.map(e=>Th(e,t,n))}const Dh=new Map;function Oh(e){let t=Dh.get(e);return t||(t={},Dh.set(e,t)),t}function kh(e){Dh.delete(e)}function Ah(e){let t=e.streamFn??vt;return(e,n,r)=>(e.api===`anthropic-messages`&&jh(e),t(e,n,{...r,...Rh(e,r)}))}function jh(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>Ph(Lh(e),n)?(globalThis.fetch=t,Mh(await t(e,Fh(e,r)))):t(e,r))}function Mh(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(`
112
-
113
- `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(Nh))),a.enqueue(r.encode(e+`
114
-
115
- `))}},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 Nh=`event: message_start
105
+ `)}function ph(e=[]){let t=nh(e).trim();return t?`${t}\n`:``}function mh(){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(`
106
+ `)}function hh(){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(`
107
+ `)}function gh(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(`
108
+ `)}function _h(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(`
109
+ `)}function vh(e){if(!e?.enabled)return``;let t=[`## Sandbox`,`You are running in a containerized cloud CLI runtime.`];return e.containerWorkspaceDir?.trim()&&t.push(`Container workdir: ${e.containerWorkspaceDir.trim()}`),e.hostWorkspaceDir?.trim()&&t.push(`Host-mounted workspace: ${e.hostWorkspaceDir.trim()}`),t.push(``),t.join(`
110
+ `)}function yh(e){let t=[];if(e.timezone&&t.push(`Time zone: ${e.timezone}`),e.currentDate){t.push(`Current date: ${e.currentDate}`);let n=bh(e.currentDate);n&&t.push(`Day of week: ${n}`)}return t.length===0?``:[`## Current Date & Time`,...t,``].join(`
111
+ `)}function bh(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 xh(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(`
112
+ `)}function Sh(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(`
113
+ `)}function Ch(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(`
114
+ `)}function wh(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(`
115
+ `)}function Th(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(`
116
+ `)}function Eh(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(`
117
+ `):``}function Dh(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:[...ih],a=e.skills??[],o=e.contextFiles??[];return[`${r}\n`,Th(e.subagentDepth??0),oh({toolNames:i,toolSummaries:e.toolSummaries}),dh(),uh(n),sh(),ch(),Aa(e.availableAgents??[]),fh(a),ph(e.autoSkillCategories),mh(),hh(),gh(e.memoryCitationsMode??`off`),_h({dataDir:e.dataDir,projectDir:e.projectDir,sandboxInfo:e.sandboxInfo}),vh(e.sandboxInfo),yh({currentDate:e.currentDate,timezone:e.timezone}),lh(),xh({isMinimal:n,enabled:e.messaging?.enabled,channels:e.messaging?.channels}),Ch({isMinimal:n}),Sh(e.runtimeInfo),wh({contextFiles:o,bootstrapWarnings:e.bootstrapWarnings}),Eh(e.priorConversationSummary)].filter(Boolean).join(`
118
+ `)}const Oh=Symbol(`pluginToolOwner`);var kh=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,Oh,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=eh({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,Oh,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Ah(e){return e[Oh]}function jh(e,t,n){return e.map(e=>{let r=e,i=Ah(e);return{...r,async execute(e,a,o,s){let c=t.toolParamOverrides?t.toolParamOverrides.consume(e,a):a,l=async e=>i?await Ra({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(ns(e))return cs(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}}}})}function Mh(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 Nh(e,t){let n=e.content,r=Lh(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=Lh(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)?Fh(e,t)?t:[...e,...t]:t}function Fh(e,t){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(!Ih(e[n],t[n]))return!1;return!0}function Ih(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Lh(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function Rh(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),ns(t))return cs(t),{block:!0,reason:t.message};throw t}let{blocked:u,blockReason:d,mergedParams:f}=Mh(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(ns(e))return cs(e),{content:[{type:`text`,text:e.message}],isError:!0,details:{}};throw e}let f=Nh({content:a.content,details:u,isError:s},d),p=Math.max(0,Date.now()-l),m=f.isError?zh(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 zh(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(`
119
+ `):void 0}var Bh=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 Vh={enabled:!1,historySize:30,warningThreshold:10,criticalThreshold:20,globalCircuitBreakerThreshold:30,detectors:{genericRepeat:!0,knownPollNoProgress:!0,pingPong:!0}};function Hh(e,t){return typeof e!=`number`||!Number.isInteger(e)||e<=0?t:e}function Uh(e){let t=Hh(e?.warningThreshold,Vh.warningThreshold),n=Hh(e?.criticalThreshold,Vh.criticalThreshold),r=Hh(e?.globalCircuitBreakerThreshold,Vh.globalCircuitBreakerThreshold);return n<=t&&(n=t+1),r<=n&&(r=n+1),{enabled:e?.enabled??Vh.enabled,historySize:Hh(e?.historySize,Vh.historySize),warningThreshold:t,criticalThreshold:n,globalCircuitBreakerThreshold:r,detectors:{genericRepeat:e?.detectors?.genericRepeat??Vh.detectors.genericRepeat,knownPollNoProgress:e?.detectors?.knownPollNoProgress??Vh.detectors.knownPollNoProgress,pingPong:e?.detectors?.pingPong??Vh.detectors.pingPong}}}function Wh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Gh(e,t){return`${e}:${Jh(t)}`}function Kh(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Kh).join(`,`)}]`;let t=e;return`{${Object.keys(t).toSorted().map(e=>`${JSON.stringify(e)}:${Kh(t[e])}`).join(`,`)}}`}function qh(e){try{return Kh(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 Jh(e){let t=qh(e);return nt(`sha256`).update(t).digest(`hex`)}function Yh(e,t){if(e===`command_status`)return!0;if(e!==`process`||!Wh(t))return!1;let n=t.action;return n===`poll`||n===`log`}function Xh(e){return!Wh(e)||!Array.isArray(e.content)?``:e.content.filter(e=>Wh(e)&&typeof e.type==`string`&&typeof e.text==`string`).map(e=>e.text).join(`
120
+ `).trim()}function Zh(e){return e instanceof Error?e.message||e.name:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?`${e}`:Kh(e)}function Qh(e,t,n,r){if(r!==void 0)return`error:${Jh(Zh(r))}`;if(!Wh(n))return n===void 0?void 0:Jh(n);let i=Wh(n.details)?n.details:{},a=Xh(n);if(Yh(e,t)&&e===`process`&&Wh(t)){let e=t.action;if(e===`poll`)return Jh({action:e,status:i.status,exitCode:i.exitCode??null,exitSignal:i.exitSignal??null,aggregated:i.aggregated??null,text:a});if(e===`log`)return Jh({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 Jh({details:i,text:a})}function $h(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 eg(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 tg(e,t){return[e,t].toSorted().join(`|`)}function ng(e,t,n,r){let i=Uh(r);if(!i.enabled)return{stuck:!1};let a=e.toolCallHistory??[],o=Gh(t,n),s=$h(a,t,o),c=s.count,l=Yh(t,n),u=eg(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:${tg(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 rg(e,t,n,r,i){let a=Uh(i);e.toolCallHistory||=[],e.toolCallHistory.push({toolName:t,argsHash:Gh(t,n),toolCallId:r,timestamp:Date.now()}),e.toolCallHistory.length>a.historySize&&e.toolCallHistory.shift()}function ig(e,t){let n=Uh(t.config),r=Qh(t.toolName,t.toolParams,t.result,t.error);if(!r)return;e.toolCallHistory||=[];let i=Gh(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 ag(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 og(e){return e&&e.trim()||`tool`}function sg(e,t,n){if(!e.execute)return e;let r=og(e.name),i=e.execute.bind(e);return{...e,execute:async(e,a,o,s)=>{let c=n(t.sessionId),l=ng(c,r,a,t.config);if(l.stuck){if(l.level===`critical`)throw Error(l.message);ag(c,l.warningKey??`${l.detector}:${r}`,l.count)&&t.onWarning?.(l)}rg(c,r,a,e,t.config);try{let n=await i(e,a,o,s);return ig(c,{toolName:r,toolParams:a,toolCallId:e,result:n,config:t.config}),n}catch(n){throw ig(c,{toolName:r,toolParams:a,toolCallId:e,error:n,config:t.config}),n}}}}function cg(e,t,n){return e.map(e=>sg(e,t,n))}const lg=new Map;function ug(e){let t=lg.get(e);return t||(t={},lg.set(e,t)),t}function dg(e){lg.delete(e)}function fg(e){let t=e.streamFn??bt;return(e,n,r)=>(e.api===`anthropic-messages`&&pg(e),t(e,n,{...r,...bg(e,r)}))}function pg(e){let t=globalThis.fetch,n=String(e.baseUrl??``).replace(/\/+$/,``);globalThis.fetch=(async(e,r)=>gg(yg(e),n)?(globalThis.fetch=t,mg(await t(e,_g(e,r)))):t(e,r))}function mg(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(`
121
+
122
+ `))!==-1;){let e=n.slice(0,o);n=n.slice(o+2),t||(t=!0,e.includes(`event: message_start`)||a.enqueue(r.encode(hg))),a.enqueue(r.encode(e+`
123
+
124
+ `))}},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 hg=`event: message_start
116
125
  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}}}
117
126
 
118
- `;function Ph(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function Fh(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))Ih(e)&&n.delete(e);return{...t,headers:n}}function Ih(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 Lh(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function Rh(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}async function zh(e){let{session:{runParams:t,sessionId:n,hookRegistry: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=Rs(t.llm),D=await Tu({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 Eu({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 Hh({sessionId:n,historyResult:O,runContext:o,eventDispatcher:s,hookRegistry:i,hookContext:a});let k=t.subagentContext?.depth??0,A=r(t.dataDir,n,X(t)),j=nn(),M=Ea([...bm(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),ee={};for(let e of M){let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.description==`string`?e.description.trim():``;!t||!n||ee[t]||(ee[t]=n)}let P=t.messaging?.enabled??t.channel!==`CRON`,I=t.messaging?.channels&&t.messaging.channels.length>0?t.messaging.channels:[t.channel],L=Gm({dataDir:t.dataDir,projectDir:t.projectDir,skills:Ta(u,S),autoSkillCategories:x?d:[],contextFiles:c,toolNames:N,toolSummaries:ee,promptMode:k>0?`minimal`:`full`,subagentDepth:k,bootstrapWarnings:l,memoryCitationsMode:t.memory?.citationsMode??`off`,messaging:{enabled:P,channels:I},sandboxInfo:{enabled:!0,hostWorkspaceDir:o.workspaceDir,containerWorkspaceDir:o.workspaceDir},runtimeInfo:{os:process.platform,node:process.version,model:t.llm.model,hostname:rt.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});L=await Vh({systemPrompt:L,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let R={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},te=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:L,systemPromptOptions:R},a,{eventDispatcher:s}),z=await i.dispatch(`before_prompt_build`,{prompt:f},a,{eventDispatcher:s});z.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 ne=[];for(let e of te){if(!e)continue;let t=e;t.systemPrompt&&(L=t.systemPrompt),t.prependContext&&(L=`${t.prependContext}\n\n${L}`),t.message&&ne.push(t.message)}for(let e of z){if(!e)continue;let t=e;t.systemPrompt&&(L=t.systemPrompt),t.prependContext&&(L=`${t.prependContext}\n\n${L}`)}await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:L},a,{eventDispatcher:s});let B=Eh(Ym(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},Oh),V=S?.model??t.llm.model,re=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of re)e&&e.modelOverride&&(V=e.modelOverride);let ie=y({...t.llm,model:V},n,t.messageId,t.channel);try{await As(t.dataDir,n,{systemPrompt:L,tools:B},X(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let H=new st({initialState:{systemPrompt:L,model:ie,tools:B,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:Ah({})}),ae={eventDispatcher:s};a.signal=b;let oe=new ih;return a.toolParamOverrides=oe,nh({agent:H,hookRegistry:i,hookContext:a,pluginRuntime:ae,overrideStore:oe}),O.messages.length>0&&(H.state.messages=O.messages),ne.length>0&&(H.state.messages=[...ne,...H.state.messages]),{agent:H,resolvedModelId:V,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function Bh(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 Vh(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 Hh(e){let{sessionId:t,historyResult:n,runContext:r,eventDispatcher:i,hookRegistry:a,hookContext:o}=e;for(let e of n.compactionEvents??[])e.type===`compaction`&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:e.reason,details:{layer:e.layer,strategy:e.strategy,estimatedTokensFreed:e.estimatedTokensFreed,affectedEntries:e.affectedEntries,snapshotVersion:e.snapshotVersion}});if(n.compactionEntry){let e=n.stats.originalCount-n.stats.keptCount,s=Uh(await a.dispatch(`before_compaction`,{messageCount:n.stats.originalCount,compactingCount:e},o,{eventDispatcher:i})),c=s.injectRecall?{...n.compactionEntry,content:`${s.injectRecall.trim()}\n\n${n.compactionEntry.content}`}:n.compactionEntry;if(s.skipPersist){await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Compaction output was skipped by plugin hook`,details:{compactedCount:e,injectedRecall:!!s.injectRecall}});return}await r.appendTranscriptEntry(c),(n.compactionEvents?.length??0)===0&&await i.dispatchDiagnostic(t,{level:`info`,scope:`session`,phase:`history_compaction`,message:`Summarised ${e} older entries`,details:{strategy:`summary_only`,compactedCount:e}}),await a.dispatch(`after_compaction`,{messageCount:n.stats.originalCount,compactedCount:e},o,{eventDispatcher:i})}}function Uh(e){let t=!1,n=[];for(let r of e)r&&(r.skipPersist&&(t=!0),typeof r.injectRecall==`string`&&r.injectRecall.trim().length>0&&n.push(r.injectRecall.trim()));return{skipPersist:t,injectRecall:n.length>0?n.join(`
127
+ `;function gg(e,t){return!!t&&e.startsWith(t)&&e.includes(`/v1/messages`)}function _g(e,t){let n=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));for(let e of Array.from(n.keys()))vg(e)&&n.delete(e);return{...t,headers:n}}function vg(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 yg(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function bg(e,t){return e.api===`anthropic-messages`?{cacheRetention:`none`,headers:{...t?.headers??{},"anthropic-beta":null,"anthropic-dangerous-direct-browser-access":null}}:{}}function xg(e,t=.3){return e.length===0?!0:e.every(e=>e.score<t)}function Sg(e){return Math.ceil(e.length/4)}function Cg(e,t){if(Sg(e)<=t)return e;let n=t*4;return`${e.slice(0,Math.max(0,n-3)).trimEnd()}...`}async function wg(e){let t=e.query.trim();if(!t)return{};let n=await e.provider.search(t),r=e.coreConfig?.knowledgeController?.scoreThreshold,i=xg(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:Cg(o.join(`
128
+ `),a),blockId:`core-recall-${Date.now()}`,isWeakLocalRecall:i}}function Tg(e,t){return`${t.trim()}\n\n${e}`}function Eg(e,t){let n=`${t.trim()}\n\n`;return e.startsWith(n)?e.slice(n.length):e}const Dg=`<!-- AIMax compaction memory recall -->`;async function Og(e){if(e.coreConfig?.compactionRecall?.enabled!==!0)return;let t=e.query.trim();if(t)try{let n=await wg({provider:e.provider,query:t,coreConfig:{...e.coreConfig,recall:{...e.coreConfig.recall,enabled:!0,tokenBudget:e.coreConfig.compactionRecall?.tokenBudget??e.coreConfig.recall?.tokenBudget}}});return n.block?`${Dg}\n\n${n.block.replace(`${Dg}\n\n`,``).trim()}`:void 0}catch{return}}async function kg(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=Sc(t.llm),D=await dd({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 fd({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 Mg({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=an(),M=ka([...th(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=Dh({dataDir:t.dataDir,projectDir:t.projectDir,skills:Oa(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:at.hostname()},currentDate:new Date().toISOString().split(`T`)[0],presetSystemPrompt:g,activeAgentSystemPrompt:S?.systemPrompt,availableAgents:t.subagentContext?[]:t.agentPolicy?.availableAgents??[],priorConversationSummary:O.priorSummary});L=await jg({systemPrompt:L,dataDir:t.dataDir,sessionId:n,sessionStoreName:t.sessionStoreName});let R,te=t.memory?.core,z=te?.recall?.enabled===!0,B=!!t.subagentContext,V=o.memoryProviderSource===`plugin`&&te?.recall?.forceWithPluginProvider!==!0;if(z&&!B&&!V&&!o.recallState.recallProvided)try{let e=await wg({provider:o.memoryProvider,query:f,coreConfig:te}),t=te?.knowledgeController;if(t?.enabled===!0&&t?.searchMode===`fallback`&&(e.isWeakLocalRecall===!0||!e.block))try{let e=await(await import(`./kc-DVYWmNeY.js`)).runKcFallbackSearch({config:t,query:f});e.block&&(R&&(L=Eg(L,R)),R=e.block,L=Tg(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=Tg(L,R),o.recallState={recallProvided:!0,source:`core`,blockId:e.blockId})}catch(e){await s.dispatchDiagnostic(n,{level:`warn`,scope:`memory`,phase:`core_recall_failed`,message:`core recall step failed`,details:{error:e instanceof Error?e.message:String(e)}}).catch(()=>{})}let ne={selectedTools:N,toolSnippets:[],promptGuidelines:[],contextFiles:c,skills:u,cwd:o.workspaceDir},re=await i.dispatch(`before_agent_start`,{prompt:f,systemPrompt:L,systemPromptOptions:ne,recallState:o.recallState},a,{eventDispatcher:s}),ie=await i.dispatchWithMetadata(`before_prompt_build`,{prompt:f,recallState:o.recallState},a,{eventDispatcher:s});ie.length>0&&console.warn(`[AgentRuntime] before_prompt_build hook(s) fired; this hook is deprecated in favor of before_agent_start. Migrate plugins to before_agent_start.`);let H=[];for(let e of re){if(!e)continue;let t=e;if(t.recall?.block?.trim()){R&&=(L=Eg(L,R),void 0),L=Tg(L,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}t.systemPrompt&&(L=t.systemPrompt),t.prependContext&&(L=`${t.prependContext}\n\n${L}`),t.message&&H.push(t.message)}for(let e of ie){if(!e.result)continue;let t=e.result;if(t.recall?.block?.trim()){R&&=(L=Eg(L,R),void 0),L=Tg(L,t.recall.block.trim()),o.recallState={recallProvided:!0,source:`plugin`};continue}if(t.systemPrompt&&(L=t.systemPrompt),t.prependContext){if((e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&o.recallState.recallProvided)continue;L=`${t.prependContext}\n\n${L}`,(e.pluginId===o.memoryPluginId||e.pluginId===o.memoryProviderId)&&(o.recallState={recallProvided:!0,source:`plugin`})}}await i.dispatch(`after_prompt_build`,{prompt:f,systemPrompt:L},a,{eventDispatcher:s});let ae=cg(jh(M,a,{eventDispatcher:s}),{sessionId:n,config:t.loopDetection},ug),U=S?.model??t.llm.model,oe=await i.dispatch(`before_model_resolve`,{prompt:f},a,{eventDispatcher:s});for(let e of oe)e&&e.modelOverride&&(U=e.modelOverride);let se=y({...t.llm,model:U},n,t.messageId,t.channel);try{await mc(t.dataDir,n,{systemPrompt:L,tools:ae},X(t))}catch(e){console.warn(`[AgentRuntime] failed to persist export snapshots for session ${n}:`,e.message)}let ce=new lt({initialState:{systemPrompt:L,model:se,tools:ae,messages:[],...t.llm.thinking?{thinkingLevel:t.llm.thinking}:{}},getApiKey:e=>t.llm.apiKey,streamFn:fg({})}),le={eventDispatcher:s};a.signal=b;let ue=new Bh;return a.toolParamOverrides=ue,Rh({agent:ce,hookRegistry:i,hookContext:a,pluginRuntime:le,overrideStore:ue}),O.messages.length>0&&(ce.state.messages=O.messages),H.length>0&&(ce.state.messages=[...H,...ce.state.messages]),{agent:ce,resolvedModelId:U,historyMessages:O.messages,historyResult:O,contextManager:D,usageBaselineTranscriptEntryCount:w.length,workspaceDir:o.workspaceDir,processRegistry:j}}async function Ag(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 jg(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 Mg(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=Ng(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 Og({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 Ng(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(`
119
129
 
120
- `):void 0}}function Wh(e){return e.some(e=>qh(e.message)!==null||e.toolResults.length>0)}function Gh(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 Kh(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 qh(e){let t=$h(e),n=Jh(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 Jh(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function Yh(e){return e.map(e=>Jh(e.message)).filter(e=>e.trim().length>0).join(`
130
+ `):void 0,pluginRecallProvided:r}}function Pg(e){return e.some(e=>Lg(e.message)!==null||e.toolResults.length>0)}function Fg(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 Ig(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 Lg(e){let t=Ug(e),n=Rg(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 Rg(e){return e.content.filter(e=>e.type===`thinking`&&typeof e.thinking==`string`).map(e=>e.thinking).join(``)}function zg(e){return e.map(e=>Rg(e.message)).filter(e=>e.trim().length>0).join(`
121
131
 
122
- `)}function Xh(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Zh(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 Qh(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:eg(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function $h(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function eg(e){let t=e.indexOf(`
132
+ `)}function Bg(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function Vg(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 Hg(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:Wg(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function Ug(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Wg(e){let t=e.indexOf(`
123
133
  Preview:
124
- `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function tg(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,onTurnRecordProduced:f}=e,p=``,m=``,h=``,g=0,_=0,v,y,b=0,x=0,S=[],C=new Map,w=new Map,T=new Set,E=So(),D=Eo(),O=new Set,k=Promise.resolve(),A,j=0,M=0,N={eventDispatcher:s},ee=e=>{O.add(e),e.catch(e=>{A??=e}).finally(()=>{O.delete(e)})},P=async()=>{for(;O.size>0;)await Promise.allSettled([...O]);if(A)throw A},F=t.subscribe(e=>{let t=k.then(()=>I(e));k=t.catch(()=>{}),ee(t)});async function I(e){let n=()=>!!D.signal||E.signal?.transparentPause===!0;if(e.type===`agent_start`){c.dispatch(`agent_start`,{turnIndex:j},l,N).catch(()=>{});return}if(e.type===`turn_start`){M=j,j+=1,c.dispatch(`turn_start`,{turnIndex:M,timestamp:Date.now()},l,N).catch(()=>{});return}if(e.type===`message_update`){let t=e.assistantMessageEvent;if(x===0&&(t.type===`text_delta`||t.type===`done`)&&(x=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=mg(`partial`in t?t.partial:void 0)??mg(`message`in t?t.message:void 0)??mg(`message`in e?e.message:void 0),a=hg(t.delta,r,m);r?(m=r,h=r):a&&(h+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){p=``,m=``,h=``,e.usage&&(g=e.usage.input,_=e.usage.output);return}p=$h(e);let r=hg(``,p,h||m);m=p,h=p,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(g=e.usage.input,_=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(g=t.usage.input,_=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=$h(e);!p&&n&&(p=n),await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:b>0?Math.max(0,Date.now()-b):void 0,usage:t.usage?{input:g,output:_,total:g+_}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(y=og(t));let r=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:Qh(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),a=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),o=new Set(r.map(e=>e.toolCallId));for(let e of w.values())!o.has(e.toolCallId)&&a.has(e.toolCallId)&&r.push(e);for(let e of r)w.delete(e.toolCallId);if(S.push({message:t,toolResults:r}),f&&!n){let e=!!E.signal,n=!!D.signal;if(e&&E.signal.transparentPause||await f(Xh(qh(t),e||n),n?[]:r.map(Zh)),e||n)return}await c.dispatch(`turn_end`,{turnIndex:M,message:t,toolResults:r},l,N);return}if(e.type===`tool_execution_start`){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}}),h=``,C.set(e.toolCallId,e.args),E.signal?.transparentPause!==!0&&!T.has(e.toolCallId)&&(T.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=pg(e.result),r=fg(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Qh(r,i,e.toolCallId,e.toolName),c=C.get(e.toolCallId);if(C.delete(e.toolCallId),E.signal?.transparentPause===!0){t.abort();return}if(D.signal){T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}w.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),T.has(e.toolCallId)||(T.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.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 L=us(d),R=L.enabled?L.maxAttempts:1;try{ng({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=R;e++){let d=S.length;y=void 0,v=void 0,j=0,M=0;try{await Bh({agent:t,hookRegistry:c,hookContext:l,pluginRuntime:N});let f=await c.dispatch(`before_provider_request`,{model:a,messages:t.state.messages,tools:t.state.tools},l,N);for(let e of f)if(e){if(e.abort)return await P(),{text:p,inputTokens:g,outputTokens:_,error:v,turnRecords:S};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`);J.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),b=Date.now(),await Co(E,async()=>{await Do(D,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await P();let m=E.signal;if(m)throw m;let h=D.signal;if(h)throw h;let x=S.some(e=>e.message.content.some(e=>e.type===`toolCall`||e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0));!y&&S.length>0&&!x&&p.trim().length===0&&(J.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,turnRecordCount:S.length}),y={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let C=t.state,w=typeof C.error==`string`?C.error:typeof C.errorMessage==`string`?C.errorMessage:void 0,T=y??w;if(T){let t=y?`sdk`:`agent_state`;if(v=gg(T),J.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,error:v,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:S.length-d,...Vo(T,`providerError`)}),await z(T,v,e,d))continue;await ne(v,T),await s.dispatchProgress(i,{type:`error`,message:v})}v||J.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,inputTokens:g,outputTokens:_,turnRecordCount:S.length-d,textLength:p.length});break}catch(t){if(await P(),vo(t)||bo(t))throw t;if(v=gg(t),J.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:R,error:v}),await z(t,v,e,d))continue;await ne(v,t),await s.dispatchProgress(i,{type:`error`,message:v});break}}}finally{F()}function te(){p=``,m=``,h=``}async function z(e,n,r,a){if(!ag({error:e,attempt:r,maxAttempts:R,turnRecords:S,attemptTurnRecordStart:a,finalAssistantText:p,streamedAssistantSnapshot:m,streamedTextSinceBoundary:h}))return!1;let o=ds(r,L);return J.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:R,delayMs:o,error:n}),await lg({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:R,message:n,delayMs:o}),S.length=a,te(),ug(t),await fs(o,u),!0}async function ne(e,t){f&&await f(Gh(e,t),[])}let B=S.length>0?S[S.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:p?[p]:[],lastAssistant:B,durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:{input:g,output:_,total:g+_}},l);let V=(D.signal?``:S.length>0?$h(S[S.length-1].message):``)||p||Kh(S,`subagent_spawn`);if(E.signal)throw E.signal;if(D.signal)throw D.signal;if(f&&!Wh(S)&&!v&&p.trim().length>0){let e=Yh(S);await f({role:`assistant`,content:p,...e?{thinking:e}:{},timestamp:new Date().toISOString()},[])}return{text:V,inputTokens:g,outputTokens:_,error:v,turnRecords:S}}function ng(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:rg(a,e.message),s=ig(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=Zo(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 rg(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function ig(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 ag(e){return e.attempt>=e.maxAttempts||!ps(e.error)||e.finalAssistantText.trim().length>0||e.streamedAssistantSnapshot.trim().length>0||e.streamedTextSinceBoundary.trim().length>0?!1:e.turnRecords.slice(e.attemptTurnRecordStart).every(e=>e.toolResults.length===0&&$h(e.message).trim().length===0)}function og(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:sg(t.errorCode),statusCode:cg(t.statusCode),providerCode:sg(t.providerCode),providerType:sg(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function sg(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function cg(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function lg(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 ug(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&dg(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function dg(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function fg(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return pg(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):pg(e)}function pg(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function mg(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 hg(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function gg(e){let t=_g(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 _g(e){if(e instanceof ao)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:sg(t.code),statusCode:cg(t.statusCode),statusText:sg(t.statusText),providerMessage:sg(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 vg(e){let t=wg(e.toolResultPreviewChars),n=Tg(e.systemPrompt,e.agentDefinition),r=Dg(e.model,e.agentDefinition),i=Ea(e.tools??[],e.agentDefinition),a=Eg(e.message,e.agentDefinition),o=await tg({agent:new st({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:yg({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new Ra,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:xg(o.turnRecords),toolResults:Sg(o.turnRecords,t)}}function yg(e){let t=e.phasePrefix??`silent_agent`;return new io({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await bg(e.diagnosticDispatcher,t,n)}})}async function bg(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 xg(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 Sg(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Cg(e.content,t)})))}function Cg(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function wg(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 Tg(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
134
+ `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}async function Gg(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=os(),O=us(),k=new ko,A={workspaceDir:l.workspaceDir},j=new Set,M=Promise.resolve(),N,P=0,ee=0,F={eventDispatcher:s},I=e=>{j.add(e),e.catch(e=>{N??=e}).finally(()=>{j.delete(e)})},L=async()=>{for(;j.size>0;)await Promise.allSettled([...j]);if(N)throw N},R=t.subscribe(e=>{let t=M.then(()=>te(e));M=t.catch(()=>{}),I(t)});async function te(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`agent_start`){c.dispatch(`agent_start`,{turnIndex:P},l,F).catch(()=>{});return}if(e.type===`turn_start`){ee=P,P+=1,c.dispatch(`turn_start`,{turnIndex:ee,timestamp:Date.now()},l,F).catch(()=>{});return}if(e.type===`message_update`){let t=e.assistantMessageEvent;if(S===0&&(t.type===`text_delta`||t.type===`done`)&&(S=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=o_(`partial`in t?t.partial:void 0)??o_(`message`in t?t.message:void 0)??o_(`message`in e?e.message:void 0),a=s_(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=Ug(e);let r=s_(``,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=Ug(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=Zg(t));let r=So(Ug(t),A);n||(r.artifacts.length>0&&p?.addOwn(r.artifacts),await oe(r.warnings));let a=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:Hg(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=Bg(Lg(t),e||n);i&&!e&&!n&&(i.content=r.cleanedText);let o=n?[]:a.map(Vg);(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=a_(e.result),r=i_(e.result);p?.addChild(Kg(e.toolName,e.result));let a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:Hg(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),p?.addInferred(jo({toolName:e.toolName,input:c,result:e.result,isError:!!e.isError,workspaceDir:l.workspaceDir})),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchDiagnostic(i,{level:`info`,scope:`tool`,phase:`tool_call_completed`,message:`tool call completed`,details:{toolCallId:e.toolCallId,toolName:e.toolName,input:c,output:n,isError:e.isError,...o?{toolResultRef:o}:{}}}),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let z=Js(d),B=z.enabled?z.maxAttempts:1;try{qg({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=B;e++){let d=C.length;b=void 0,y=void 0,P=0,ee=0;try{await Ag({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`);J.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),x=Date.now(),await ss(D,async()=>{await ds(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&&(J.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,turnRecordCount:C.length}),b={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let S=t.state,w=typeof S.error==`string`?S.error:typeof S.errorMessage==`string`?S.errorMessage:void 0,T=b??w;if(T){let t=b?`sdk`:`agent_state`;if(y=c_(T),J.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y,errorSource:t,abortSignalAborted:!!u?.aborted,turnRecordCount:C.length-d,...Ts(T,`providerError`)}),await ne(T,y,e,d))continue;await re(y,T),await s.dispatchProgress(i,{type:`error`,message:y})}y||J.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await L(),ns(t)||is(t))throw t;if(y=c_(t),J.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:B,error:y}),await ne(t,y,e,d))continue;await re(y,t),await s.dispatchProgress(i,{type:`error`,message:y});break}}}finally{R()}function V(){m=``,h=``,g=``}async function ne(e,n,r,a){if(!Xg({error:e,attempt:r,maxAttempts:B,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g}))return!1;let o=Ys(r,z);return J.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:B,delayMs:o,error:n}),await e_({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:B,message:n,delayMs:o}),C.length=a,V(),t_(t),await Xs(o,u),!0}async function re(e,t){f&&await f(Fg(e,t),[])}let ie=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:ie,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let H=O.signal?``:C.length>0?So(Ug(C[C.length-1].message),A).cleanedText:``,ae=So(m,A).cleanedText,U=H||ae||Ig(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=So(m,A);e.artifacts.length>0&&p?.addOwn(e.artifacts),await oe(e.warnings);let t=zg(C);await f({role:`assistant`,content:e.cleanedText,...t?{thinking:t}:{},timestamp:new Date().toISOString()},[])}return{text:U,inputTokens:_,outputTokens:v,error:y,turnRecords:C};async function oe(e){for(let t of e)await s.dispatchDiagnostic(i,{level:`warn`,scope:`runner`,phase:`artifact_parse`,message:t})}}function Kg(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 qg(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:Jg(a,e.message),s=Yg(t?.tools);try{let t=r&&r!==`off`?{reasoningEffort:r}:void 0,a=Fs(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 Jg(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function Yg(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 Xg(e){return e.attempt>=e.maxAttempts||!Zs(e.error)||e.finalAssistantText.trim().length>0||e.streamedAssistantSnapshot.trim().length>0||e.streamedTextSinceBoundary.trim().length>0?!1:e.turnRecords.slice(e.attemptTurnRecordStart).every(e=>e.toolResults.length===0&&Ug(e.message).trim().length===0)}function Zg(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:Qg(t.errorCode),statusCode:$g(t.statusCode),providerCode:Qg(t.providerCode),providerType:Qg(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function Qg(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function $g(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function e_(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 t_(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&n_(n[n.length-1]);)n.pop();n.length!==t.messages.length&&(e.state.messages=n)}function n_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`?t.stopReason===`error`||t.stopReason===`aborted`?!0:r_(t.content):!1}function r_(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 i_(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return a_(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):a_(e)}function a_(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return t===void 0?String(e):t}function o_(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 s_(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function c_(e){let t=l_(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 l_(e){if(e instanceof co)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:Qg(t.code),statusCode:$g(t.statusCode),statusText:Qg(t.statusText),providerMessage:Qg(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 u_(e){let t=g_(e.toolResultPreviewChars),n=__(e.systemPrompt,e.agentDefinition),r=y_(e.model,e.agentDefinition),i=ka(e.tools??[],e.agentDefinition),a=v_(e.message,e.agentDefinition),o=await Gg({agent:new lt({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:d_({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new Va,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:p_(o.turnRecords),toolResults:m_(o.turnRecords,t)}}function d_(e){let t=e.phasePrefix??`silent_agent`;return new so({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await f_(e.diagnosticDispatcher,t,n)}})}async function f_(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 p_(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 m_(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:h_(e.content,t)})))}function h_(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function g_(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 __(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
135
+
136
+ `)}function v_(e,t){return!t?.initPrompt||typeof e!=`string`?e:ja(t,e)}function y_(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const b_=q.Object({kind:q.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>q.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:q.Optional(q.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:q.Optional(q.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:q.Optional(q.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:q.Optional(q.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function x_(e){let t=Yr({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??Wr}),n={storeName:e.storeName};return{name:`auto_skill_review_context_view`,label:`Auto-Skill Review Context`,description:`Internal read-only review tool for controlled access to the current session transcript and persisted tool-result evidence. Only use inside the auto-skill review agent.`,parameters:b_,async execute(r,i){try{return i.kind===`tool_result`?C_(await Jr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?C_(await Gr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?C_(await Kr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?C_({...await qr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):C_(await qr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:S_(i),limits:t}))}catch(r){return C_({kind:i.kind,error:w_(r),limits:t,contextFiles:Zr(e.dataDir,e.sessionId,n)})}}}}function S_(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 C_(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function w_(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function T_(e){let t=[Am(e.dataDir),jm(e.dataDir),Mm(e.dataDir),x_({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(Nm(e.dataDir)),t}const E_=`auto-skill-reviewer`;async function D_(e){let t=e.createModel??ha,n=e.tools??T_({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 u_({sessionId:e.sessionId,systemPrompt:O_(e.mode),message:k_(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=A_(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 O_(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(`
137
+ `)}function k_(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(`
138
+ `)}function A_(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=j_(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 j_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const M_=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],N_=M_,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}},F_=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function I_(e){let t=R_(e.gates),n={session:B_(`session`,e.sessionTranscript,t.session),currentRun:B_(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:B_(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=W_(e.reviewState?.reviewCount,0),i=W_(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return K_(n,a,r,i,o,`run_error`);if(e.result?.paused)return K_(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return K_(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return K_(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 L_(e,t={}){let n=Pr(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??M_),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(q_(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}J_(t)&&Y_(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 R_(e){return{session:z_(e?e.session:P_.session),currentRun:z_(e?e.currentRun:P_.currentRun),reviewWindow:z_(e?e.reviewWindow:P_.reviewWindow)}}function z_(e){let t={};for(let n of F_){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?N_:void 0;if(typeof r==`number`){let e=U_(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=U_(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:G_(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:G_(r.toolNames,i)})}return t}function B_(e,t,n){let r=L_(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=F_.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];V_(t,o,r)?i.push({code:t,description:H_(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 V_(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 H_(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 U_(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function W_(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function G_(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function K_(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 q_(e){return e.role===`assistant`}function J_(e){return e.role===`tool_result`}function Y_(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:X_(e.content)?.success===!1}function X_(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}function Z_(e){let t=Ir(e.transcript.length,e.transcriptStartIndex),n=Lr(e.transcript.length,e.recentEntryLimit),r=Ir(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Ir(e.transcript.length,0),a=Rr(e.transcript,t),o=Rr(e.transcript,r),s=L_(e.transcript),c=L_(a),l=L_(o),u=Nr(e.transcript),d=Nr(a),f=Nr(o),p=a.filter($_),m=a.filter(ev);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:Q_(p[0]?.content??``,800),finalResponse:Q_(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:Fr(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 Q_(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function $_(e){return e.role===`user`}function ev(e){return e.role===`assistant`}function tv(e,t,n){return G.join(r(e,t,n),`auto-skill-review-state.json`)}function nv(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function rv(e,t,n){let r=tv(e,t,n),i;try{i=await W.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return nv(t);throw e}return cv(JSON.parse(i),t)}async function iv(e,t,n){let r=tv(e,t.sessionId,n);await W.mkdir(G.dirname(r),{recursive:!0}),await W.writeFile(r,`${JSON.stringify(cv(t,t.sessionId),null,2)}\n`,`utf-8`)}async function av(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await iv(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function ov(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 iv(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function sv(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await iv(e.dataDir,t,{storeName:e.sessionStoreName}),t}function cv(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:dv(n.reviewCount,0),lastAttemptedReviewAt:lv(n.lastAttemptedReviewAt),lastCompletedReviewAt:lv(n.lastCompletedReviewAt),lastFailedReviewAt:lv(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:uv(n.lastReviewedTranscriptEndIndex)}}function lv(e){return typeof e==`string`&&e.trim()?e:null}function uv(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function dv(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function fv(e){return G.join(hi(e),`.reviews`,`run-log.jsonl`)}async function pv(e,t){let n=fv(e);await W.mkdir(G.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await W.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const mv=`write`,hv=new Set([`off`,`gate`,`dry_run`,`write`]);async function gv(e){let t=_v(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=yv(e);if(n){await Cv(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=bv(n,e.transcriptStartIndex),o=await rv(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=xv(o.lastReviewedTranscriptEndIndex,n.length),c=bv(n,s);await wv(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=I_({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await wv(e,`auto_skill_review_gate_evaluation_completed`,`auto-skill review gate evaluation completed`,{mode:t.mode,worthReview:l.worthReview,selectedGateScope:l.selectedGateScope,skipReason:l.skipReason}),!l.worthReview){await Tv(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await wv(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new Fi({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=Z_({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:Zr(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await wv(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await Tv(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(E_);if(!p){J.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:E_}),await Cv(e,t,`reviewer_agent_missing`,{reviewerAgentName:E_});return}i={mode:f,decision:l,packet:d},r=await av({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??D_,h=T_({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 sv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await Ev(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await Sv(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:Dv(g.toolCalls),toolResults:Pv(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await ov({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await Ev(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:Nv(g.text,2e3),toolCalls:Dv(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 sv({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await Ev(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await Sv(e,n,a?{reviewRunLogPath:a}:void 0)}}function _v(e){return{mode:vv(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function vv(e){if(e==null)return mv;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?hv.has(t)?t:`off`:mv}function yv(e){if(e.runParams.subagentContext)return`subagent`;if(e.runParams.channel===`CRON`)return`cron`;if(e.result.error)return`run_error`;if(e.result.paused)return`hitl_paused`;if(e.result.uiToolPending)return`ui_tool_pending`}function bv(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function xv(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function Sv(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 Cv(e,t,n,r={}){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:n===`run_error`?`warn`:`info`,scope:`skill`,phase:`auto_skill_review_skipped`,message:n===`reviewer_agent_missing`?`auto-skill review skipped because reviewer agent is missing`:`auto-skill review skipped before gate evaluation`,details:{mode:t.mode,reason:n,...r}})}async function wv(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function Tv(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:Mv(n),...i.packet?{packet:i.packet}:{}}})}async function Ev(e,t,n){return pv(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?kv(n.curatorResult.text):void 0,conclusionText:n.curatorResult?Av(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?Dv(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 Dv(e){return e.map(e=>({...e,arguments:Ov(e.name,e.arguments)}))}function Ov(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 kv(e){let t=jv(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function Av(e){return kv(e)?void 0:Nv(e,8e3)}function jv(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 Mv(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 Nv(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 Fv=!1;function Iv(){Fv||=(yt(),vt({api:`openai-completions`,stream:Ns,streamSimple:Ps}),!0)}const Lv=[`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(`
139
+ `);async function Rv(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o,onFallback:s}=e,c=t.trim().replace(/\s+/g,` `);if(!c)return`New session`;if(!r.flashModel)return Uv(c);let l=Uv(c),u=r.flashModel,d=lo({apiFormat:r.apiFormat,baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:u,hooks:a,hookCtx:o}),f=[{role:`user`,content:c}];n&&f.push({role:`assistant`,content:n});let p=Bv(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await d.chat({system:Lv,user:JSON.stringify(f),temperature:0,maxTokens:100,signal:p.signal})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(Vv(t)){if(p.didTimeout())return s?.(`timeout`),l;throw t}e<3&&await zv(500*e,p.signal)}}catch(e){if(Vv(e)&&p.didTimeout())return s?.(`timeout`),l;throw e}finally{p.clear()}return s?.(`error`),l}function zv(e,t){return t?t.aborted?Promise.reject(Hv()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(Hv())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function Bv(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 Vv(e){return e instanceof Error&&e.name===`AbortError`}function Hv(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function Uv(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 Wv(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 Gv(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await Jv(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 Kv(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 qv(e){await Gv(e),await Kv(e)}async function Jv(e,t){return e.map(e=>({...e}))}function Yv(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(`
125
140
 
126
- `)}function Eg(e,t){return!t?.initPrompt||typeof e!=`string`?e:Oa(t,e)}function Dg(e,t){let n=t?.model?.trim();return n?{...e,id:n,name:n}:e}const Og=K.Object({kind:K.Union([`current_run`,`recent_conversation`,`review_window`,`transcript_range`,`tool_result`].map(e=>K.Literal(e)),{description:`Controlled review evidence kind to read.`}),startIndex:K.Optional(K.Number({description:`Inclusive zero-based transcript entry index. Required for transcript_range.`})),endIndex:K.Optional(K.Number({description:`Exclusive zero-based transcript entry index. Required for transcript_range.`})),toolCallId:K.Optional(K.String({description:`Tool call id for a persisted tool result referenced by this session.`})),storagePath:K.Optional(K.String({description:`Exact referenced storagePath for a persisted tool result. Must already appear in transcript/context.`}))});function kg(e){let t=Kr({maxEntries:e.maxEntries??80,maxBytes:e.maxBytes??Vr}),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:Og,async execute(r,i){try{return i.kind===`tool_result`?jg(await Gr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,toolCallId:i.toolCallId,storagePath:i.storagePath,limits:t})):i.kind===`current_run`?jg(await Hr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.currentRunRange,limits:t})):i.kind===`recent_conversation`?jg(await Ur({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.recentRange,limits:t})):i.kind===`review_window`?jg({...await Wr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:e.reviewWindowRange,limits:t}),kind:`review_window`}):jg(await Wr({dataDir:e.dataDir,sessionId:e.sessionId,sessionOptions:n,range:Ag(i),limits:t}))}catch(r){return jg({kind:i.kind,error:Mg(r),limits:t,contextFiles:Jr(e.dataDir,e.sessionId,n)})}}}}function Ag(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 jg(e){return{content:[{type:`text`,text:JSON.stringify({success:!e.error,...e})}],details:e}}function Mg(e){return e instanceof Error&&e.message.trim()?e.message:String(e)}function Ng(e){let t=[Jp(e.dataDir),Yp(e.dataDir),Xp(e.dataDir),kg({dataDir:e.dataDir,sessionId:e.sessionId,storeName:e.sessionStoreName,currentRunRange:e.currentRunRange,recentRange:e.recentRange,reviewWindowRange:e.reviewWindowRange})];return e.mode===`write`&&t.push(Zp(e.dataDir)),t}const Pg=`auto-skill-reviewer`;async function Fg(e){let t=e.createModel??fa,n=e.tools??Ng({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 vg({sessionId:e.sessionId,systemPrompt:Ig(e.mode),message:Lg(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=Rg(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 Ig(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(`
127
- `)}function Lg(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(`
128
- `)}function Rg(e){return e.filter(e=>e.toolName===`auto_skill_manage`).map(e=>{let t=zg(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 zg(e){try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}catch{return}}const Bg=[`write_file`,`edit_file`,`apply_patch`,`exec`,`process`,`memory_write`,`memory_log`,`memory_update`,`memory_forget`],Vg=Bg,Hg={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}},Ug=[`tool_call_volume`,`tool_diversity`,`state_changing_tools`,`tool_errors`,`multi_turn`];function Wg(e){let t=Kg(e.gates),n={session:Jg(`session`,e.sessionTranscript,t.session),currentRun:Jg(`currentRun`,e.currentRunTranscript,t.currentRun),reviewWindow:Jg(`reviewWindow`,e.reviewWindowTranscript,t.reviewWindow)},r=Qg(e.reviewState?.reviewCount,0),i=Qg(e.maxReviewsPerSession,1),a=r===0?[`session`,`currentRun`]:[`reviewWindow`,`currentRun`],o=n.currentRun.stats;if(e.result?.error)return e_(n,a,r,i,o,`run_error`);if(e.result?.paused)return e_(n,a,r,i,o,`hitl_paused`);if(e.result?.uiToolPending)return e_(n,a,r,i,o,`ui_tool_pending`);if(r>=i)return e_(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 Gg(e,t={}){let n=jr(e),r=new Set,i=new Set,a=new Set(t.stateChangingToolNames??Bg),o=new Set,s=0,c=0,l=0;for(let t of e){if(t.role===`user`){l+=1;continue}if(t_(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}n_(t)&&r_(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 Kg(e){return{session:qg(e?e.session:Hg.session),currentRun:qg(e?e.currentRun:Hg.currentRun),reviewWindow:qg(e?e.reviewWindow:Hg.reviewWindow)}}function qg(e){let t={};for(let n of Ug){let r=e?.[n];if(r===void 0)continue;let i=n===`state_changing_tools`?Vg:void 0;if(typeof r==`number`){let e=Zg(r);if(e===void 0)continue;t[n]={enabled:!0,min:e,toolNames:i?[...i]:void 0};continue}let a=r.enabled??!0,o=Zg(r.min);if(!a){t[n]={enabled:!1,min:o??0,toolNames:$g(r.toolNames,i)};continue}o!==void 0&&(t[n]={enabled:a,min:o,toolNames:$g(r.toolNames,i)})}return t}function Jg(e,t,n){let r=Gg(t,{stateChangingToolNames:n.state_changing_tools?.toolNames}),i=[],a=[],o=Ug.filter(e=>n[e]?.enabled!==!1&&n[e]);for(let t of o){let o=n[t];Yg(t,o,r)?i.push({code:t,description:Xg(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 Yg(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 Xg(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 Zg(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function Qg(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function $g(e,t){return e?Array.from(new Set(e.map(e=>e.trim()).filter(e=>e.length>0))).sort():t?[...t]:void 0}function e_(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 t_(e){return e.role===`assistant`}function n_(e){return e.role===`tool_result`}function r_(e){return e.toolName!==`skill_load`&&e.toolName!==`auto_skill_view`?!1:e.isError?!0:i_(e.content)?.success===!1}function i_(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=Nr(e.transcript.length,e.transcriptStartIndex),n=Pr(e.transcript.length,e.recentEntryLimit),r=Nr(e.transcript.length,e.reviewWindowStartIndex??void 0),i=Nr(e.transcript.length,0),a=Fr(e.transcript,t),o=Fr(e.transcript,r),s=Gg(e.transcript),c=Gg(a),l=Gg(o),u=Ar(e.transcript),d=Ar(a),f=Ar(o),p=a.filter(s_),m=a.filter(c_);return{sessionId:e.sessionId,transcriptStartIndex:t.startIndex,userRequest:o_(p[0]?.content??``,800),finalResponse:o_(e.result.text||m.at(-1)?.content||``,800),contextFiles:e.contextFiles,currentRunRange:t,recentRange:n,reviewWindowRange:r,sessionStats:u,currentRunStats:d,reviewWindowStats:f,session:{transcriptRange:i,stats:u,toolStats:s},currentRun:{transcriptRange:t,stats:d,toolStats:c},reviewWindow:{transcriptRange:r,stats:f,toolStats:l},reviewState:{reviewCount:e.reviewState?.reviewCount??0,lastCompletedReviewAt:e.reviewState?.lastCompletedReviewAt??null,lastReviewedTranscriptEndIndex:e.reviewState?.lastReviewedTranscriptEndIndex??null},transcriptSummary:{entryCount:d.totalEntryCount,userTurnCount:d.userTurnCount,assistantTurnCount:d.assistantTurnCount,toolResultCount:d.toolResultCount},toolStats:c,loadedSkills:c.loadedSkills,viewedAutoSkills:c.viewedAutoSkills,failedTools:Mr(a,{limit:8,maxPreviewChars:400}).map(e=>({toolName:e.toolName,preview:e.preview})),activeCategories:(e.activeCategories??[]).map(e=>({path:e.path,description:e.description}))}}function o_(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function s_(e){return e.role===`user`}function c_(e){return e.role===`assistant`}function l_(e,t,n){return W.join(r(e,t,n),`auto-skill-review-state.json`)}function u_(e){return{version:1,sessionId:e,reviewCount:0,lastAttemptedReviewAt:null,lastCompletedReviewAt:null,lastFailedReviewAt:null,lastReviewedTranscriptEndIndex:null}}async function d_(e,t,n){let r=l_(e,t,n),i;try{i=await U.readFile(r,`utf-8`)}catch(e){if(e.code===`ENOENT`)return u_(t);throw e}return g_(JSON.parse(i),t)}async function f_(e,t,n){let r=l_(e,t.sessionId,n);await U.mkdir(W.dirname(r),{recursive:!0}),await U.writeFile(r,`${JSON.stringify(g_(t,t.sessionId),null,2)}\n`,`utf-8`)}async function p_(e){let t={...e.state,sessionId:e.sessionId,lastAttemptedReviewAt:e.attemptedAt??new Date().toISOString()};return await f_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function m_(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 f_(e.dataDir,t,{storeName:e.sessionStoreName}),t}async function h_(e){let t={...e.state,sessionId:e.sessionId,lastFailedReviewAt:e.failedAt??new Date().toISOString()};return await f_(e.dataDir,t,{storeName:e.sessionStoreName}),t}function g_(e,t){let n=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{version:1,sessionId:t,reviewCount:y_(n.reviewCount,0),lastAttemptedReviewAt:__(n.lastAttemptedReviewAt),lastCompletedReviewAt:__(n.lastCompletedReviewAt),lastFailedReviewAt:__(n.lastFailedReviewAt),lastReviewedTranscriptEndIndex:v_(n.lastReviewedTranscriptEndIndex)}}function __(e){return typeof e==`string`&&e.trim()?e:null}function v_(e){return typeof e!=`number`||!Number.isFinite(e)?null:Math.max(0,Math.floor(e))}function y_(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:Math.max(0,Math.floor(e))}function b_(e){return W.join(fi(e),`.reviews`,`run-log.jsonl`)}async function x_(e,t){let n=b_(e);await U.mkdir(W.dirname(n),{recursive:!0});let r={...t,version:1,createdAt:t.createdAt??new Date().toISOString()};return await U.appendFile(n,`${JSON.stringify(r)}\n`,`utf-8`),n}const S_=`write`,C_=new Set([`off`,`gate`,`dry_run`,`write`]);async function w_(e){let t=T_(e.runParams.autoSkills?.review);if(t.mode===`off`)return;let n=D_(e);if(n){await j_(e,t,n);return}let r,i;try{let n=await F(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),a=O_(n,e.transcriptStartIndex),o=await d_(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),s=k_(o.lastReviewedTranscriptEndIndex,n.length),c=O_(n,s);await M_(e,`auto_skill_review_gate_evaluation_started`,`auto-skill review gate evaluation started`,{mode:t.mode});let l=Wg({sessionId:e.sessionId,sessionTranscript:n,currentRunTranscript:a,reviewWindowTranscript:c,reviewState:o,result:e.result,maxReviewsPerSession:t.maxReviewsPerSession,gates:t.gates});if(await M_(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 N_(e,t,l,a,{skipReason:l.skipReason??`gate_not_matched`});return}await M_(e,`auto_skill_review_packet_build_started`,`auto-skill review packet build started`,{mode:t.mode,selectedGateScope:l.selectedGateScope});let u=await new Mi({dataDir:e.runParams.dataDir}).autoSkillCategories().catch(()=>[]),d=a_({sessionId:e.sessionId,transcript:n,transcriptStartIndex:e.transcriptStartIndex,reviewWindowStartIndex:s,contextFiles:Jr(e.runParams.dataDir,e.sessionId,{storeName:e.runParams.sessionStoreName}),result:e.result,reviewState:o,activeCategories:u});if(await M_(e,`auto_skill_review_packet_build_completed`,`auto-skill review packet build completed`,{mode:t.mode,selectedGateScope:l.selectedGateScope,activeCategoryCount:u.length}),await N_(e,t,l,a,{packet:d}),t.mode===`gate`)return;let f=t.mode,p=e.runParams.agentPolicy?.findAny?.(Pg);if(!p){J.info(`auto-skill review skipped because reviewer agent is missing`,{sessionId:e.sessionId,mode:t.mode,reviewerAgentName:Pg}),await j_(e,t,`reviewer_agent_missing`,{reviewerAgentName:Pg});return}i={mode:f,decision:l,packet:d},r=await p_({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??Fg,h=Ng({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 h_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName});let n=await P_(e.runParams.dataDir,i,{status:`failed`,curatorResult:g,error:g.error,reviewState:r});await A_(e,g.error,{mode:t.mode,usage:g.usage,toolCalls:F_(g.toolCalls),toolResults:H_(g.toolResults),writeResults:g.writeResults,wrote:g.wrote,reviewRunLogPath:n});return}r=await m_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,reviewedTranscriptEndIndex:d.reviewWindowRange.endIndex,sessionStoreName:e.runParams.sessionStoreName});let _=await P_(e.runParams.dataDir,i,{status:`completed`,curatorResult:g,reviewState:r});await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:`auto_skill_review_completed`,message:`auto-skill review agent completed`,details:{mode:t.mode,usage:g.usage,text:V_(g.text,2e3),toolCalls:F_(g.toolCalls),toolResults:H_(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 h_({dataDir:e.runParams.dataDir,sessionId:e.sessionId,state:r,sessionStoreName:e.runParams.sessionStoreName}).catch(()=>void 0),i&&(a=await P_(e.runParams.dataDir,i,{status:`failed`,error:n,reviewState:r}).catch(()=>void 0))),await A_(e,n,a?{reviewRunLogPath:a}:void 0)}}function T_(e){return{mode:E_(e?.mode),maxReviewsPerSession:e?.maxReviewsPerSession,gates:e?.gates}}function E_(e){if(e==null)return S_;if(typeof e!=`string`)return`off`;let t=e.trim().toLowerCase();return t?C_.has(t)?t:`off`:S_}function D_(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 O_(e,t){if(typeof t!=`number`||!Number.isFinite(t))return e;let n=Math.max(0,Math.floor(t));return e.slice(n)}function k_(e,t){return typeof e!=`number`||!Number.isFinite(e)?0:Math.min(t,Math.max(0,Math.floor(e)))}async function A_(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 j_(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 M_(e,t,n,r){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`info`,scope:`skill`,phase:t,message:n,details:r})}async function N_(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:B_(n),...i.packet?{packet:i.packet}:{}}})}async function P_(e,t,n){return x_(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?L_(n.curatorResult.text):void 0,conclusionText:n.curatorResult?R_(n.curatorResult.text):void 0,usage:n.curatorResult?.usage,toolCalls:n.curatorResult?F_(n.curatorResult.toolCalls):void 0,toolResults:n.curatorResult?H_(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 F_(e){return e.map(e=>({...e,arguments:I_(e.name,e.arguments)}))}function I_(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 L_(e){let t=z_(e);for(let e of t)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}function R_(e){return L_(e)?void 0:V_(e,8e3)}function z_(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 B_(e){return Object.fromEntries(Object.entries(e.gateResults).map(([e,t])=>[e,{configured:t.configured,passed:t.passed,reasons:t.reasons.map(e=>({code:e.code})),missingReasonCodes:t.missingReasonCodes,stats:t.stats}]))}function V_(e,t){return e.length<=t?e:`${e.slice(0,t-3)}...`}function H_(e){return e.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,preview:e.isError?e.preview:``}))}let U_=!1;function W_(){U_||=(_t(),gt({api:`openai-completions`,stream:Yo,streamSimple:Xo}),!0)}const G_=[`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(`
129
- `);async function K_(e){let{message:t,text:n=``,llm:r,signal:i,hooks:a,hookCtx:o,onFallback:s}=e,c=t.trim().replace(/\s+/g,` `);if(!c)return`New session`;if(!r.flashModel)return Z_(c);let l=Z_(c),u=r.flashModel,d=oo({apiFormat:r.apiFormat,baseUrl:r.baseUrl,apiKey:r.apiKey,defaultModel:u,hooks:a,hookCtx:o}),f=[{role:`user`,content:c}];n&&f.push({role:`assistant`,content:n});let p=J_(i,5e3);try{for(let e=1;e<=3;e++)try{let e=(await d.chat({system:G_,user:JSON.stringify(f),temperature:0,maxTokens:100,signal:p.signal})).text.trim();if(!e)throw Error(`LLM title generation returned empty content`);return e.length>80?e.slice(0,79)+`…`:e}catch(t){if(Y_(t)){if(p.didTimeout())return s?.(`timeout`),l;throw t}e<3&&await q_(500*e,p.signal)}}catch(e){if(Y_(e)&&p.didTimeout())return s?.(`timeout`),l;throw e}finally{p.clear()}return s?.(`error`),l}function q_(e,t){return t?t.aborted?Promise.reject(X_()):new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),t.removeEventListener(`abort`,a),r(X_())};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>setTimeout(t,e))}function J_(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 Y_(e){return e instanceof Error&&e.name===`AbortError`}function X_(){let e=Error(`The operation was aborted.`);return e.name=`AbortError`,e}function Z_(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 Q_(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 $_(e){let{sessionId:t,result:n,runParams:r,hookRegistry:i,hookContext:a}=e,o=await nv(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 ev(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 tv(e){await $_(e),await ev(e)}async function nv(e,t){return e.map(e=>({...e}))}async function rv(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,timestamp:new Date().toISOString()},m),r){let t=await av({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,context:{snapshotPath:_(o.dataDir,n,X(o)),toolResultsDir:s(o.dataDir,n,X(o))}};return J.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 tv({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function iv(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,eventDispatcher:h,sessionEndOnly:g}=e;if(n){let n=X(i),s=await av({sessionId:t,titleSource:r,text:e.text,runParams:i,hookRegistry:a,hookContext:o,logLifecycle:!0});await u(i.dataDir,t,{title:s},n),await h.dispatchProgress(t,{type:`title_updated`,title:s})}let v={sessionId:t,text:l,usage:d,durationMs:Date.now()-c,error:f,paused:p,uiToolPending:m,context:{snapshotPath:_(i.dataDir,t,X(i)),toolResultsDir:s(i.dataDir,t,X(i))}},y={sessionId:t,kind:`completed`,durationMs:v.durationMs,isNewSession:n,inputTokens:d.input,outputTokens:d.output,totalTokens:d.total,hasError:!!f,error:f,paused:!!p,uiToolPending:!!m,textLength:l.length,snapshotPath:v.context.snapshotPath,toolResultsDir:v.context.toolResultsDir};f?J.warn(`agent run finalized with error`,y):J.info(`agent run finalized`,y);let b={sessionId:t,result:v,runParams:i,hookRegistry:a,hookContext:o,eventDispatcher:h};return g?await ev(b):await tv(b),v}async function av(e){let t=Z_(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&J.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await K_({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,onFallback:e=>{n=e}});return n?J.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&J.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return J.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const ov=new Set([`pause`,`resume`,`clear`,`help`]),sv=`/goal
141
+ `).slice(0,4e3)}async function Xv(e){if(e.coreConfig?.capture?.enabled!==!0)return;let t=Yv(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 Zv(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 Xv({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 Qv(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 ty({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 J.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 Zv({sessionId:n,runParams:o,runContext:e.runContext,eventDispatcher:p}),await qv({sessionId:n,result:v,runParams:o,hookRegistry:c,hookContext:l,eventDispatcher:p}),v}async function $v(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 ty({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 ey({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?J.warn(`agent run finalized with error`,b):J.info(`agent run finalized`,b),await Zv({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 Kv(x):await qv(x),y}async function ey(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 ty(e){let t=Uv(e.titleSource.trim()?e.titleSource:`New session`);e.logLifecycle&&J.info(`session title generation started`,{sessionId:e.sessionId});let n;try{let t=await Rv({message:e.titleSource,llm:e.runParams.llm,text:e.text,hooks:e.hookRegistry,hookCtx:e.hookContext,onFallback:e=>{n=e}});return n?J.warn(`session title generation failed`,{sessionId:e.sessionId,reason:n,fallbackTitle:t}):e.logLifecycle&&J.info(`session title generation completed`,{sessionId:e.sessionId,title:t}),t}catch(n){return J.warn(`session title generation failed`,{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n),fallbackTitle:t}),t}}const ny=new Set([`pause`,`resume`,`clear`,`help`]),ry=`/goal
130
142
  【目标】:把 src/auth 目录下重复的参数校验逻辑抽离成公共函数。
131
143
  【范围】:只处理 src/auth 目录,不扩散到用户模块或订单模块。
132
144
  【约束】:保持现有 API 兼容,不引入新依赖,不要改变数据库结构。
133
145
  【验证】:每次改动后请自主运行 npm test auth 以及 npm run typecheck。如果测试失败,请定位原因并修复。
134
- 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function cv(){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 发送):`,sv].join(`
135
- `)}function lv(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,sv,``,`正文(写入 objective.txt 供 --goal-file):`,sv.replace(/^\/goal\s+/,``)].join(`
136
- `)}async function uv(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await H(e.dataDir,e.sessionId,t);if(!r){let r=await oe(e.dataDir,e.sessionId,{goalId:nt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await Sn(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`created`,goal:r}}if((await z(e.dataDir,e.sessionId,r,t)).trim()!==n){let r=await oe(e.dataDir,e.sessionId,{goalId:nt(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await Sn(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 B(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function dv(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(ov.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 fv(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function pv(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function mv(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${fv(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:`,` 状态:${pv(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(`
137
- `)}async function hv(e,t,n){let r=await bn(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return mv(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 _v(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:cv()};if(e.action===`get`){let e=await H(t.dataDir,t.sessionId,n);return e?{replyText:await hv(t,e,await z(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
138
- `)}}if(e.action===`set`){let r=await uv({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await z(t.dataDir,t.sessionId,r.goal,n);if(r.action===`unchanged`){let e=await hv(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 hv(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await B(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await hv(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能恢复。`);if(e.status===`budget_limited`)throw Error(`/goal 目标已触达预算限制,不能恢复;请使用 /goal clear 清除,或重新设置新的 /goal 目标。`);if(e.status===`active`)return{replyText:`/goal 目标已处于进行中状态。\n\n${await hv(t,e,await z(t.dataDir,t.sessionId,e,n))}`};let r=await B(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${await hv(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ae(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const vv=[{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 yv(){return vv.map(e=>({...e}))}function bv(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function xv(e){let t=new Set,n=[];for(let r of e){let e=bv(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function Sv(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function Cv(e,t){let n=yv(),r=xv(e),i=t?Sv(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function wv(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 Tv(e){let t=wv(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 Ev(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 Dv(e,t){let n=Tv(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=dv(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:bv(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 Ov=new Set([`/new`,`/reset`,`/compact`]),kv=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),Av=new Set([`/help`]);function jv(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function Mv(e){if(e.length===0)return[];let t=e.map(jv),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function Nv(e){let t=Cv(e.skills),n=t.builtin.filter(e=>Ov.has(e.name)),r=t.builtin.filter(e=>kv.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>Av.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...Mv(n)),s.push(``),s.push(`目标命令`),s.push(...Mv(r)),s.push(``),s.push(`技能命令`),s.push(...Mv(i)),o.length>0?(s.push(...Mv(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...Mv(a)),{kind:`reply`,text:s.join(`
139
- `)}}function Pv(e,t){let n=t.trim().toLowerCase();return n&&xv(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function Fv(e){let t=Pv(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(`
146
+ 【输出】:完成后输出修改的文件列表、改动原因和测试通过的截图/日志。`;function iy(){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 发送):`,ry].join(`
147
+ `)}function ay(){return[``,`多行目标:`,` 会话内 /goal 后换行(Console:Shift+Enter 换行,Enter 发送;详见 /goal help)`,` CLI aimax run --goal-file <path>,或 shell heredoc 传给 aimax goal set`,``,`结构化示例(会话 /goal;--goal-file 可只用下面「正文」部分):`,ry,``,`正文(写入 objective.txt 供 --goal-file):`,ry.replace(/^\/goal\s+/,``)].join(`
148
+ `)}async function oy(e){let t={storeName:e.sessionStoreName},n=e.objective.trim();if(!n)throw Error(`/goal 目标内容不能为空。`);let r=await H(e.dataDir,e.sessionId,t);if(!r){let r=await U(e.dataDir,e.sessionId,{goalId:it(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await wn(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`created`,goal:r}}if((await z(e.dataDir,e.sessionId,r,t)).trim()!==n){let r=await U(e.dataDir,e.sessionId,{goalId:it(),objective:n,status:`active`,tokenBudget:e.tokenBudget??null,tokensUsed:0,timeUsedSeconds:0},{...t,eventSource:e.eventSource});return await wn(e.dataDir,e.sessionId,{goalId:r.goalId,objective:n},t),{action:`replaced`,goal:r}}if(r.status===`complete`)return{action:`unchanged`,goal:r};let i={};if(r.status===`paused`&&(i.status=`active`),e.tokenBudget!==void 0&&e.tokenBudget!==r.tokenBudget&&(i.tokenBudget=e.tokenBudget),Object.keys(i).length===0)return{action:`unchanged`,goal:r};let a=await V(e.dataDir,e.sessionId,i,{...t,eventSource:e.eventSource});return{action:r.status===`paused`?`resumed`:`updated`,goal:a}}function sy(e){let t=e.trim();if(!t)return{action:`get`,objective:``};let n=t.split(/\s+/)[0]?.toLowerCase()??``;if(ny.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 cy(e){switch(e){case`active`:return`进行中`;case`paused`:return`已暂停`;case`budget_limited`:return`预算受限`;case`complete`:return`已完成`;default:return e}}function ly(e){switch(e){case`active`:return`进行中`;case`blocked`:return`已阻塞`;case`complete`:return`已完成`;default:return e}}function uy(e,t,n,r){let i=e.tokenBudget===null?`Token 预算:不限`:`Token 预算:${e.tokenBudget}(已使用 ${e.tokensUsed},剩余 ${Math.max(0,e.tokenBudget-e.tokensUsed)})`,a=[`/goal 目标`,`状态:${cy(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:`,` 状态:${ly(n.workflowStatus)}`,n.currentTaskTitle?` 当前任务:${n.currentTaskTitle}(${n.currentTaskStatus??`unknown`})`:` 当前任务:(无)`),n.blockedReason&&a.push(` 阻塞原因:${n.blockedReason}`),a.push(` 待完成必需任务:${n.openRequiredTasks}`)),a.push(``,fy(e.status)),a.join(`
149
+ `)}async function dy(e,t,n){let r=await Sn(e.dataDir,e.sessionId,{storeName:e.sessionStoreName});return uy(t,n,r.goalState,r.workflowWarning)}function fy(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 py(e,t){let n={storeName:t.sessionStoreName};if(e.action===`help`)return{replyText:iy()};if(e.action===`get`){let e=await H(t.dataDir,t.sessionId,n);return e?{replyText:await dy(t,e,await z(t.dataDir,t.sessionId,e,n))}:{replyText:[`当前会话尚未设置 /goal 目标。`,`用法:/goal <目标内容>`,``,`建议把“目标”和“完成标准”一起写进 /goal 目标,避免仅凭主观判断完成,例如:`,`- /goal 完善 benchmark 覆盖率。完成标准:覆盖率提升到 85% 以上,并通过相关测试。`,`- /goal 修复订单创建接口的空指针异常。完成标准:定位根因并完成修复;补充回归测试;相关接口测试通过;相同输入不再触发 NullPointerException。`,`- /goal 修复登录接口 500 错误。完成标准:定位根因并完成修复;新增回归测试;验证失败场景不再复现。`,``,`支持多行书写(/goal 后换行);完整多行模板见 /goal help。`].join(`
150
+ `)}}if(e.action===`set`){let r=await oy({dataDir:t.dataDir,sessionId:t.sessionId,sessionStoreName:t.sessionStoreName,objective:e.objective,tokenBudget:e.tokenBudget,eventSource:`slash`}),i=await z(t.dataDir,t.sessionId,r.goal,n);if(r.action===`unchanged`){let e=await dy(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 dy(t,r.goal,i)}`,goalUpdate:{action:r.action,goal:r.goal}}}if(e.action===`pause`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能暂停。`);if(e.status===`paused`)return{replyText:`/goal 目标已处于暂停状态。使用 /goal resume 可继续。`};let r=await V(t.dataDir,t.sessionId,{status:`paused`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已暂停。\n\n${await dy(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`paused`,goal:r}}}if(e.action===`resume`){let e=await H(t.dataDir,t.sessionId,n);if(!e)throw Error(`当前会话尚未设置 /goal 目标。`);if(e.status===`complete`)throw Error(`已完成的 /goal 目标不能恢复。`);if(e.status===`budget_limited`)throw Error(`/goal 目标已触达预算限制,不能恢复;请使用 /goal clear 清除,或重新设置新的 /goal 目标。`);if(e.status===`active`)return{replyText:`/goal 目标已处于进行中状态。\n\n${await dy(t,e,await z(t.dataDir,t.sessionId,e,n))}`};let r=await V(t.dataDir,t.sessionId,{status:`active`},{...n,eventSource:`slash`});return{replyText:`/goal 目标已恢复(进行中)。\n\n${await dy(t,r,await z(t.dataDir,t.sessionId,r,n))}`,goalUpdate:{action:`resumed`,goal:r}}}return e.action===`clear`?await ae(t.dataDir,t.sessionId,{...n,eventSource:`slash`})?{replyText:`/goal 目标已清除。`,goalUpdate:{action:`cleared`,goal:null}}:{replyText:`当前会话尚未设置 /goal 目标。`}:{replyText:`无法识别的 /goal 命令。可尝试 /goal help。`}}const my=[{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 hy(){return my.map(e=>({...e}))}function gy(e){return e.trim().replace(/^\/+/,``).toLowerCase().replace(/[\s_]+/g,`-`)}function _y(e){let t=new Set,n=[];for(let r of e){let e=gy(r.name);e&&(t.has(e)||(t.add(e),n.push({name:`/${e}`,description:r.description||`Skill command.`})))}return n}function vy(e){return[...e.entries()].map(([e])=>({name:`/${e}`,description:`Extension command: ${e}`}))}function yy(e,t){let n=hy(),r=_y(e),i=t?vy(t):[];return{builtin:n,skillCommands:r,all:[...n,...r,...i]}}function by(e){let t=e.trim();if(!t)return``;let n=t.match(/^\/([^\s:]+)\s*:(.*)$/s);if(!n)return t;let[,r,i]=n,a=i.trimStart();return a?`/${r} ${a}`:`/${r}`}function xy(e){let t=by(e);if(!t.startsWith(`/`))return null;let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]+))?$/);if(!n)return null;let r=n[1]?.trim().toLowerCase()??``,i=(n[2]??``).trim();return r?{name:r,rest:i}:null}function Sy(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 Cy(e,t){let n=xy(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=sy(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:gy(e[1]??``),args:(e[2]??``).trim()}:{kind:`unknown`,name:n.name,args:n.rest}}return new Set(_y(t).map(e=>e.name.slice(1))).has(n.name)?{kind:`skill-direct`,name:n.name,args:n.rest}:{kind:`unknown`,name:n.name,args:n.rest}}const wy=new Set([`/new`,`/reset`,`/compact`]),Ty=new Set([`/goal`,`/goal pause`,`/goal resume`,`/goal clear`]),Ey=new Set([`/help`]);function Dy(e){return e.name===`/compact`?{...e,name:`/compact [instructions]`}:e.name===`/skill`?{...e,name:`/skill <name> [input]`}:e}function Oy(e){if(e.length===0)return[];let t=e.map(Dy),n=Math.max(25,...t.map(e=>e.name.length));return t.map(e=>` ${e.name.padEnd(n)} ${e.description}`)}function ky(e){let t=yy(e.skills),n=t.builtin.filter(e=>wy.has(e.name)),r=t.builtin.filter(e=>Ty.has(e.name)),i=t.builtin.filter(e=>e.name===`/skill`),a=t.builtin.filter(e=>Ey.has(e.name)),o=t.skillCommands.slice(0,4),s=[];return s.push(`帮助`),s.push(``),s.push(`会话命令`),s.push(...Oy(n)),s.push(``),s.push(`目标命令`),s.push(...Oy(r)),s.push(``),s.push(`技能命令`),s.push(...Oy(i)),o.length>0?(s.push(...Oy(o)),t.skillCommands.length>o.length&&s.push(` ... 还有 ${t.skillCommands.length-o.length} 个`)):s.push(` 未安装技能命令`),s.push(``),s.push(`其他命令`),s.push(...Oy(a)),{kind:`reply`,text:s.join(`
151
+ `)}}function Ay(e,t){let n=t.trim().toLowerCase();return n&&_y(e).map(e=>e.name.slice(1)).includes(n)?{name:n}:null}function jy(e){let t=Ay(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(`
140
152
 
141
- `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function Iv(e){let t=Dv(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?Nv(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?Fv({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 Lv(e){let{entries:t,contextWindowTokens:n,llm:r,instructions:i,signal:a,hooks:o,hookCtx:s}=e,c=Rv(t),l=c>=0?t[c].content:void 0,u=Fs(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}=nc(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 Gs({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 Rv(e){for(let t=e.length-1;t>=0;t--)if(e[t].role===`compaction`)return t;return-1}const zv=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
142
- `),Bv=[`.aimax/new.txt`];async function Vv(e){try{return(await Qe(e,`utf-8`)).trim()||null}catch{return null}}async function Hv(e){for(let t of Bv){let n=await Vv($e(e,t));if(n)return n}return await Vv(`/aimax_pvc/new.txt`)||zv}async function Uv(e){return{kind:`reply`,text:await Hv(e)}}function Wv(){return{kind:`reply`,text:`✅ Session reset.`}}async function Gv(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function Kv(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 Gv(e,t,{action:n.action,goal:n.after??null})}function qv(e){let t=Xv(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?Zv(r):null,a=n??i?.text,o=a?Ev(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Qv(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:$v(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Jv(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=Dv(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=Iv({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:Qv(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:$v(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Yv(e){let t=Jv(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 rv({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,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 rv({replyText:(t.action===`reset`?Wv():await Uv(e.runParams.dataDir)).text,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`reply`)return{kind:`completed`,result:await rv({replyText:t.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})};if(t.kind===`goal`){let n;try{n=await _v({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 Gv(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),ey(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await z(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await rv({replyText:n.replyText,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,eventDispatcher:e.eventDispatcher})}}if(t.kind!==`compact`)return{kind:`continue`,effectivePrompt:e.invocation.promptInput,transcriptMessage:e.invocation.transcriptMessage};let n=await Lv({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 rv({replyText:n.status===`compacted`?`⚙️ Compacted (kept ${n.keptCount}, dropped ${n.droppedCount}).`:`⚙️ Compaction skipped: ${n.reason}`,sessionId:e.sessionId,isNewSession:e.isNewSession,transcriptMessage:t.transcriptMessage,initialUserEntryPersisted:t.initialUserEntryPersisted||e.initialUserEntryPersisted,runParams:e.runParams,hookRegistry:e.hookRegistry,hookContext:e.hookContext,startTime:e.startTime,compactionEntry:n.status===`compacted`?n.entry:void 0,eventDispatcher:e.eventDispatcher})}}function Xv(e){return typeof e.message==`string`}function Zv(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 Qv(e,t){let n=Zv(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 $v(e){return typeof e==`string`?e:JSON.stringify(e)}function ey(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function ty(e){let{agent:t,registry:n,sessionId:r,resolvedModelId:i,eventDispatcher:a,hookRegistry:o,hookContext:s,abortSignal:c,retry:l,appendEntry:u}=e,d=0,f=``,p=0,m=0,h;for(;!c?.aborted&&n.needsAnnounce(r)&&d<10;){d++,J.info(`subagent announce round started`,{sessionId:r,announceRound:d,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){J.info(`subagent announce round skipped`,{sessionId:r,announceRound:d,reason:`no_completed_subagents`});break}J.info(`subagent completions ready for announcement`,{sessionId:r,announceRound:d,completedCount:e.length,runIds:e.map(e=>e.runId).join(`,`),statuses:e.map(e=>e.status).join(`,`)});for(let t of e)await a.dispatchProgress(r,{type:`subagent_complete`,childSessionId:t.childSessionId,task:t.task,status:t.status});let g=ny(e);await u({role:`assistant`,content:g,timestamp:new Date().toISOString()});let _=await tg({agent:t,message:g,sessionId:r,modelId:i,historyMessages:[],eventDispatcher:a,hooks:o,hookCtx:s,abortSignal:c,retry:l,onTurnRecordProduced:async(e,t)=>{e&&await u(e);for(let e of t)await u(e)}});f=_.text,p+=_.inputTokens,m+=_.outputTokens,_.error&&!h&&(h=_.error),n.markAnnounced(e.map(e=>e.runId));let v={sessionId:r,announceRound:d,completedCount:e.length,inputTokens:_.inputTokens,outputTokens:_.outputTokens,hasError:!!_.error,error:_.error,responseTextLength:_.text.length};_.error?J.warn(`subagent announce round completed with error`,v):J.info(`subagent announce round completed`,v)}return d>=10&&n.needsAnnounce(r)&&J.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:d,maxRounds:10}),{text:f,inputTokens:p,outputTokens:m,error:h}}function ny(e){if(e.length===1){let t=e[0];return sm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>sm({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
153
+ `)}:{kind:`reply`,text:`❌ Skill not found: ${e.skillName}. Use /help to see available skills.`}}function My(e){let t=Cy(e.message,e.skills);return t.kind===`none`?{kind:`pass`,message:e.message}:t.kind===`help`?ky(e):t.kind===`compact`?{kind:`compact`,instructions:t.instructions}:t.kind===`skill`||t.kind===`skill-direct`?jy({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 Ny(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=yc(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}=Bc(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 kc({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 Fy=[`新会话已开始!`,`<br>`,` 告诉我你的需求吧,例如:<br>`,` ✏️ “帮我写一份项目总结报告”<br>`,` 💻 “这段代码怎么优化?”<br>`,` 📊 “怎么用Excel快速分析数据?”<br>`,` ✍️ “给我起个有创意的标题”<br>`,`<br>`,` 直接输入你的需求,我们立刻开始 👇`].join(`
154
+ `),Iy=[`.aimax/new.txt`];async function Ly(e){try{return(await et(e,`utf-8`)).trim()||null}catch{return null}}async function Ry(e){for(let t of Iy){let n=await Ly(tt(e,t));if(n)return n}return await Ly(`/aimax_pvc/new.txt`)||Fy}async function zy(e){return{kind:`reply`,text:await Ry(e)}}function By(){return{kind:`reply`,text:`✅ Session reset.`}}async function Vy(e,t,n){await e.dispatchProgress(t,{type:`goal_updated`,action:n.action,goalId:n.goal?.goalId,goalStatus:n.goal?.status??null})}async function Hy(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 Vy(e,t,{action:n.action,goal:n.after??null})}function Uy(e){let t=Ky(e)?`text`:`messages`,n=t===`text`?e.message:void 0,r=t===`messages`?e.messages:void 0,i=r?qy(r):null,a=n??i?.text,o=a?Sy(a):null,s=o?.remainder??``,c=!!(o&&!s),l=o&&s?s:a,u=t===`text`?l??``:o&&s&&r?Jy(r,s):r;return{inputMode:t,rawMessage:n,promptInput:u,transcriptMessage:t===`text`?c?n:l??``:Yy(u),slashCommandSource:a,messageForRun:l,requestedSessionId:o?void 0:e.sessionId,previousSessionId:o?e.sessionId:void 0,resetCommand:o??void 0,resetShortCircuit:c}}function Wy(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=Cy(e.slashCommandSource,t);if(a.kind===`goal`)return{kind:`goal`,action:a.action,objective:a.objective,tokenBudget:a.tokenBudget,transcriptMessage:e.transcriptMessage};let o=My({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:Jy(e.promptInput,o.message);return{kind:`run`,effectivePrompt:t,transcriptMessage:Yy(t)}}return{kind:`run`,effectivePrompt:e.inputMode===`text`?e.messageForRun??``:e.promptInput,transcriptMessage:e.inputMode===`text`?e.messageForRun??``:e.transcriptMessage}}async function Gy(e){let t=Wy(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 Qv({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 Qv({replyText:(t.action===`reset`?By():await zy(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 Qv({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 py({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 Vy(e.eventDispatcher,e.sessionId,{action:n.goalUpdate.action,goal:n.goalUpdate.goal}),Xy(t.action,n.goalUpdate.action,n.goalUpdate.goal))?{kind:`continue`,effectivePrompt:n.goalUpdate.goal?await z(e.runParams.dataDir,e.sessionId,n.goalUpdate.goal,{storeName:e.runParams.sessionStoreName}):t.objective,transcriptMessage:t.transcriptMessage}:{kind:`completed`,result:await Qv({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 Ny({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 Qv({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 Ky(e){return typeof e.message==`string`}function qy(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 Jy(e,t){let n=qy(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 Yy(e){return typeof e==`string`?e:JSON.stringify(e)}function Xy(e,t,n){return n?.status===`active`?e===`resume`?t===`resumed`:e===`set`?t===`created`||t===`replaced`||t===`resumed`:!1:!1}async function Zy(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++,J.info(`subagent announce round started`,{sessionId:r,announceRound:f,maxRounds:10}),await n.waitForAll(r);let e=n.peekCompleted(r);if(e.length===0){J.info(`subagent announce round skipped`,{sessionId:r,announceRound:f,reason:`no_completed_subagents`});break}J.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 _=Qy(e);await d({role:`assistant`,content:_,timestamp:new Date().toISOString()});let v=await Gg({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?J.warn(`subagent announce round completed with error`,y):J.info(`subagent announce round completed`,y)}return f>=10&&n.needsAnnounce(r)&&J.warn(`subagent announce loop stopped at safety cap`,{sessionId:r,announceRound:f,maxRounds:10}),{text:p,inputTokens:m,outputTokens:h,error:g}}function Qy(e){if(e.length===1){let t=e[0];return Hm({task:t.task,label:t.label,status:t.status,result:t.result,error:t.error})}let t=e.map(e=>Hm({task:e.task,label:e.label,status:e.status,result:e.result,error:e.error}));return`[${e.length} subagents completed]\n\n${t.join(`
143
155
 
144
156
  ---
145
157
 
146
- `)}`}function ry(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function iy(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function ay(){let e=rt.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function oy(e){let t=e.trim(),n=ay();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?W.join(n,t.slice(2)):void 0:W.resolve(t)}const sy=new xt({allErrors:!0,strict:!1}),cy=new Map;function ly(e,t){let n=cy.get(t);if(n)return n;let r=sy.compile(e);return cy.set(t,r),r}function uy(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ly(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function dy(e){let t=iy(e?.allow),n=iy(e?.deny),r=iy(e?.load?.paths),i=iy(e?.piExtensions?.paths),a=e?.entries??{},o=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),piExtensionPaths:Array.from(new Set(i)),entries:a,slots:o}}function fy(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=uy({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function py(e){try{return G.realpathSync(e)}catch{return null}}function my(e){try{return G.statSync(e)}catch{return null}}function hy(e,t){let n=W.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!W.isAbsolute(n)}function gy(e){return`0o${e.toString(8).padStart(3,`0`)}`}const _y=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),vy=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function yy(e){let t=W.join(e,`package.json`);if(G.existsSync(t))try{let e=JSON.parse(G.readFileSync(t,`utf-8`));return ry(e)?e:void 0}catch{return}}function by(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function xy(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Sy(e){let t=py(e.source),n=py(e.rootDir);return!t||!n||hy(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function Cy(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=W.resolve(r);if(n.has(t))continue;n.add(t);let i=my(r);if(!i)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let a=i.mode&511;if(a&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:a};if(e.origin!==`bundled`&&e.uid!==null&&typeof i.uid==`number`&&i.uid!==e.uid&&i.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:i.uid,expectedUid:e.uid}}return null}function wy(e){return Sy({source:e.source,rootDir:e.rootDir})||Cy({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:xy(e.ownershipUid)})}function Ty(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${gy(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Ey(e){let t=wy({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Ty(t),source:e.source}),!0):!1}function Dy(e){return W.basename(e,W.extname(e))}function Oy(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function ky(e){for(let t of vy){let n=W.join(e,t);if(G.existsSync(n))return n}return null}function Ay(e){let t;try{t=G.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=W.join(e.rootDir,n.name);if(n.isFile()){if(!_y.has(W.extname(n.name)))continue;let r=W.dirname(t);if(Ey({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(Oy({idHint:Dy(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=yy(t),i=by(r);if(i.status===`ok`){for(let n of i.entries){let i=W.resolve(t,n);if(!hy(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!G.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!_y.has(W.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Ey({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Dy(i)}`:Dy(i);e.candidates.push(Oy({idHint:o,source:i,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let a=ky(t);a&&(Ey({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(Oy({idHint:W.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function jy(e){return e?e.map(oy).filter(e=>typeof e==`string`&&e.length>0):[]}function My(){let e=ay();if(e)return W.join(e,`.aimax`,`extensions`)}function Ny(e){return W.join(e,`.aimax`,`extensions`)}function Py(e){return W.join(e,`.aimax`,`extensions`)}function Fy(e={}){let t=[],n=[],r=jy(e.extraPaths);for(let i of r){if(!G.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=my(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!_y.has(W.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=W.dirname(i);if(Ey({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(Oy({idHint:Dy(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Ay({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Ay({rootDir:Ny(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Ay({rootDir:Py(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=My();return i?Ay({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&Ay({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Iy(e){let t=e.rejectHardlinks??!0,n=py(e.rootPath),r=py(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!hy(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=G.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:G.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Ly=`aimax.plugin.json`,Ry=[Ly];function zy(e){for(let t of Ry){let n=W.join(e,t);if(G.existsSync(n))return n}return W.join(e,Ly)}function By(e,t=!0){let n=zy(e),r=Iy({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(G.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{G.closeSync(r.fd)}if(!ry(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=ry(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let s=typeof i.kind==`string`?i.kind:void 0,c=typeof i.name==`string`?i.name.trim():void 0,l=typeof i.description==`string`?i.description.trim():void 0,u=typeof i.version==`string`?i.version.trim():void 0,d=iy(i.skills),f;return ry(i.uiHints)&&(f=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:s,name:c,description:l,version:u,skills:d,uiHints:f},manifestPath:n}}function Vy(e){let t=new Map,n=[];for(let r of e){let e=By(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let Hy=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Uy(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Hy.ERROR){J.error(i);return}if(e===Hy.WARN){J.warn(i);return}J.info(i)}function Wy(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Uy(Hy.INFO,e.pluginId,t,n),warn:n=>Uy(Hy.WARN,e.pluginId,t,n),error:n=>Uy(Hy.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}let Gy;function Ky(){return Gy||=St(import.meta.url,{interopDefault:!0,requireCache:!0}),Gy}function qy(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function Jy(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function Yy(e){let t=[...e.registry.diagnostics],n=new qm,r=new Ra,i=[],a=[],o=e.runtime?.llm?oo({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Xy(e.runtime?.llmAllowlist),c=Ky();for(let l of e.registry.manifests.values()){let u=qy({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Jy({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f=Date.now(),p;try{p=c(l.source)}catch(e){d.status=`error`,d.error=String(e),d.durationMs=Math.max(0,Date.now()-f),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let m=p&&typeof p==`object`&&`default`in p?p.default:p,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){d.status=`error`,d.error=`plugin module does not export a register function`,d.durationMs=Math.max(0,Date.now()-f),t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let g=Wy({pluginId:l.id,env:e.runtime?.env}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!Zy(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);le({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);_e({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=W.isAbsolute(e)?e:W.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>Ia(l.id)};try{h(v)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=W.isAbsolute(e)?e:W.resolve(l.rootDir,e);i.push(t)}d.durationMs=Math.max(0,Date.now()-f),a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Xy(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Zy(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}let Qy=null,$y=null;function eb(e){let{dataDir:t,bundledDir:n,workspaceDir:r}=e,i=e.config?JSON.stringify({allow:e.config.allow,deny:e.config.deny,enabled:e.config.enabled,piExtensions:e.config.piExtensions}):``;return`${t??``}|${n??``}|${r??``}|${i}`}function tb(e){let t=eb(e);return Qy&&$y===t?Qy:(Qy=rb(e),$y=t,Qy)}function nb(e){return Qy&&$y===eb(e)?Qy:rb(e)}function rb(e={}){let t=dy(e.config),n=Fy({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Vy(n.candidates),i=fy({config:t,registry:r}),a=Yy({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t,piExtensions:[]}}function ib(e,t){return Array.from(new Set([...t?.piExtensionPaths??[],...e.piExtensionPaths]))}async function ab(e,t){let n=ib(e,t);return n.length===0?[]:ye(n)}async function ob(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?rb({...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 Ra,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=ib(c.normalizedConfig),d;if(u.length>0){let e=await ab(c.normalizedConfig);if(e.length>0){d=new be(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 sb=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 cb(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=Gf(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 sb,d=await ob({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await Kf({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=>Q_({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function lb(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ub(e){if(!(e instanceof Error))return{errorValue:lb(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]=lb(n[e]));return t}async function db(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ub(e.error)}})}function fb(e,t,n){return W.join(r(e,t,n),`pending-ui-tool.json`)}async function pb(e,t,n,i){let a=r(e,t,i);await U.mkdir(a,{recursive:!0}),await L(fb(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function mb(e,t,n){let r=await o(fb(e,t,n));return r===null?null:JSON.parse(r)}async function hb(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await pb(e,t,a,r),a}async function gb(e,t,n,r,i){let a=await mb(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 pb(e,t,o,i),o}async function _b(e,t,n){try{await U.unlink(fb(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function vb(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function yb(e,t,n,r,i,a){let o=await H(e,t,{storeName:a?.storeName});await vb(e,t,n,a);let s=await wt(e,t,n,r,a);return s.goal&&await Kv(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function bb(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Xe(t))}async function xb(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=So();if(i=await Co(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(vo(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=Sb(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 Sb(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 Cb=2e4,wb=15e4,Tb=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Eb(e){return W.join(e,`.aimax`)}async function Db(e){let t=Eb(e),n=[];for(let e of Tb){let r=W.join(t,e);try{let t=await U.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await U.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 Ob(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(`
158
+ `)}`}function $y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eb(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function tb(){let e=at.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function nb(e){let t=e.trim(),n=tb();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?G.join(n,t.slice(2)):void 0:G.resolve(t)}const rb=new Ct({allErrors:!0,strict:!1}),ib=new Map;function ab(e,t){let n=ib.get(t);if(n)return n;let r=rb.compile(e);return ib.set(t,r),r}function ob(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ab(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function sb(e){let t=eb(e?.allow),n=eb(e?.deny),r=eb(e?.load?.paths),i=eb(e?.piExtensions?.paths),a=e?.entries??{},o=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),piExtensionPaths:Array.from(new Set(i)),entries:a,slots:o}}function cb(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=ob({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function lb(e){try{return K.realpathSync(e)}catch{return null}}function ub(e){try{return K.statSync(e)}catch{return null}}function db(e,t){let n=G.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!G.isAbsolute(n)}function fb(e){return`0o${e.toString(8).padStart(3,`0`)}`}const pb=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),mb=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function hb(e){let t=G.join(e,`package.json`);if(K.existsSync(t))try{let e=JSON.parse(K.readFileSync(t,`utf-8`));return $y(e)?e:void 0}catch{return}}function gb(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function _b(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function vb(e){let t=lb(e.source),n=lb(e.rootDir);return!t||!n||db(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function yb(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=G.resolve(r);if(n.has(t))continue;n.add(t);let i=ub(r);if(!i)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let a=i.mode&511;if(a&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:a};if(e.origin!==`bundled`&&e.uid!==null&&typeof i.uid==`number`&&i.uid!==e.uid&&i.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:i.uid,expectedUid:e.uid}}return null}function bb(e){return vb({source:e.source,rootDir:e.rootDir})||yb({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:_b(e.ownershipUid)})}function xb(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${fb(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function Sb(e){let t=bb({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:xb(t),source:e.source}),!0):!1}function Cb(e){return G.basename(e,G.extname(e))}function wb(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function Tb(e){for(let t of mb){let n=G.join(e,t);if(K.existsSync(n))return n}return null}function Eb(e){let t;try{t=K.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=G.join(e.rootDir,n.name);if(n.isFile()){if(!pb.has(G.extname(n.name)))continue;let r=G.dirname(t);if(Sb({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(wb({idHint:Cb(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=hb(t),i=gb(r);if(i.status===`ok`){for(let n of i.entries){let i=G.resolve(t,n);if(!db(t,i)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:i});continue}if(!K.existsSync(i)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${i}`,source:i});continue}if(!pb.has(G.extname(i))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${i}`,source:i});continue}if(Sb({source:i,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let a=r?.name?.trim(),o=a?`${a}/${Cb(i)}`:Cb(i);e.candidates.push(wb({idHint:o,source:i,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let a=Tb(t);a&&(Sb({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(wb({idHint:G.basename(t),source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function Db(e){return e?e.map(nb).filter(e=>typeof e==`string`&&e.length>0):[]}function Ob(){let e=tb();if(e)return G.join(e,`.aimax`,`extensions`)}function kb(e){return G.join(e,`.aimax`,`extensions`)}function Ab(e){return G.join(e,`.aimax`,`extensions`)}function jb(e={}){let t=[],n=[],r=Db(e.extraPaths);for(let i of r){if(!K.existsSync(i)){n.push({level:`warn`,message:`plugin path not found: ${i}`,source:i});continue}let r=ub(i);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${i}`,source:i});continue}if(r.isFile()){if(!pb.has(G.extname(i))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${i}`,source:i});continue}let r=G.dirname(i);if(Sb({source:i,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(wb({idHint:Cb(i),source:i,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&Eb({rootDir:i,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?Eb({rootDir:kb(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&Eb({rootDir:Ab(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let i=Ob();return i?Eb({rootDir:i,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&Eb({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function Mb(e){let t=e.rejectHardlinks??!0,n=lb(e.rootPath),r=lb(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!db(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=K.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:K.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const Nb=`aimax.plugin.json`,Pb=[Nb];function Fb(e){for(let t of Pb){let n=G.join(e,t);if(K.existsSync(n))return n}return G.join(e,Nb)}function Ib(e,t=!0){let n=Fb(e),r=Mb({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(K.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{K.closeSync(r.fd)}if(!$y(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=$y(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let s=typeof i.kind==`string`?i.kind:void 0,c=typeof i.name==`string`?i.name.trim():void 0,l=typeof i.description==`string`?i.description.trim():void 0,u=typeof i.version==`string`?i.version.trim():void 0,d=eb(i.skills),f;return $y(i.uiHints)&&(f=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:s,name:c,description:l,version:u,skills:d,uiHints:f},manifestPath:n}}function Lb(e){let t=new Map,n=[];for(let r of e){let e=Ib(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let Rb=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function zb(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Rb.ERROR){J.error(i);return}if(e===Rb.WARN){J.warn(i);return}J.info(i)}function Bb(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>zb(Rb.INFO,e.pluginId,t,n),warn:n=>zb(Rb.WARN,e.pluginId,t,n),error:n=>zb(Rb.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}let Vb;function Hb(){return Vb||=wt(import.meta.url,{interopDefault:!0,requireCache:!0}),Vb}function Ub(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function Wb(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function Gb(e){let t=[...e.registry.diagnostics],n=new kh,r=new Va,i=[],a=[],o=e.runtime?.llm?lo({apiFormat:e.runtime.llm.apiFormat,baseUrl:e.runtime.llm.baseUrl,apiKey:e.runtime.llm.apiKey,defaultModel:e.runtime.llm.model,hooks:r,hookCtx:e.runtime.hookCtx}):void 0,s=Kb(e.runtime?.llmAllowlist),c=Hb();for(let l of e.registry.manifests.values()){let u=Ub({config:e.plugins,pluginId:l.id,origin:l.origin,kind:l.manifest.kind}),d=Wb({id:l.id,source:l.source,origin:l.origin,enabled:u,configSchema:!0,skills:l.manifest.skills??[]});if(!u){a.push(d);continue}let f=Date.now(),p;try{p=c(l.source)}catch(e){d.status=`error`,d.error=String(e),d.durationMs=Math.max(0,Date.now()-f),t.push({level:`error`,message:`failed to load plugin ${l.id}: ${String(e)}`,pluginId:l.id,source:l.source}),a.push(d);continue}let m=p&&typeof p==`object`&&`default`in p?p.default:p,h=typeof m==`function`?m:m&&typeof m==`object`&&typeof m.register==`function`?m.register:void 0;if(!h){d.status=`error`,d.error=`plugin module does not export a register function`,d.durationMs=Math.max(0,Date.now()-f),t.push({level:`error`,message:`plugin ${l.id} has no register function`,pluginId:l.id,source:l.source}),a.push(d);continue}let g=Bb({pluginId:l.id,env:e.runtime?.env}),_=e.plugins.entries[l.id]?.config,v={id:l.id,source:l.source,rootDir:l.rootDir,config:_,runtime:g,llm:{chat:async e=>{if(!o)throw Error(`LLM client is not configured`);if(!qb(l.id,n,s))throw Error(`Plugin ${l.id} is not allowed to use LLM`);return o.chat(e)}},registerTool:(e,t)=>{n.register(l.id,e,t),d.toolCount+=1},registerUiTool:(e,t)=>{n.registerUiTool(l.id,e,t),d.toolCount+=1},registerEmbeddingProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register embedding providers`);be({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerMemoryProvider:e=>{if(l.manifest.kind!==`memory`)throw Error(`Plugin ${l.id} is not allowed to register memory providers`);fe({pluginId:l.id,id:e.id,create:e.create,config:_,rootDir:l.rootDir,source:l.source})},registerHook:(e,t,n)=>{r.register({pluginId:l.id,hookName:e,handler:t,priority:n?.priority,source:l.source}),d.hookCount+=1},registerSkillDir:e=>{let t=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)},createProgressEmitter:()=>za(l.id)};try{h(v)}catch(e){d.status=`error`,d.error=String(e),t.push({level:`error`,message:`plugin ${l.id} registration failed: ${String(e)}`,pluginId:l.id,source:l.source})}if(l.manifest.skills&&l.manifest.skills.length>0)for(let e of l.manifest.skills){let t=G.isAbsolute(e)?e:G.resolve(l.rootDir,e);i.push(t)}d.durationMs=Math.max(0,Date.now()-f),a.push(d)}return{plugins:a,diagnostics:t,tools:n,hooks:r,skills:i}}function Kb(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function qb(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}let Jb=null,Yb=null;function Xb(e){let{dataDir:t,bundledDir:n,workspaceDir:r}=e,i=e.config?JSON.stringify({allow:e.config.allow,deny:e.config.deny,enabled:e.config.enabled,piExtensions:e.config.piExtensions}):``;return`${t??``}|${n??``}|${r??``}|${i}`}function Zb(e){let t=Xb(e);return Jb&&Yb===t?Jb:(Jb=$b(e),Yb=t,Jb)}function Qb(e){return Jb&&Yb===Xb(e)?Jb:$b(e)}function $b(e={}){let t=sb(e.config),n=jb({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=Lb(n.candidates),i=cb({config:t,registry:r}),a=Gb({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t,piExtensions:[]}}function ex(e,t){return Array.from(new Set([...t?.piExtensionPaths??[],...e.piExtensionPaths]))}async function tx(e,t){let n=ex(e,t);return n.length===0?[]:xe(n)}async function nx(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?$b({...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 Va,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=ex(c.normalizedConfig),d;if(u.length>0){let e=await tx(c.normalizedConfig);if(e.length>0){d=new Se(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 rx=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 ix(e){let{runParams:t,requestedSessionId:n,eventDispatcher:i}=e,a=kp(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 rx,d=await nx({runParams:t,hookContext:l,sessionId:o,eventDispatcher:i,runtimeBridge:u}),f=d.hookRegistry,p=await Ap({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=>Wv({sessionId:o,runParams:t,hookRegistry:f,hookContext:l,eventDispatcher:i,...e})}}function ax(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)??String(e)}function ox(e){if(!(e instanceof Error))return{errorValue:ax(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]=ax(n[e]));return t}async function sx(e){await e.dispatcher.dispatchDiagnostic(e.sessionId,{level:`error`,scope:e.scope,phase:e.phase,message:e.message,details:{...e.details,...ox(e.error)}})}function cx(e,t,n){return G.join(r(e,t,n),`pending-ui-tool.json`)}async function lx(e,t,n,i){let a=r(e,t,i);await W.mkdir(a,{recursive:!0}),await L(cx(e,t,i),JSON.stringify(n,null,2),i?.encryptSessions)}async function ux(e,t,n){let r=await o(cx(e,t,n));return r===null?null:JSON.parse(r)}async function dx(e,t,n,r){let i=new Date().toISOString(),a={version:1,sessionId:t,request:n,status:`pending`,createdAt:i,updatedAt:i};return await lx(e,t,a,r),a}async function fx(e,t,n,r,i){let a=await ux(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 lx(e,t,o,i),o}async function px(e,t,n){try{await W.unlink(cx(e,t,n))}catch(e){if(e.code===`ENOENT`)return;throw e}}async function mx(e,t,n,r){let i=await H(e,t,{storeName:r?.storeName});if(!i||i.status!==`active`&&i.status!==`budget_limited`){n.clearActiveGoal();return}(n.turn?.activeGoalId??n.wallClock.activeGoalId)!==i.goalId&&n.markActiveGoal(`run`,i.goalId,{input:0,output:0,total:0})}async function hx(e,t,n,r,i,a){let o=await H(e,t,{storeName:a?.storeName});await mx(e,t,n,a);let s=await Et(e,t,n,r,a);return s.goal&&await Hy(i,t,{before:o,after:s.goal,action:s.budgetLimited?`budget_limited`:`updated`}),s}function gx(e){let t=e.hitlResume?.toolContext?.toolName;return!!(e.hitlResume&&e.hitlResume.checkpoint.phase===`before_tool`&&e.hitlResume.toolContext&&t&&!Qe(t))}async function _x(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=os();if(i=await ss(t,async()=>await r.execute(n.toolCallId,n.toolArgs,e.abortSignal)),t.signal)throw t.signal;a=!!i?.isError}catch(e){if(ns(e))throw e;a=!0,i={content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],details:{}}}let o=vx(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 vx(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 yx=2e4,bx=15e4,xx=[`AGENTS.md`,`SOUL.md`,`TOOLS.md`,`IDENTITY.md`,`USER.md`,`MEMORY.md`,`BOOTSTRAP.md`];function Sx(e){return G.join(e,`.aimax`)}async function Cx(e){let t=Sx(e),n=[];for(let e of xx){let r=G.join(t,e);try{let t=await W.readFile(r,`utf-8`);n.push({name:e,path:r,content:t,missing:!1}),e===`BOOTSTRAP.md`&&await W.unlink(r).catch(()=>{})}catch(t){if(t.code===`ENOENT`)n.push({name:e,path:r,content:null,missing:!0});else throw t}}return n}function wx(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(`
147
159
  `),s].join(`
148
- `),truncated:!0,originalLength:r.length}}function kb(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Ab(e,t){let n=t?.maxChars??Cb,r=Math.max(1,t?.totalMaxChars??Math.max(n,wb)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=kb(`[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}=Ob(a.content??``,a.name,e),l=kb(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 jb=`You are a personal assistant running inside AiMax.`;async function Mb(e){try{return{presetSystemPrompt:ot(await U.readFile(e,`utf-8`)).content.trim()||jb}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:jb};throw e}}async function Nb(){return Mb(`/aimax_pvc/system_prompt.md`)}async function Pb(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await Db(t.dataDir),o=[],s=Ab(a,{warn:e=>o.push(e)}),c=await Nb();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}}),J.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await Df(t.dataDir,r.pluginSkillDirs,l),d=await ya({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}))}}),J.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}))}}),J.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 Fb({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function Fb(e){if(!e.enabled)return[];try{let t=await new Mi({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 Ib=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=`crons`;function Rb(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:ro(e.message)}}async function zb(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 tg({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 ty({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 Lv({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 Bb(e,t){W_();let n=Date.now(),i=new io(e),a=qv(e);J.info(`agent invocation prepared`,{requestedSessionId:a.requestedSessionId,previousSessionId:a.previousSessionId,inputMode:a.inputMode,hasSlashCommand:!!a.slashCommandSource,resetAction:a.resetCommand?.action,resetShortCircuit:a.resetShortCircuit,transcriptLength:a.transcriptMessage.length,messageForRunLength:a.messageForRun?.length,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId});let o=a.transcriptMessage,s=!1,c=a.previousSessionId,l=await cb({runParams:e,requestedSessionId:a.requestedSessionId,eventDispatcher:i}),u=l.sessionId;no(e.dataDir,{messageId:e.messageId,sessionId:u,sessionStoreName:e.sessionStoreName,sessionDir:r(e.dataDir,u,X(e))});let d=l.isNewSession,f=l.workspaceDir,m=l.hookContext,h=l.hookRegistry,g=l.pluginContext,_=l.runContext,v=l.runtimeBridge,y=0,b=!1,x=()=>{b||(b=!0,v.dispose())},S=(await F(e.dataDir,u,{storeName:e.sessionStoreName})).length;if(J.info(`agent run started`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,channel:e.channel,messageId:e.messageId,sessionStoreName:e.sessionStoreName,isNewSession:d,hasPlugins:!!e.plugins,hasMemory:!!e.memory,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`run_started`,message:`agent run started`,details:{channel:e.channel,isNewSession:d,hasMessageId:!!e.messageId,hasPlugins:!!e.plugins,hasMemory:!!e.memory}}),J.info(d?`session created`:`session resumed`,{sessionId:u,requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}),await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:d?`session_created`:`session_resumed`,message:d?`session created`:`session resumed`,details:{requestedSessionId:a.requestedSessionId,previousSessionId:c,workspaceDir:f}}),d&&await p(e.dataDir,qf({sessionId:u,title:Z_(o),channel:e.channel}),X(e)),e.pendingGoal){let t=await oe(e.dataDir,u,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await Sn(e.dataDir,u,{goalId:t.goalId,objective:e.pendingGoal.objective},{storeName:e.sessionStoreName})}a.resetCommand&&!e.hitlResume&&!e.uiToolResume&&(s=await _.persistInitialUserEntry(o));let C=new AbortController;e.abortSignal?.aborted?C.abort():e.abortSignal?.addEventListener(`abort`,()=>C.abort()),m.signal=C.signal,await l.start({resetCommand:a.resetCommand,previousSessionId:c,resetMessage:a.slashCommandSource,startMessage:typeof a.promptInput==`string`?a.promptInput:o});let w=await Pb({runParams:e,sessionId:u,pluginContext:g,eventDispatcher:i}),T=e=>_.appendTranscriptEntry(e),E=await Yv({invocation:a,skills:w.skills,sessionId:u,isNewSession:d,initialUserEntryPersisted:s,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,extensionHost:g.extensionHost});if(E.kind===`completed`)return J.info(`agent run short-circuited`,{sessionId:u,durationMs:Date.now()-n,hasError:!!E.result.error,paused:!!E.result.paused,uiToolPending:!!E.result.uiToolPending,textLength:E.result.text.length}),x(),E.result;let D=E.effectivePrompt;o=E.transcriptMessage;let O=typeof D==`string`?D:o;await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`invocation_resolved`,message:`invocation resolved`,details:{promptType:typeof D==`string`?`string`:`messages`,transcriptLength:o.length}}),J.info(`invocation resolved`,{sessionId:u,promptType:typeof D==`string`?`string`:`messages`,transcriptLength:o.length});let k=await zh({session:{runParams:w.runParamsWithAgentPolicy,sessionId:u,hookRegistry:h,hookContext:m,runContext:_,eventDispatcher:i},runtimeInputs:{contextFiles:w.contextFiles,bootstrapWarnings:w.bootstrapWarnings,skills:w.skills,autoSkillCategories:w.autoSkillCategories,effectivePromptText:O,pluginTools:g.pluginTools,pluginSkillDirs:g.pluginSkillDirs,skillsLoadPaths:w.skillsLoadPaths,presetSystemPrompt:w.presetSystemPrompt},dependencies:{registry:t,spawnFn:e=>Bb(e,new rm),createModel:fa,abortSignal:C.signal}}),A=k.agent,j=k.resolvedModelId;v.bindAgent(A),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`runtime_created`,message:`agent runtime created`,details:{modelId:j,historyMessageCount:k.historyMessages.length,pluginToolCount:g.pluginTools.length}}),J.info(`agent runtime created`,{sessionId:u,modelId:j,historyMessageCount:k.historyMessages.length,pluginToolCount:g.pluginTools.length});let M=Kb(e.timeoutMs),N=!1,ee=M===void 0?void 0:setTimeout(()=>{N=!0,C.abort(),A.abort(),i.dispatchDiagnostic(u,{level:`warn`,scope:`runner`,phase:`run_timeout`,message:`agent run timed out`,details:{timeoutMs:M}}),J.warn(`agent run timed out`,{sessionId:u,timeoutMs:M})},M);C.signal.addEventListener(`abort`,()=>A.abort());let P=new Ib,I=``,L,R=!1,te=new Ct;await vb(e.dataDir,u,te,{storeName:e.sessionStoreName}),C.signal;try{if(bb(e)){let t=await xb({params:e,agent:A,sessionId:u,eventDispatcher:i,appendEntry:T,abortSignal:C.signal});return I=t.text,x(),iv({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,text:I,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let t=await _.persistInitialUserEntry(o);R=t,s=t||s;try{await un(e.dataDir,u,{storeName:e.sessionStoreName},()=>xr(e.dataDir,u,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof sn))throw e}}await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await H(e.dataDir,u,{storeName:e.sessionStoreName}),a=!1,c=null;if(r?.status===`active`)try{c=await hr(e.dataDir,u,{storeName:e.sessionStoreName})}catch(e){if(e instanceof sn)a=!0;else throw e}let l=!!(a||c&&Er(c)),f=kr({hookRegistry:h,isGateActive:()=>l}),p=await Cr(e.dataDir,u,D,{storeName:e.sessionStoreName}),g;if(a){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(`
149
- `);g={prompt:typeof p.prompt==`string`?e+p.prompt:[{type:`text`,text:e},...p.prompt],hadFirstGoalWorkflowSteering:!0}}else g=await Sr(e.dataDir,u,p.prompt,{storeName:e.sessionStoreName});J.info(`first agent turn started`,{sessionId:u,modelId:j});let b=await tg({agent:A,message:g.prompt,continueFromHistory:!!e.uiToolResume,sessionId:u,channel:e.channel,modelId:j,historyMessages:k.historyMessages,eventDispatcher:i,hooks:h,hookCtx:m,abortSignal:C.signal,retry:e.llmRetry,onTurnRecordProduced:async(e,t)=>{e&&await T(e);for(let e of t)await T(e)}});f(),I=b.text,P.add(b.inputTokens,b.outputTokens),b.error&&(L=b.error),p.hadObjectiveUpdatedSteering&&!b.error&&await wr(e.dataDir,u,{storeName:e.sessionStoreName}),await i.dispatchDiagnostic(u,{level:b.error?`warn`:`info`,scope:`runner`,phase:`first_turn_completed`,message:`first agent turn completed`,details:{hasError:!!b.error,error:b.error,inputTokens:b.inputTokens,outputTokens:b.outputTokens}});let S={sessionId:u,hasError:!!b.error,error:b.error,inputTokens:b.inputTokens,outputTokens:b.outputTokens};b.error?J.warn(`first agent turn completed with error`,S):J.info(`first agent turn completed`,S);let w=await yb(e.dataDir,u,te,P.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`});w.budgetLimited&&await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),J.info(`announce loop started`,{sessionId:u});let E=await ty({agent:A,registry:t,sessionId:u,resolvedModelId:j,eventDispatcher:i,hookRegistry:h,hookContext:m,abortSignal:C.signal,retry:e.llmRetry,appendEntry:T});if(E.text&&(I=E.text),P.add(E.inputTokens,E.outputTokens),E.error&&!L&&(L=E.error),await i.dispatchDiagnostic(u,{level:E.error?`warn`:`info`,scope:`runner`,phase:`announce_loop_completed`,message:`announce loop completed`,details:{hasError:!!E.error,error:E.error,inputTokens:E.inputTokens,outputTokens:E.outputTokens}}),w=await yb(e.dataDir,u,te,P.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`}),w.budgetLimited&&await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),gr()){let n=new mr;n.reset(),b.error&&(n.lastTurnHadOutput=!1);let r=!0,a=qe;for(;r&&n.continuationCount<a&&!C.signal.aborted;)if(r=await yr({agent:A,dataDir:e.dataDir,sessionId:u,sessionStoreName:e.sessionStoreName,state:n,accounting:te,abortSignal:C.signal,executeTurn:async t=>{let n=await tg({agent:A,message:t,continueFromHistory:!1,sessionId:u,channel:e.channel,modelId:j,historyMessages:k.historyMessages,eventDispatcher:i,hooks:h,hookCtx:m,abortSignal:C.signal,onTurnRecordProduced:async(e,t)=>{await br(T,e,t)}});P.add(n.inputTokens,n.outputTokens),I=n.text||I,n.error&&!L&&(L=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 yb(e.dataDir,u,te,P.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await i.dispatchDiagnostic(u,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),r){let e=await ty({agent:A,registry:t,sessionId:u,resolvedModelId:j,eventDispatcher:i,hookRegistry:h,hookContext:m,abortSignal:C.signal,appendEntry:T});P.add(e.inputTokens,e.outputTokens),e.text&&(I=e.text),e.error&&!L&&(L=e.error)}}do{if(C.signal.aborted)break;if(y++,y>8){i.dispatchDiagnostic(u,{level:`warn`,scope:`runner`,phase:`bridge_cycle_limit`,message:`SessionRuntimeBridge exceeded max cycles (8)`}).catch(()=>{});break}await $_({sessionId:u,result:{sessionId:u,text:I??``,usage:P.snapshot(),durationMs:Date.now()-n,error:L},runParams:e,hookRegistry:h,hookContext:m,eventDispatcher:i});let r=await zb({runtimeBridge:v,agent:k.agent,runtime:k,sessionId:u,channel:e.channel,resolvedModelId:j,eventDispatcher:i,hookRegistry:h,hookContext:m,abortSignal:C.signal,retry:e.llmRetry,appendEntry:T,runParams:e,registry:t});P.add(r.inputTokens,r.outputTokens),r.lastResponseText&&(I=r.lastResponseText),r.error&&!L&&(L=r.error)}while(!C.signal.aborted&&(v.hasPendingMessages()||v.hasPendingCompact()));x();let O={sessionId:u,hasError:!!E.error,error:E.error,inputTokens:E.inputTokens,outputTokens:E.outputTokens};E.error?J.warn(`announce loop completed with error`,O):J.info(`announce loop completed`,O)}catch(t){if(vo(t)){let r=t,a=e.subagentContext?.parentSessionId??u,s=a===r.request.sessionId?r.request:{...r.request,sessionId:a};await we(e.dataDir,a,s,r.checkpoint,{agentId:e.subagentContext?`subagent-depth-${e.subagentContext.depth}`:void 0,channel:e.channel,parentSessionId:e.subagentContext?.parentSessionId,depth:e.subagentContext?.depth},r.toolContext),await i.dispatchProgress(a,{type:`hitl_requested`,request:s}),await i.dispatchDiagnostic(u,{level:`info`,scope:`runner`,phase:`hitl_paused`,message:`agent paused for HITL: ${r.request.kind} — ${r.request.title}`,details:{requestId:s.requestId,kind:s.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId}}),J.info(`agent paused for HITL`,{sessionId:u,requestId:s.requestId,kind:s.kind,checkpointPhase:r.checkpoint.phase,bubbledToParent:!!e.subagentContext?.parentSessionId});let c={...P.snapshot()};return await Vb({runtime:k,resolvedModelId:j,usage:c,currentUserEntryCoveredByUsage:R}),x(),iv({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,text:I||`[HITL paused] ${r.request.title}: ${r.request.prompt}`,usage:c,error:void 0,paused:{requestId:s.requestId,kind:s.kind,title:s.title}})}if(bo(t)){let r=t,a=r.request.outputSchema.properties??{};await hb(e.dataDir,u,r.request,X(e)),await i.dispatchProgress(u,{type:`ui_tool_request`,request:r.request}),await i.dispatchDiagnostic(u,{level:`info`,scope:`tool`,phase:`ui_tool_paused`,message:`agent paused for UI tool input: ${r.request.toolName}`,details:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(a).length}}),J.info(`agent paused for UI tool input`,{sessionId:u,requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchemaTitle:r.request.outputSchema.title,propertyCount:Object.keys(a).length});let s={...P.snapshot()};return await Vb({runtime:k,resolvedModelId:j,usage:s,currentUserEntryCoveredByUsage:R}),x(),iv({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,text:I||``,usage:s,error:void 0,uiToolPending:{requestId:r.request.requestId,toolName:r.request.toolName,toolCallId:r.request.toolCallId,outputSchema:r.request.outputSchema,extra:r.request.extra}})}if(N&&qb(t))L=`Run timed out after ${M}ms`;else throw await db({dispatcher:i,sessionId:u,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:d}}),J.error(`agent run failed`,{sessionId:u,channel:e.channel,isNewSession:d,error:t instanceof Error?t.message:String(t)}),t}finally{ee!==void 0&&clearTimeout(ee);try{await yb(e.dataDir,u,te,P.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}te.clearActiveGoal(),kh(u);try{k.processRegistry.disposeAll()}catch{}_.stop(),x()}let z=P.snapshot();N&&(L=`Run timed out after ${M}ms`),await i.dispatchDiagnostic(u,{level:L?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:z.input,outputTokens:z.output,totalTokens:z.total,hasError:!!L,error:L}});let ne={sessionId:u,durationMs:Date.now()-n,inputTokens:z.input,outputTokens:z.output,totalTokens:z.total,hasError:!!L,error:L};return L?J.warn(`agent run completed with error`,ne):J.info(`agent run completed`,ne),await Vb({runtime:k,resolvedModelId:j,usage:z,currentUserEntryCoveredByUsage:R}),await w_({sessionId:u,runParams:w.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:S,result:{text:I,usage:z,durationMs:Date.now()-n,error:L}}),iv({sessionId:u,isNewSession:d,transcriptMessage:o,runParams:e,hookRegistry:h,hookContext:m,startTime:n,eventDispatcher:i,text:I,usage:z,error:L,sessionEndOnly:y>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 Hb(e){let t=Date.now(),i=new io(e),a=qv(e),o=a.transcriptMessage.trim()||`CRON task`,c=e.sessionStoreName;J.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...Rb(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,qf({sessionId:l,title:Z_(o),channel:e.channel}),{storeName:c});let f=await T(e.dataDir,e.channel,{storeName:Lb});no(e.dataDir,{messageId:e.messageId,sessionId:f,sessionStoreName:Lb,sessionDir:r(e.dataDir,f,{storeName:Lb})}),await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:f,task:o}),J.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:f,taskLength:o.length,taskPreview:ro(o)});let m={...e,sessionId:f,sessionStoreName:Lb,subagentContext:{depth:1,parentSessionId:l}},g,y=`done`;try{g=await Bb(m,new rm),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:Lb}),toolResultsDir:s(e.dataDir,f,{storeName:Lb})}},y=`error`,J.error(`cron child run failed`,{parentSessionId:l,childSessionId:f,error:r})}await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:f,task:o,status:y}),J.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:f,status:y,durationMs:Date.now()-t,hasError:!!g.error});let b=sm({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 P(e.dataDir,l,e=>Ub(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 Ub(e,t){if(t<=0)return e.filter(e=>!Wb(e));let n=e.reduce((e,t,n)=>(Wb(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Wb(e)||r.has(t))}function Wb(e){return`source`in e&&e.source===`cron`}async function Gb(e,t){let n=async()=>{if(J.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...Rb(e)}),e.channel===`CRON`&&!e.subagentContext)return Hb(e);let n=t??new rm;try{return await Bb(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:ub(t)}),J.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};return e.onLog?Ua(e.onLog,n):n()}function Kb(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function qb(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 Jb={"AGENTS.md":`---
160
+ `),truncated:!0,originalLength:r.length}}function Tx(e,t){return t<=0?``:e.length<=t?e:t<=1?e.slice(0,t):`${e.slice(0,t-1)}…`}function Ex(e,t){let n=t?.maxChars??yx,r=Math.max(1,t?.totalMaxChars??Math.max(n,bx)),i=[];for(let a of e){if(r<=0)break;if(a.missing){let e=Tx(`[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}=wx(a.content??``,a.name,e),l=Tx(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 Dx=`You are a personal assistant running inside AiMax.`;async function Ox(e){try{return{presetSystemPrompt:ct(await W.readFile(e,`utf-8`)).content.trim()||Dx}}catch(e){if(e.code===`ENOENT`)return{presetSystemPrompt:Dx};throw e}}async function kx(){return Ox(`/aimax_pvc/system_prompt.md`)}async function Ax(e){let{runParams:t,sessionId:n,pluginContext:r,eventDispatcher:i}=e,a=await Cx(t.dataDir),o=[],s=Ex(a,{warn:e=>o.push(e)}),c=await kx();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}}),J.info(`bootstrap context loaded`,{sessionId:n,bootstrapFileCount:a.length,contextFileCount:s.length,warningCount:o.length});let l=t.skillsLoadPaths??[],u=await pp(t.dataDir,r.pluginSkillDirs,l),d=await Sa({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}))}}),J.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}))}}),J.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 jx({dataDir:t.dataDir,sessionId:n,eventDispatcher:i,enabled:t.autoSkills?.load?.enabled===!0}),runParamsWithAgentPolicy:h,skillsLoadPaths:l,presetSystemPrompt:c.presetSystemPrompt}}async function jx(e){if(!e.enabled)return[];try{let t=await new Fi({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 Mx=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 Nx={Inferred:1,Child:2,Own:3};var Px=class{records=[];indices=new Map;urlWhitelist;constructor(e={}){let t=Ix(e.urlWhitelist);this.urlWhitelist=t.length>0?new Set(t):void 0}addOwn(e){this.add(e,Nx.Own)}addInferred(e){this.add(e,Nx.Inferred)}addChild(e){e&&e.length>0&&this.add(e,Nx.Child)}dump(){return this.records.map(e=>e.record)}add(e,t){for(let n of e){if(!this.shouldCollect(n))continue;let e=Fx(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=Lx(e.url);return t?this.urlWhitelist.has(t):!1}};function Fx(e){return e.kind===`file`?`file:${e.file}`:`url:${e.url}`}function Ix(e){return e?e.map(e=>e.trim().toLowerCase()).filter(Boolean):[]}function Lx(e){try{return new URL(e).hostname.trim().toLowerCase()||null}catch{return null}}const Rx=`crons`;function zx(e){return`messages`in e?{inputMode:`messages`,messagesCount:e.messages.length}:{inputMode:`text`,messageLength:e.message.length,messagePreview:oo(e.message)}}async function Bx(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 Gg({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 Zy({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 Ny({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 Vx(e,t){Iv();let n=Date.now(),i=new so(e),a=new Px({urlWhitelist:e.artifactsUrlWhitelist}),o=Uy(e);J.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 ix({runParams:e,requestedSessionId:o.requestedSessionId,eventDispatcher:i}),d=u.sessionId;ao(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(J.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}}),J.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,Mp({sessionId:d,title:Uv(s),channel:e.channel}),X(e)),e.pendingGoal){let t=await U(e.dataDir,d,{objective:e.pendingGoal.objective,status:`active`,tokenBudget:e.pendingGoal.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:e.sessionStoreName,eventSource:`runner`});await wn(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 Ax({runParams:e,sessionId:d,pluginContext:_,eventDispatcher:i}),E=e=>v.appendTranscriptEntry(e),D=await Gy({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 J.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}}),J.info(`invocation resolved`,{sessionId:d,promptType:typeof O==`string`?`string`:`messages`,transcriptLength:s.length});let A=await kg({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=>Vx(e,new Rm),createModel:ha,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}}),J.info(`agent runtime created`,{sessionId:d,modelId:M,historyMessageCount:A.historyMessages.length,pluginToolCount:_.pluginTools.length});let N=qx(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}}),J.warn(`agent run timed out`,{sessionId:d,timeoutMs:N})},N);w.signal.addEventListener(`abort`,()=>j.abort());let I=new Mx,L=``,R,te=!1,z=new Tt;await mx(e.dataDir,d,z,{storeName:e.sessionStoreName}),w.signal;try{if(gx(e)){let t=await _x({params:e,agent:j,sessionId:d,eventDispatcher:i,appendEntry:E,abortSignal:w.signal});return L=t.text,S(),$v({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),text:L,usage:{input:0,output:0,total:0},error:t.error})}if(!e.hitlResume&&!e.uiToolResume){let t=await v.persistInitialUserEntry(s);te=t,c=t||c;try{await fn(e.dataDir,d,{storeName:e.sessionStoreName},()=>wr(e.dataDir,d,{storeName:e.sessionStoreName}))}catch(e){if(!(e instanceof ln))throw e}}await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`first_turn_started`,message:`first agent turn started`});let r=await H(e.dataDir,d,{storeName:e.sessionStoreName}),o=!1,l=null;if(r?.status===`active`)try{l=await vr(e.dataDir,d,{storeName:e.sessionStoreName})}catch(e){if(e instanceof ln)o=!0;else throw e}let u=!!(o||l&&kr(l)),p=Mr({hookRegistry:g,isGateActive:()=>u}),m=await Er(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(`
161
+ `);_={prompt:typeof m.prompt==`string`?e+m.prompt:[{type:`text`,text:e},...m.prompt],hadFirstGoalWorkflowSteering:!0}}else _=await Tr(e.dataDir,d,m.prompt,{storeName:e.sessionStoreName});J.info(`first agent turn started`,{sessionId:d,modelId:M});let x=await Gg({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 Dr(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?J.warn(`first agent turn completed with error`,C):J.info(`first agent turn completed`,C);let T=await hx(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`});T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),await i.dispatchDiagnostic(d,{level:`info`,scope:`runner`,phase:`announce_loop_started`,message:`announce loop started`}),J.info(`announce loop started`,{sessionId:d});let D=await Zy({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 hx(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`}),T.budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`}),yr()){let n=new _r;n.reset(),x.error&&(n.lastTurnHadOutput=!1);let r=!0,o=Ye;for(;r&&n.continuationCount<o&&!w.signal.aborted;)if(r=await Sr({agent:j,dataDir:e.dataDir,sessionId:d,sessionStoreName:e.sessionStoreName,state:n,accounting:z,abortSignal:w.signal,executeTurn:async t=>{let n=await Gg({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 Cr(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 hx(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})).budgetLimited&&await i.dispatchDiagnostic(d,{level:`info`,scope:`session`,phase:`goal_budget_limited`,message:`goal token budget exhausted`})}}),r){let e=await Zy({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 Gv({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 Bx({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?J.warn(`announce loop completed with error`,k):J.info(`announce loop completed`,k)}catch(t){if(ns(t)){let r=t,o=e.subagentContext?.parentSessionId??d,c=o===r.request.sessionId?r.request:{...r.request,sessionId:o};await Ee(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}}),J.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 Hx({runtime:A,resolvedModelId:M,usage:l,currentUserEntryCoveredByUsage:te}),S(),$v({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(is(t)){let r=t,o=r.request.outputSchema.properties??{};await dx(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}}),J.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 Hx({runtime:A,resolvedModelId:M,usage:c,currentUserEntryCoveredByUsage:te}),S(),$v({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&&Jx(t))R=`Run timed out after ${N}ms`;else throw await sx({dispatcher:i,sessionId:d,scope:`runner`,phase:`run_failed`,message:`agent run failed`,error:t,details:{channel:e.channel,isNewSession:f}}),J.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 hx(e.dataDir,d,z,I.snapshot(),i,{storeName:e.sessionStoreName,eventSource:`runner`})}catch{}z.clearActiveGoal(),dg(d);try{A.processRegistry.disposeAll()}catch{}try{se.disposeForDataDir(e.dataDir)}catch{}v.stop(),S()}let B=I.snapshot();P&&(R=`Run timed out after ${N}ms`),await i.dispatchDiagnostic(d,{level:R?`warn`:`info`,scope:`runner`,phase:`run_completed`,message:`agent run completed`,details:{durationMs:Date.now()-n,inputTokens:B.input,outputTokens:B.output,totalTokens:B.total,hasError:!!R,error:R}});let V={sessionId:d,durationMs:Date.now()-n,inputTokens:B.input,outputTokens:B.output,totalTokens:B.total,hasError:!!R,error:R};return R?J.warn(`agent run completed with error`,V):J.info(`agent run completed`,V),await Hx({runtime:A,resolvedModelId:M,usage:B,currentUserEntryCoveredByUsage:te}),await gv({sessionId:d,runParams:T.runParamsWithAgentPolicy,eventDispatcher:i,transcriptStartIndex:C,result:{text:L,usage:B,durationMs:Date.now()-n,error:R}}),$v({sessionId:d,isNewSession:f,transcriptMessage:s,runParams:e,runContext:v,hookRegistry:g,hookContext:h,startTime:n,eventDispatcher:i,artifacts:a.dump(),transcriptStartIndex:C,text:L,usage:B,error:R,sessionEndOnly:b>0})}async function Hx(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 Ux(e){let t=Date.now(),i=new so(e),a=Uy(e),o=a.transcriptMessage.trim()||`CRON task`,c=e.sessionStoreName;J.info(`cron run started`,{requestedSessionId:a.requestedSessionId,channel:e.channel,sessionStoreName:c,...zx(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,Mp({sessionId:l,title:Uv(o),channel:e.channel}),{storeName:c});let f=await T(e.dataDir,e.channel,{storeName:Rx});ao(e.dataDir,{messageId:e.messageId,sessionId:f,sessionStoreName:Rx,sessionDir:r(e.dataDir,f,{storeName:Rx})}),await i.dispatchProgress(l,{type:`subagent_spawn`,childSessionId:f,task:o}),J.info(`cron child subagent spawned`,{parentSessionId:l,childSessionId:f,taskLength:o.length,taskPreview:oo(o)});let m={...e,sessionId:f,sessionStoreName:Rx,subagentContext:{depth:1,parentSessionId:l}},g,y=`done`;try{g=await Vx(m,new Rm),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:Rx}),toolResultsDir:s(e.dataDir,f,{storeName:Rx})}},y=`error`,J.error(`cron child run failed`,{parentSessionId:l,childSessionId:f,error:r})}await i.dispatchProgress(l,{type:`subagent_complete`,childSessionId:f,task:o,status:y}),J.info(`cron child subagent completed`,{parentSessionId:l,childSessionId:f,status:y,durationMs:Date.now()-t,hasError:!!g.error});let b=Hm({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=>Wx(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 Wx(e,t){if(t<=0)return e.filter(e=>!Gx(e));let n=e.reduce((e,t,n)=>(Gx(t)&&e.push(n),e),[]);if(n.length<=t)return e;let r=new Set(n.slice(-t));return e.filter((e,t)=>!Gx(e)||r.has(t))}function Gx(e){return`source`in e&&e.source===`cron`}async function Kx(e,t){let n=async()=>{if(J.info(`agent request received`,{dataDir:e.dataDir,projectDir:e.projectDir,sessionId:e.sessionId,messageId:e.messageId,channel:e.channel,sessionStoreName:e.sessionStoreName,hasHitlResume:!!e.hitlResume,hasUiToolResume:!!e.uiToolResume,isSubagent:!!e.subagentContext,depth:e.subagentContext?.depth,parentSessionId:e.subagentContext?.parentSessionId,hasPlugins:!!e.plugins,hasMemory:!!e.memory,...zx(e)}),e.channel===`CRON`&&!e.subagentContext)return Ux(e);let n=t??new Rm;try{return await Vx(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:ox(t)}),J.error(`agent run crashed before completion`,{sessionId:e.sessionId,channel:e.channel,messageId:e.messageId,error:t instanceof Error?t.message:String(t)}),t}};return e.onLog?Ka(e.onLog,n):n()}function qx(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function Jx(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 Yx={"AGENTS.md":`---
150
162
  title: "AGENTS.md Template"
151
163
  summary: ".aimax template for AGENTS.md"
152
164
  read_when:
@@ -439,7 +451,7 @@ Skills are shared. Your setup is yours. Keeping them apart means you can update
439
451
  This file belongs in \`.aimax/TOOLS.md\`. Keep workspace-only project artifacts in \`workspace/\`.
440
452
 
441
453
  Add whatever helps you do your job. This is your cheat sheet.
442
- `},Yb=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Xb(e,t){try{if(!(await U.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 U.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Zb(e,t,n){try{if(!(await U.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 U.mkdir(W.dirname(e),{recursive:!0});try{await U.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 Qb(e){let t=Eb(e);return[e,t,W.join(t,`skills`),W.join(t,`sessions`),W.join(t,`memory`),W.join(e,`workspace`)]}function $b(e){let t=Eb(e);return[...Yb.filter(e=>e!==`BOOTSTRAP.md`).map(e=>W.join(t,e)),W.join(t,`MEMORY.md`)]}function ex(e){return W.join(Eb(e),`.bootstrapped`)}async function tx(e){try{return(await U.stat(ex(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function nx(e){let t=ex(e);await U.mkdir(W.dirname(t),{recursive:!0}),await U.writeFile(t,``,{encoding:`utf-8`})}async function rx(e){let t=[],n=[];for(let n of Qb(e))try{(await U.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of $b(e))try{(await U.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 ix(e){return(await rx(e)).ready}async function ax(e){if(await tx(e))return{ready:!0,performedBootstrap:!1};if((await rx(e)).ready)return await nx(e),{ready:!0,performedBootstrap:!1};let t=await ox(e);return await nx(e),{ready:!0,performedBootstrap:!0,result:t}}async function ox(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=Eb(e),r=W.join(e,`workspace`),i=W.join(n,`skills`),a=W.join(n,`sessions`),o=W.join(n,`memory`);await Xb(e,t),await Xb(n,t),await Xb(i,t),await Xb(a,t),await Xb(o,t),await Xb(r,t);for(let e of Yb){let r=Jb[e]??``;await Zb(W.join(n,e),r,t)}return await Zb(W.join(n,`MEMORY.md`),``,t),t}async function sx(e){let t=W.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await U.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 cx(e,t){let n=W.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 U.mkdir(W.dirname(n),{recursive:!0}),await U.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function lx(e,t){let n=await sx(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 ux(e,t=7){let n=await sx(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 cx(e,n),i}var dx=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function fx(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function px(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await H(t,n,s);if(!l){let e=await oe(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await Sn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`created`,goal:e}}let u=(await z(t,n,l,s)).trim();if(u!==c){if(!a)throw new dx(`A different goal already exists for this session. Use --force to replace it.`,fx(u));let e=await oe(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await Sn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new dx(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,fx(u));if(a){let e=await oe(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await Sn(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 B(t,n,d,{storeName:o,eventSource:`cli`})}}async function mx(e,t,n,r){let i=await De(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ye(i.request)?(await Ce(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 hx(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await Ee(t,n,r,{storeName:a});if(o){let e=o.resolution?.idempotencyKey;if(e&&i.idempotencyKey&&e===i.idempotencyKey)return{state:o,idempotentReplay:!0};throw Error(`HITL resume validation failed: HITL request is already "${o.status}", cannot resume`)}let s=await mx(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await Ce(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 gx={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 _x(e){return e.action===`timeout`?gx.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?gx.approval.summary.approved:gx.approval.summary.denied}function vx(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:_x(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function yx(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 bx(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 xx(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
454
+ `},Xx=[`AGENTS.md`,`BOOTSTRAP.md`,`IDENTITY.md`,`USER.md`,`SOUL.md`,`TOOLS.md`];async function Zx(e,t){try{if(!(await W.stat(e)).isDirectory())throw Error(`Path exists but is not a directory: ${e}`);t.skippedDirs.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await W.mkdir(e,{recursive:!0}),t.createdDirs.push(e)}async function Qx(e,t,n){try{if(!(await W.stat(e)).isFile())throw Error(`Path exists but is not a file: ${e}`);n.skippedFiles.push(e);return}catch(e){if(e.code!==`ENOENT`)throw e}await W.mkdir(G.dirname(e),{recursive:!0});try{await W.writeFile(e,t,{encoding:`utf-8`,flag:`wx`}),n.createdFiles.push(e)}catch(t){if(t.code===`EEXIST`){n.skippedFiles.push(e);return}throw t}}function $x(e){let t=Sx(e);return[e,t,G.join(t,`skills`),G.join(t,`sessions`),G.join(t,`memory`),G.join(e,`workspace`)]}function eS(e){let t=Sx(e);return[...Xx.filter(e=>e!==`BOOTSTRAP.md`).map(e=>G.join(t,e)),G.join(t,`MEMORY.md`)]}function tS(e){return G.join(Sx(e),`.bootstrapped`)}async function nS(e){try{return(await W.stat(tS(e))).isFile()}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function rS(e){let t=tS(e);await W.mkdir(G.dirname(t),{recursive:!0}),await W.writeFile(t,``,{encoding:`utf-8`})}async function iS(e){let t=[],n=[];for(let n of $x(e))try{(await W.stat(n)).isDirectory()||t.push(n)}catch(e){if(e.code===`ENOENT`){t.push(n);continue}throw e}for(let t of eS(e))try{(await W.stat(t)).isFile()||n.push(t)}catch(e){if(e.code===`ENOENT`){n.push(t);continue}throw e}return{dataDir:e,ready:t.length===0&&n.length===0,missingDirs:t,missingFiles:n}}async function aS(e){return(await iS(e)).ready}async function oS(e){if(await nS(e))return{ready:!0,performedBootstrap:!1};if((await iS(e)).ready)return await rS(e),{ready:!0,performedBootstrap:!1};let t=await sS(e);return await rS(e),{ready:!0,performedBootstrap:!0,result:t}}async function sS(e){let t={dataDir:e,createdDirs:[],skippedDirs:[],createdFiles:[],skippedFiles:[]},n=Sx(e),r=G.join(e,`workspace`),i=G.join(n,`skills`),a=G.join(n,`sessions`),o=G.join(n,`memory`);await Zx(e,t),await Zx(n,t),await Zx(i,t),await Zx(a,t),await Zx(o,t),await Zx(r,t);for(let e of Xx){let r=Yx[e]??``;await Qx(G.join(n,e),r,t)}return await Qx(G.join(n,`MEMORY.md`),``,t),t}async function cS(e){let t=G.join(e,`.aimax`,`subagents`,`runs.json`);try{let e=await W.readFile(t,`utf-8`),n=JSON.parse(e);if(!n||typeof n!=`object`)return new Map;let r;if(n.version===1&&n.records)r=n.records;else if(n.version===void 0)r=n;else return new Map;let i=new Map;for(let[e,t]of Object.entries(r)){if(!t||typeof t!=`object`)continue;let n=t;i.set(e,{...n,abortController:new AbortController})}return i}catch(e){return e.code,new Map}}async function lS(e,t){let n=G.join(e,`.aimax`,`subagents`,`runs.json`),r={};for(let[e,n]of t.entries())if(typeof n.endedAt==`number`){let{abortController:t,...i}=n;r[e]={...i,version:1}}let i={version:1,records:r};await W.mkdir(G.dirname(n),{recursive:!0}),await W.writeFile(n,JSON.stringify(i,null,2),`utf-8`)}async function uS(e,t){let n=await cS(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 dS(e,t=7){let n=await cS(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 lS(e,n),i}var fS=class extends Error{existingObjectivePreview;constructor(e,t){super(e),this.name=`GoalConflictError`,this.existingObjectivePreview=t}};function pS(e,t=200){return e.length<=t?e:`${e.slice(0,t)}...`}async function mS(e){let{dataDir:t,sessionId:n,objective:r,tokenBudget:i,force:a,storeName:o}=e,s={storeName:o},c=r.trim();if(!c)throw Error(`Goal objective cannot be empty`);let l=await H(t,n,s);if(!l){let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??null,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await wn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`created`,goal:e}}let u=(await z(t,n,l,s)).trim();if(u!==c){if(!a)throw new fS(`A different goal already exists for this session. Use --force to replace it.`,pS(u));let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await wn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}if(l.status===`complete`&&!a)throw new fS(`The goal is already complete. Use --force to start a new pursuit with the same objective.`,pS(u));if(a){let e=await U(t,n,{objective:c,status:`active`,tokenBudget:i??l.tokenBudget,tokensUsed:0,timeUsedSeconds:0},{storeName:o,eventSource:`cli`});return await wn(t,n,{goalId:e.goalId,objective:c},{storeName:o}),{action:`replaced`,goal:e}}let d={};return l.status===`paused`&&(d.status=`active`),i!==void 0&&i!==l.tokenBudget&&(d.tokenBudget=i),Object.keys(d).length===0?{action:`unchanged`,goal:l}:{action:`updated`,goal:await V(t,n,d,{storeName:o,eventSource:`cli`})}}async function hS(e,t,n,r){let i=await ke(e,t,{storeName:r});return i?i.request.requestId===n?i.sessionId===t?i.status===`pending`?Ze(i.request)?(await Te(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 gS(e){let{dataDir:t,sessionId:n,requestId:r,resolution:i,sessionStoreName:a}=e,o=await Oe(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 hS(t,n,r,a);if(!s.valid)throw Error(`HITL resume validation failed: ${s.reason}`);let c=await Te(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 _S={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 vS(e){return e.action===`timeout`?_S.approval.summary.timeout:e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1)?_S.approval.summary.approved:_S.approval.summary.denied}function yS(e){let t=e.action===`submit`&&(e.values?.selectedChoiceIds?.includes(`approve`)??!1);return JSON.stringify({summary:vS(e),action:e.action,approved:t,values:e.values??{},submittedBy:e.submittedBy,submittedAt:e.submittedAt,idempotencyKey:e.idempotencyKey})}function bS(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 xS(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 SS(e,t){let n=[];return n.push(`[HITL 恢复] 用户已响应 ${t} 请求(${e.requestId})。`),e.action===`cancel`?(n.push(`动作:用户取消了该请求。请确认取消并继续后续流程,不要执行原操作。`),n.join(`
443
455
  `)):e.action===`timeout`?(n.push(`动作:该请求在未收到用户响应的情况下超时。请按默认超时策略处理。`),n.join(`
444
456
  `)):(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(`
445
- `))}export{Mi as AutoSkillsLoader,Tb as BOOTSTRAP_FILE_NAMES,Cb as BOOTSTRAP_MAX_CHARS,wb as BOOTSTRAP_TOTAL_MAX_CHARS,Et as CLARIFY_ACCEPTANCE_TEXT,Tr as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,Tt as CLARIFY_TASK_TITLE,mr as ContinuationState,sn as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,pr as ENV_GOAL_CONTINUATION,or as FIRST_TURN_GOAL_WORKFLOW_INTRO,sv as GOAL_MULTILINE_TEMPLATE_EXAMPLE,rn as GOAL_WORKFLOW_STATE_VERSION,Ct as GoalAccounting,dx as GoalConflictError,gx as HITL_MESSAGES,_o as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,nm as MAX_CHILDREN_PER_SESSION,tm as MAX_SUBAGENT_DEPTH,pe as MemoryIndexManager,Ly as PLUGIN_MANIFEST_FILENAME,Ry as PLUGIN_MANIFEST_FILENAMES,Ra as PluginHookRegistry,qm as PluginToolRegistry,pa as SYSTEM_AGENTS_DIR,rm as SubagentRegistry,yo as UiToolPauseSignal,Ue as addAgent,ze as addBinding,ha as agentDirCandidates,Ca as agentVisibility,Eb as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,te as appendGoalEvent,kd as appendRecentToMemory,i as appendSessionFile,Od as appendToMemory,h as appendTranscriptEntry,px as applyCliGoalBeforeRun,_x as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,fi as autoSkillsDir,ox as bootstrapMountLayout,Da as buildAgentDelegationPrompt,Oa as buildAgentTaskPrompt,lv as buildAimaxGoalCliHelpExtra,Ab as buildBootstrapContextFiles,lr as buildBudgetLimitPrompt,cr as buildContinuationPrompt,sr as buildFirstTurnGoalWorkflowPrompt,dr as buildGoalContextItem,cv as buildGoalSlashHelpText,ur as buildObjectiveUpdatedPrompt,xx as buildResumeNarration,Mf as buildSkillsPrompt,sm as buildSubagentAnnounceMessage,Gm as buildSystemPrompt,ux as cleanupOldSubagentRecords,Oe as clearPendingHitl,_b as clearPendingUiTool,j as collapseLogPath,wr as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,vr as continuationTurnHadMeaningfulOutput,_a as createAgentDefinitionsContext,bm as createAgentTools,sd as createApplyPatchTool,qp as createAutoSkillCategoriesTool,Jp as createAutoSkillListTool,Yp as createAutoSkillSearchTool,Xp as createAutoSkillViewTool,Ai as createAutoSkillsLoader,Hu as createBashTool,dm as createBatchSubagentSpawnTool,de as createBuiltinMemoryProvider,Tu as createContextManager,Qu as createEditFileTool,Lu as createExecTool,_m as createImageTool,ed as createListDirTool,Ld as createMemoryAppendTool,Zd as createMemoryForgetTool,Fd as createMemoryGetTool,Yd as createMemoryListTool,qd as createMemoryLogTool,Nd as createMemorySearchTool,$d as createMemoryUpdateTool,zd as createMemoryWriteTool,we as createPendingHitl,hb as createPendingUiTool,Ia as createPluginProgressEmitter,Wy as createPluginRuntime,Vu as createProcessTool,Ju as createReadFileTool,T as createSession,Ql as createSessionContextStore,tf as createSessionSearchTool,If as createSkillListTool,Lf as createSkillLoadTool,um as createSubagentSpawnTool,hm as createSubagentsTool,ym as createUiTool,Xu as createWriteFileTool,N as cronExecutionsPath,vm as defaultUiToolInputSchema,ae as deleteGoal,xn as deleteGoalWorkflow,jd as deleteMemoryFile,Fy as discoverAIMaxPlugins,Gv as emitGoalUpdatedProgress,ax as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,zt as extractWorkflowPlanFromObjective,Ta as filterSkillsForAgent,Ea as filterToolsForAgent,Sa as findAgentDefinition,kf as findSkillByName,wt as flushAccounting,vx as formatApprovalResolution,yx as formatClarifyResolution,bx as formatReviewResolution,K_ as generateSessionTitle,Ie as getAgentConfig,Dd as getMemoryLines,nb as getPluginSystem,pn as goalArtifactsDir,V as goalDir,R as goalEventsPath,ie as goalObjectiveMdPath,ne as goalPath,fn as goalWorkflowPlanPath,dn as goalWorkflowStatePath,tx as hasBootstrapSentinel,Se as hitlHistoryPath,Sn as initializeGoalWorkflow,rb as initializePluginSystem,rx as inspectBootstrapMountLayout,k as inspectSession,kr as installClarifyFirstTurnGate,ix as isBootstrapMountLayoutReady,Dr as isClarifyFirstTurnBlockedTool,Er as isClarifyWorkflowTask,gr as isContinuationEnabled,fr as isGoalContext,vo as isHitlPauseSignal,bo as isUiToolPauseSignal,Ae as listAgents,Cv as listAvailableSlashCommands,Be as listBindings,Cd as listMemoryFiles,E as listSessionSummaries,x as listSessions,lx as listSubagentRunsFromDisk,ba as loadAgentDefinitionsFromDir,He as loadAgentsConfig,b as loadArtifactOperations,Db as loadBootstrapFiles,m as loadCronExecutionRecords,De as loadPendingHitl,De as readPendingHitl,mb as loadPendingUiTool,mb as readPendingUiTool,By as loadPluginManifest,Vy as loadPluginManifestRegistry,Yy as loadPlugins,ee as loadSessionContextSnapshot,js as loadSessionExportSnapshots,I as loadSessionMetadata,jf as loadSkillView,Ef as loadSkills,Of as loadSkillsFromDirs,Df as loadSkillsWithPluginDirs,sx as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,F as loadTranscript,hr as loadWorkflowPromptContext,yr as maybeContinueGoalIfIdle,yd as memoryDir,f as metadataPath,re as mirrorGoalStatusToSession,je as normalizeAgentId,dy as normalizePluginsConfig,t as normalizeSessionStoreName,xa as parseAgentDefinition,xe as pendingHitlPath,fb as pendingUiToolPath,As as persistSessionExportSnapshots,tb as preloadPluginSystem,Sr as prependFirstGoalWorkflowSteeringIfNeeded,Cr as prependObjectiveUpdatedSteeringIfNeeded,bd as primaryMemoryPath,wa as publicAgentDefinitions,H as readGoal,_n as readGoalWorkflowState,yn as readGoalWorkflowSummary,Te as readHitlHistory,wd as readMemoryFile,Td as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,xr as recoverBlockedWorkflowOnUserTurn,le as registerEmbeddingProvider,_e as registerMemoryProvider,Le as removeAgent,We as removeBindings,Ht as renderGoalPlanMarkdown,vn as repairGoalWorkflowState,Ad as replaceMemoryFile,se as resetEmbeddingProviderRegistryForTests,ve as resetMemoryProviderRegistryForTests,ya as resolveAgentDefinitionsContext,Me as resolveAgentDir,Ne as resolveAgentIdByBinding,Ve as resolveAgentsConfigPath,Re as resolveDefaultAgentId,fe as resolveEmbeddingProvider,z as resolveGoalObjective,bn as resolveGoalToolWorkflowView,hx as resolveHitlRequest,hx as resolvePendingHitl,ge as resolveMemoryProvider,Fe as resolveModelFallbacks,Pe as resolveModelString,gb as resolvePendingUiTool,zy as resolvePluginManifestPath,P as rewriteTranscript,Gb as runAgent,ke as saveAgentsConfig,p as saveSessionMetadata,cx as saveSubagentRegistryToDisk,ga as scanAgentDefinitions,Ed as searchMemory,Os as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,Ds as sessionToolsSnapshotPath,e as sessionsDir,_r as shouldContinueGoal,bf as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,Ce as transitionHitlStatus,Ge as updateAgent,Ke as updateAgentIdentity,B as updateGoal,u as updateSessionMetadata,fy as validatePluginsConfig,mx as validateResume,un as withGoalWorkflowLock,Ym as wrapToolsWithHooks,oe as writeGoal,L as writeSessionFile};
457
+ `))}export{Fi as AutoSkillsLoader,xx as BOOTSTRAP_FILE_NAMES,yx as BOOTSTRAP_MAX_CHARS,bx as BOOTSTRAP_TOTAL_MAX_CHARS,Ot as CLARIFY_ACCEPTANCE_TEXT,Or as CLARIFY_FIRST_TURN_BLOCKED_TOOLS,Dt as CLARIFY_TASK_TITLE,_r as ContinuationState,ln as CorruptGoalWorkflowStateError,M as DEFAULT_SESSION_STORE_NAME,gr as ENV_GOAL_CONTINUATION,lr as FIRST_TURN_GOAL_WORKFLOW_INTRO,ry as GOAL_MULTILINE_TEMPLATE_EXAMPLE,on as GOAL_WORKFLOW_STATE_VERSION,Tt as GoalAccounting,fS as GoalConflictError,_S as HITL_MESSAGES,ts as HitlPauseSignal,D as MAX_ARTIFACT_CONTENT_CHARS,Lm as MAX_CHILDREN_PER_SESSION,Im as MAX_SUBAGENT_DEPTH,se as MemoryIndexManager,Nb as PLUGIN_MANIFEST_FILENAME,Pb as PLUGIN_MANIFEST_FILENAMES,Va as PluginHookRegistry,kh as PluginToolRegistry,ga as SYSTEM_AGENTS_DIR,Rm as SubagentRegistry,rs as UiToolPauseSignal,Ge as addAgent,Ve as addBinding,va as agentDirCandidates,Ea as agentVisibility,Sx as aimaxDir,A as appendArtifactOperation,S as appendCronExecutionRecord,te as appendGoalEvent,gf as appendRecentToMemory,i as appendSessionFile,hf as appendToMemory,h as appendTranscriptEntry,mS as applyCliGoalBeforeRun,vS as approvalSummaryFromResolution,O as artifactsPath,a as atomicWriteSessionFile,hi as autoSkillsDir,sS as bootstrapMountLayout,Aa as buildAgentDelegationPrompt,ja as buildAgentTaskPrompt,ay as buildAimaxGoalCliHelpExtra,Ex as buildBootstrapContextFiles,fr as buildBudgetLimitPrompt,dr as buildContinuationPrompt,ur as buildFirstTurnGoalWorkflowPrompt,mr as buildGoalContextItem,iy as buildGoalSlashHelpText,pr as buildObjectiveUpdatedPrompt,SS as buildResumeNarration,vp as buildSkillsPrompt,Hm as buildSubagentAnnounceMessage,Dh as buildSystemPrompt,dS as cleanupOldSubagentRecords,Ae as clearPendingHitl,px as clearPendingUiTool,j as collapseLogPath,Dr as confirmObjectiveUpdatedSteeringConsumed,_ as contextSnapshotPath,xr as continuationTurnHadMeaningfulOutput,ba as createAgentDefinitionsContext,th as createAgentTools,qd as createApplyPatchTool,km as createAutoSkillCategoriesTool,Am as createAutoSkillListTool,jm as createAutoSkillSearchTool,Mm as createAutoSkillViewTool,Ni as createAutoSkillsLoader,Od as createBashTool,Km as createBatchSubagentSpawnTool,ve as createBuiltinMemoryProvider,dd as createContextManager,ye as createDefaultMemoryProvider,Rd as createEditFileTool,Cd as createExecTool,Qm as createImageTool,Bd as createListDirTool,wf as createMemoryAppendTool,Rf as createMemoryForgetTool,Sf as createMemoryGetTool,If as createMemoryListTool,Pf as createMemoryLogTool,bf as createMemorySearchTool,Bf as createMemoryUpdateTool,Ef as createMemoryWriteTool,Ee as createPendingHitl,dx as createPendingUiTool,za as createPluginProgressEmitter,Bb as createPluginRuntime,Dd as createProcessTool,Pd as createReadFileTool,T as createSession,Iu as createSessionContextStore,Hf as createSessionSearchTool,Sp as createSkillListTool,Cp as createSkillLoadTool,Gm as createSubagentSpawnTool,Xm as createSubagentsTool,eh as createUiTool,Id as createWriteFileTool,N as cronExecutionsPath,$m as defaultUiToolInputSchema,ae as deleteGoal,Cn as deleteGoalWorkflow,vf as deleteMemoryFile,jb as discoverAIMaxPlugins,Vy as emitGoalUpdatedProgress,oS as ensureBootstrapMountLayout,v as ensureSession,y as exportSession,Vt as extractWorkflowPlanFromObjective,Oa as filterSkillsForAgent,ka as filterToolsForAgent,Ta as findAgentDefinition,hp as findSkillByName,Et as flushAccounting,yS as formatApprovalResolution,bS as formatClarifyResolution,xS as formatReviewResolution,Rv as generateSessionTitle,Re as getAgentConfig,mf as getMemoryLines,Qb as getPluginSystem,hn as goalArtifactsDir,ne as goalDir,R as goalEventsPath,ie as goalObjectiveMdPath,B as goalPath,mn as goalWorkflowPlanPath,pn as goalWorkflowStatePath,nS as hasBootstrapSentinel,we as hitlHistoryPath,wn as initializeGoalWorkflow,$b as initializePluginSystem,iS as inspectBootstrapMountLayout,k as inspectSession,Mr as installClarifyFirstTurnGate,aS as isBootstrapMountLayoutReady,Ar as isClarifyFirstTurnBlockedTool,kr as isClarifyWorkflowTask,yr as isContinuationEnabled,hr as isGoalContext,ns as isHitlPauseSignal,is as isUiToolPauseSignal,Me as listAgents,yy as listAvailableSlashCommands,He as listBindings,uf as listMemoryFiles,E as listSessionSummaries,x as listSessions,uS as listSubagentRunsFromDisk,Ca as loadAgentDefinitionsFromDir,We as loadAgentsConfig,b as loadArtifactOperations,Cx as loadBootstrapFiles,m as loadCronExecutionRecords,ke as loadPendingHitl,ke as readPendingHitl,ux as loadPendingUiTool,ux as readPendingUiTool,Ib as loadPluginManifest,Lb as loadPluginManifestRegistry,Gb as loadPlugins,P as loadSessionContextSnapshot,hc as loadSessionExportSnapshots,I as loadSessionMetadata,_p as loadSkillView,fp as loadSkills,mp as loadSkillsFromDirs,pp as loadSkillsWithPluginDirs,cS as loadSubagentRegistryFromDisk,g as loadSystemPromptSnapshot,F as loadTranscript,vr as loadWorkflowPromptContext,Sr as maybeContinueGoalIfIdle,of as memoryDir,f as metadataPath,re as mirrorGoalStatusToSession,Ne as normalizeAgentId,sb as normalizePluginsConfig,t as normalizeSessionStoreName,wa as parseAgentDefinition,Ce as pendingHitlPath,cx as pendingUiToolPath,mc as persistSessionExportSnapshots,Zb as preloadPluginSystem,Tr as prependFirstGoalWorkflowSteeringIfNeeded,Er as prependObjectiveUpdatedSteeringIfNeeded,sf as primaryMemoryPath,Da as publicAgentDefinitions,H as readGoal,yn as readGoalWorkflowState,xn as readGoalWorkflowSummary,De as readHitlHistory,df as readMemoryFile,ff as readPrimaryMemory,o as readSessionFile,d as readSessionFileContent,wr as recoverBlockedWorkflowOnUserTurn,be as registerEmbeddingProvider,fe as registerMemoryProvider,ze as removeAgent,Ke as removeBindings,Wt as renderGoalPlanMarkdown,bn as repairGoalWorkflowState,_f as replaceMemoryFile,ce as resetEmbeddingProviderRegistryForTests,oe as resetMemoryProviderRegistryForTests,Sa as resolveAgentDefinitionsContext,Pe as resolveAgentDir,Fe as resolveAgentIdByBinding,Ue as resolveAgentsConfigPath,Be as resolveDefaultAgentId,le as resolveEmbeddingProvider,z as resolveGoalObjective,Sn as resolveGoalToolWorkflowView,gS as resolveHitlRequest,gS as resolvePendingHitl,he as resolveMemoryProvider,_e as resolveMemoryProviderOrDefault,Le as resolveModelFallbacks,Ie as resolveModelString,fx as resolvePendingUiTool,Fb as resolvePluginManifestPath,ee as rewriteTranscript,Kx as runAgent,je as saveAgentsConfig,p as saveSessionMetadata,lS as saveSubagentRegistryToDisk,ya as scanAgentDefinitions,pf as searchMemory,fc as serializeToolsForSnapshot,r as sessionDir,l as sessionMemoryPath,dc as sessionToolsSnapshotPath,e as sessionsDir,br as shouldContinueGoal,op as skillsDir,C as systemPromptSnapshotPath,s as toolResultsDir,c as transcriptPath,Te as transitionHitlStatus,qe as updateAgent,Je as updateAgentIdentity,V as updateGoal,u as updateSessionMetadata,cb as validatePluginsConfig,hS as validateResume,fn as withGoalWorkflowLock,jh as wrapToolsWithHooks,U as writeGoal,L as writeSessionFile};